-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvsd.go
522 lines (451 loc) · 14.7 KB
/
vsd.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package main
import (
"embed"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"regexp"
"strings"
"rsc.io/quote"
)
func run(msg string, cmd *exec.Cmd) {
fmt.Println(msg)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
if err := cmd.Run(); err != nil {
fmt.Println("Error:", err)
}
fmt.Println("")
}
// Sets up the shared Docker Compose network.
//
// Creates the named (attachable) network if it doesn't exist.
func setupNetwork(composeNetwork string) {
networks := exec.Command("docker", "network", "ls")
output, err := networks.Output()
if err != nil {
log.Println(err)
}
matches := regexp.MustCompile(composeNetwork).FindStringSubmatch(string(output))
if len(matches) >= 1 {
fmt.Printf("Docker network %s already exists, joining.\n", composeNetwork)
} else {
fmt.Println("Create user-defined network")
createNewnet := exec.Command("docker", "network", "create", "--driver", "bridge", "--attachable", composeNetwork)
if output, err := createNewnet.Output(); err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Otuput: %s\n", output)
}
}
}
func showHelp() {
fmt.Println("Help placeholder")
}
// Project .. Environment variables used by Docker Compose.
type Project struct {
// Path to Docker Compose specifications.
composeSpecs string
// Options passed to Docker Compose command.
composeOptions string
// Shared network name.
network string
// Path to source code directory, mounted into containers.
source string
// Name of current directory, used for service aliases.
name string
// Expected input by the php-fpm service, tells XDebug address where to find IDE.
// php-fpm service located in docker-compose.vsd.yml file.
// https://www.reddit.com/r/bashonubuntuonwindows/comments/c871g7/command_to_get_virtual_machine_ip_in_wsl2/
xdebug string
// Name the shared services.
sharedServices []string
// Name the project services.
projectServices []string
}
//go:embed docker
var dockerfs embed.FS
func embedRead(filename string) []byte {
file, e := dockerfs.ReadFile(filename)
if e != nil {
panic(e)
}
return file
}
// Search destination for compose spec file, copies from source in embed filesystem into destination if not found.
func provideOverride(source string, destination string) {
if _, err := os.Stat(destination); os.IsNotExist(err) {
fmt.Printf("Required file %s not found, copying into %s \n", source, destination)
override := embedRead(source)
err := os.WriteFile(destination, override, 0744)
if err != nil {
panic(err)
}
} else {
fmt.Printf("Found requried file: %s \n", source)
}
}
// Gather information used by all sub-commands.
func bootstrap() Project {
composeNetwork := `VSD`
// Provide shared services override, if not present already.
provideOverride("docker/docker-compose.override.yml", "docker-compose.override.yml")
composeOptsPtr := flag.String("options", "--file=docker-compose.override.yml", "Options passed to Docker Compose command (optional).")
flag.Parse()
projectSource, err := os.Getwd()
if err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("Your project location is %s\n", projectSource)
// https://stackoverflow.com/a/1371283
projectName, err := exec.Command("bash", "-c", "echo ${PWD##*/}").Output()
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Your project name is: %s", projectName)
}
xdebugHost, err := exec.Command("bash", "-c", `ip addr show eth0 | grep -oE '\d+(\.\d+){3}' | head -n 1`).Output()
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("XDebug will contact your Visual Studio Code IDE at %s\n", xdebugHost)
}
sshAuthSock := os.Getenv("SSH_AUTH_SOCK")
if sshAuthSock != "" {
fmt.Printf("Using SSH_AUTH_SOCK: %s\n", sshAuthSock)
} else {
log.Default().Println(`Missing environment variable: $SSH_AUTH_SOCK
*Interaction with Git and firewalled Packagist repositories may be limited*`)
}
sServices := []string{"mysql", "pma", "memcached"}
pServices := []string{"varnish", "nginx", "php-fpm"}
project := Project{
composeSpecs: "docker",
composeOptions: string(*composeOptsPtr),
network: composeNetwork,
source: projectSource,
name: strings.TrimSuffix(string(projectName), "\n"),
xdebug: string(xdebugHost),
sharedServices: sServices,
projectServices: pServices,
}
return project
}
func main() {
fmt.Println("WELCOME TO THE VSD ENVIRONMENT !!!")
fmt.Println("(V)isual Studio Code | (S)ubsystem4Linux | (D)ocker")
fmt.Println("")
if len(os.Args) < 1 {
showHelp()
os.Exit(0)
}
project := bootstrap()
setupNetwork(project.network)
// Set up environment variables for Docker Compose.
os.Setenv("COMPOSE_NETWORK", project.network)
os.Setenv("PROJECT_SOURCE", project.source)
os.Setenv("PROJECT_NAME", project.name)
os.Setenv("XDEBUG_REMOTE_HOST", project.xdebug)
os.Setenv("PROJECT_DEST", "/vsdroot")
subcommand := flag.Arg(0)
switch subcommand {
case "version":
print("VSD version 0.3.0\n")
case "status":
stackStatus(project)
case "start":
startShared(project)
startProject(project)
stackStatus(project)
case "down":
stackDown(project)
case "rec":
case "recreate":
stackDown(project)
// Recreate the network as well.
setupNetwork(project.network)
startShared(project)
startProject(project)
stackStatus(project)
case "show":
//@TODO: Create a mapping of services source ports, user should not need to specify them.
serviceShow(project)
case "open":
servicePort := serviceShow(project)
serviceOpen(servicePort)
case "logs":
serviceLog(project, flag.Arg(1))
case "drush":
serviceDrush(project, flag.Arg(1))
case "drush-bash":
serviceDrushBash(project, flag.Arg(1))
case "exec":
serviceExec(project, flag.Arg(1))
default:
showHelp()
}
fmt.Println(quote.Go())
}
// ComposeExec Docker Compose command specs.
type ComposeExec struct {
// Project name associated with Docker Compose.
project string
// Additional docker-compose options.
options string
// Embedded spec file to execute.
spec string
// Docker Compose command to execute.
command string
}
// Execute Docker Compose command using embedded spec.
//
// Only one embedded file is supported by --file /dev/stdin
//
// WARNING: dockerComposeEmbed() DOES NOT provide a pty/tty response.
//
// For pipe execution see https://golang.org/pkg/os/exec/#Cmd.StdinPipe.
func dockerComposeEmbed(compose ComposeExec) {
specFile := embedRead(compose.spec)
cmdString := fmt.Sprintf("docker-compose --project-name %s %s --file /dev/stdin %s", compose.project, compose.options, compose.command)
log.Default().Printf("Executing command:\n %s", cmdString)
cmd := exec.Command("bash", "-c", cmdString)
stdin, err := cmd.StdinPipe()
if err != nil {
fmt.Println("Error:", err)
}
go func() {
defer stdin.Close()
io.WriteString(stdin, string(specFile))
}()
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("%s\n", out)
}
// Run Docker Compose w/ interactive (tty) support.
func dockerComposeTTY(compose ComposeExec) {
cmdString := fmt.Sprintf(
"docker-compose --project-name %s %s %s",
compose.project,
compose.options,
compose.command,
)
log.Default().Printf("Executing command:\n %s", cmdString)
cmd := exec.Command("bash", "-c", cmdString)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Println("Error:", err)
}
}
// Show current stack status.
func stackStatus(project Project) {
fmt.Println("Shared services status")
dockerComposeEmbed(ComposeExec{
project: "localenv",
options: project.composeOptions,
spec: fmt.Sprintf("%s/docker-compose.shared.yml", project.composeSpecs),
command: "ps",
})
fmt.Println("Project services status")
dockerComposeEmbed(ComposeExec{
project: project.name,
options: "",
spec: fmt.Sprintf("%s/run/drupal/docker-compose.vsd.yml", project.composeSpecs),
command: "ps",
})
}
// Start compose service for current directory.
func startProject(project Project) {
fmt.Println("Start project services")
dockerComposeEmbed(ComposeExec{
project: project.name,
options: "",
spec: fmt.Sprintf("%s/run/drupal/docker-compose.vsd.yml", project.composeSpecs),
command: "up --detach",
})
}
// Fire up stack shared amongst all projects.
func startShared(project Project) {
fmt.Println("Start shared services")
dockerComposeEmbed(ComposeExec{
project: "localenv",
options: project.composeOptions,
spec: fmt.Sprintf("%s/docker-compose.shared.yml", project.composeSpecs),
command: "up --detach --no-recreate",
})
}
// Remove services, containers, and networks.
func stackDown(project Project) {
fmt.Println("Stop shared services")
dockerComposeEmbed(ComposeExec{
project: "localenv",
options: project.composeOptions,
spec: fmt.Sprintf("%s/docker-compose.shared.yml", project.composeSpecs),
command: "down --remove-orphans",
})
fmt.Println("Stop project servicess")
dockerComposeEmbed(ComposeExec{
project: project.name,
options: "",
spec: fmt.Sprintf("%s/run/drupal/docker-compose.vsd.yml", project.composeSpecs),
command: "down --remove-orphans",
})
run("Cleanup Docker containers",
exec.Command("docker", "system", "prune", "--force"))
run("Cleanup Docker network",
exec.Command("docker", "network", "rm", project.network))
}
// Show location of service port.
//
// Example: go run ./vsd.go show nginx 8080
func serviceShow(project Project) string {
// @TODO: Decouple domain-name for use with let's encrypt!
var service string
var port string
// Define default service to show.
var command string
if len(os.Args) >= 3 && os.Args[2] != "" && os.Args[3] != "" {
service = os.Args[2]
port = os.Args[3]
} else {
service = "nginx"
port = "8080"
}
fmt.Printf("Retrieving service %s @ %s\n", service, port)
// NOTE: Only shows project services, and not shared services!
command = fmt.Sprintf(`docker-compose --project-name="%s" \
--file %s/run/drupal/docker-compose.vsd.yml \
port %s %s | sed 's/0.0.0.0/%s/g'`,
strings.TrimSuffix(project.name, "\n"),
project.composeSpecs,
service,
port,
"localhost")
url := exec.Command("bash", "-c", command)
srvLocation, err := url.Output()
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Service %s is running at: %s\n", service, srvLocation)
}
return string(srvLocation)
}
// Open default browser to specified services' mapped port.
//
// Example: go run ./vsd.go open nginx 8080
//
// Resources:
// - https://ss64.com/nt/cmd.html
// - https://superuser.com/questions/1182275/how-to-use-start-command-in-bash-on-windows
// - https://github.com/microsoft/terminal/issues/204#issuecomment-696816617
func serviceOpen(servicePort string) {
format := fmt.Sprintf(`cmd.exe /c start chrome "http://%s" 2> /dev/null`, servicePort)
command := exec.Command("bash", "-c", format)
command.Stdout = os.Stdout
command.Stderr = os.Stdout
if err := command.Run(); err != nil {
fmt.Println("Error:", err)
}
}
// Fires up drush container into current PWD.
func serviceDrush(project Project, version string) {
fmt.Printf("Start container for drush %s\n", version)
// Copy embedded compose specs.
provideOverride("docker/docker-compose.shared.yml", "docker-compose.shared.yml")
provideOverride("docker/docker-compose.override.yml", "docker-compose.override.yml")
provideOverride("docker/run/drupal/docker-compose.vsd.yml", "docker-compose.vsd-go-drupal.yml")
provideOverride("docker/run/drush/docker-compose.vsd.yml", "docker-compose.vsd-go-drush.yml")
// Source specs from current PWD.
dockerComposeTTY(ComposeExec{
project: project.name,
options: `--file ./docker-compose.shared.yml \
--file ./docker-compose.override.yml \
--file ./docker-compose.vsd-go-drupal.yml \
--file ./docker-compose.vsd-go-drush.yml`,
command: fmt.Sprintf("run --entrypoint=ash --rm --user=nobody drush%s", version),
})
}
// TTY into Drush container using bash script.
func serviceDrushBash(project Project, version string) {
fmt.Printf("Start container for drush %s\n", version)
// Copy embedded compose specs.
provideOverride("docker/docker-compose.shared.yml", "docker-compose.shared.yml")
provideOverride("docker/docker-compose.override.yml", "docker-compose.override.yml")
provideOverride("docker/run/drupal/docker-compose.vsd.yml", "docker-compose.vsd-go-drupal.yml")
provideOverride("docker/run/drush/docker-compose.vsd.yml", "docker-compose.vsd-go-drush.yml")
provideOverride("docker/scripts/vsd-go-drush7.sh", "vsd-go-drush7.sh")
cmd := exec.Command("./vsd-go-drush7.sh")
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Println("Error:", err)
}
}
func contains(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
func serviceExec(project Project, service string) {
fmt.Printf("Running compose exec for service %s\n", service)
if contains(project.sharedServices, service) {
provideOverride("docker/docker-compose.shared.yml", "docker-compose.shared.yml")
provideOverride("docker/docker-compose.override.yml", "docker-compose.override.yml")
dockerComposeTTY(ComposeExec{
project: "localenv",
options: `--file ./docker-compose.shared.yml \
--file ./docker-compose.override.yml`,
command: fmt.Sprintf("exec --user=root %s ash", service),
})
}
if contains(project.projectServices, service) {
provideOverride("docker/run/drupal/docker-compose.vsd.yml", "docker-compose.vsd-go-drupal.yml")
dockerComposeTTY(ComposeExec{
project: project.name,
options: `--file ./docker-compose.vsd-go-drupal.yml`,
command: fmt.Sprintf("exec --user=root %s ash", service),
})
}
}
// Show service log.
func serviceLog(project Project, service string) {
if contains(project.sharedServices, service) {
serviceLogShared(project, service)
}
if contains(project.projectServices, service) {
serviceLogProject(project, service)
}
}
func serviceLogShared(project Project, service string) {
fmt.Printf("Show Docker log for shared service %s\n", service)
// Copy embedded compose specs.
provideOverride("docker/docker-compose.shared.yml", "docker-compose.shared.yml")
provideOverride("docker/docker-compose.override.yml", "docker-compose.override.yml")
// If you want to --follow the log, golang must allocate tty.
dockerComposeTTY(ComposeExec{
project: "localenv",
options: `--file ./docker-compose.shared.yml \
--file ./docker-compose.override.yml`,
command: fmt.Sprintf("logs --follow --tail=30 %s", service),
})
}
func serviceLogProject(project Project, service string) {
fmt.Printf("Show Docker log for project service %s\n", service)
// This log show example does not follow, therefore doesn't allocate tty.
dockerComposeEmbed(ComposeExec{
project: project.name,
options: "",
spec: fmt.Sprintf("%s/run/drupal/docker-compose.vsd.yml", project.composeSpecs),
command: fmt.Sprintf("logs --tail=30 %s", service),
})
}