-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathlocal_runner.go
More file actions
1363 lines (1168 loc) · 37.4 KB
/
local_runner.go
File metadata and controls
1363 lines (1168 loc) · 37.4 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package playground
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"maps"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"syscall"
"text/template"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/ethereum/go-ethereum/log"
"github.com/flashbots/builder-playground/utils"
"github.com/flashbots/builder-playground/utils/mainctx"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
)
const (
defaultNetworkName = "ethplayground"
stopGracePeriodSecs = 30
)
// LocalRunner is a component that runs the services from the manifest on the local host machine.
// By default, it uses docker and docker compose to run all the services.
// But, some services (if they are configured to do so) can be run on the host machine instead.
// When running inside docker, each service will use the port numbers they define in the component description.
// Besides, they will also bind to an available public port on the host machine.
// If the service runs on the host, it will use the host port numbers instead directly.
type LocalRunner struct {
config *RunnerConfig
out *output
manifest *Manifest
client *client.Client
// reservedPorts is a map of port numbers reserved for each service to avoid conflicts
// since we reserve ports for all the services before they are used
reservedPorts map[int]bool
// handles stores the references to the processes that are running on host machine
// they are executed sequentially so we do not need to lock the handles
handles []*exec.Cmd
handlesMu sync.Mutex
// lifecycleServices tracks services with lifecycle configs for stop command execution
lifecycleServices []*lifecycleServiceInfo
lifecycleMu sync.Mutex
// exitError signals when one of the services fails
exitErr chan error
exitErrOnce sync.Once
// tasks tracks the status of each service
tasksMtx sync.Mutex
tasks map[string]*task
allTasksReadyCh chan struct{}
}
type task struct {
status TaskStatus
ready bool
logs *os.File
}
type TaskStatus string
var (
TaskStatusPulling TaskStatus = "pulling"
TaskStatusPulled TaskStatus = "pulled"
TaskStatusPending TaskStatus = "pending"
TaskStatusStarted TaskStatus = "started"
TaskStatusDie TaskStatus = "die"
TaskStatusHealthy TaskStatus = "healthy"
TaskStatusUnhealty TaskStatus = "unhealthy"
)
func newDockerClient() (*client.Client, error) {
client, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, fmt.Errorf("failed to create docker client: %w", err)
}
return client, nil
}
type RunnerConfig struct {
Out *output
Manifest *Manifest
BindHostPortsLocally bool
NetworkName string
Labels map[string]string
LogInternally bool
Platform string
Callbacks []Callback
}
func (r *RunnerConfig) AddCallback(c Callback) {
if r.Callbacks == nil {
r.Callbacks = append(r.Callbacks, c)
}
}
type Callback func(serviceName string, update TaskStatus)
func NewLocalRunner(cfg *RunnerConfig) (*LocalRunner, error) {
client, err := newDockerClient()
if err != nil {
return nil, fmt.Errorf("failed to create docker client: %w", err)
}
// download any local release artifacts for the services that require them
// TODO: it feels a bit weird to have all this logic on the new command. We should split it later on.
for _, service := range cfg.Manifest.Services {
if service.Labels[useHostExecutionLabel] == "true" {
// If HostPath is already set, use it directly (user-provided binary path)
if service.HostPath != "" {
continue
}
// If LifecycleHooks is set, no binary path needed - commands are shell commands
if service.LifecycleHooks {
continue
}
// Otherwise, download the release artifact
releaseArtifact := service.release
if releaseArtifact == nil {
return nil, fmt.Errorf("service '%s' requires either host_path, release, or lifecycle configuration", service.Name)
}
bin, err := DownloadRelease(cfg.Out.homeDir, releaseArtifact)
if err != nil {
return nil, fmt.Errorf("failed to download release artifact for service '%s': %w", service.Name, err)
}
service.HostPath = bin
}
}
tasks := map[string]*task{}
for _, service := range cfg.Manifest.Services {
var logs *os.File
if cfg.LogInternally {
if logs, err = cfg.Out.LogOutput(service.Name); err != nil {
return nil, fmt.Errorf("error getting log output: %w", err)
}
}
tasks[service.Name] = &task{
status: TaskStatusPending,
logs: logs,
}
}
if cfg.NetworkName == "" {
cfg.NetworkName = defaultNetworkName
}
if cfg.Callbacks == nil {
cfg.Callbacks = []Callback{func(serviceName string, update TaskStatus) {}} // noop
}
d := &LocalRunner{
config: cfg,
out: cfg.Out,
manifest: cfg.Manifest,
client: client,
reservedPorts: map[int]bool{},
handles: []*exec.Cmd{},
tasks: tasks,
allTasksReadyCh: make(chan struct{}),
exitErr: make(chan error, 2),
}
return d, nil
}
func (d *LocalRunner) checkAndUpdateReadiness() {
for name, task := range d.tasks {
// ensure the task is a docker service
if !d.isDockerService(name) {
continue
}
// first ensure the task has started
if task.status != TaskStatusStarted {
return
}
// then ensure it is ready if it has a ready function
svc := d.getService(name)
if svc.ReadyCheck != nil {
if !task.ready {
return
}
}
}
select {
case <-d.allTasksReadyCh:
// Channel is already closed, do nothing
default:
// Channel is not closed yet, close it
close(d.allTasksReadyCh)
}
}
func (d *LocalRunner) WaitForReady(ctx context.Context) error {
defer utils.StartTimer("docker.wait-for-ready")()
select {
case <-ctx.Done():
return ctx.Err()
case <-d.allTasksReadyCh:
return nil
case err := <-d.exitErr:
return err
}
}
func (d *LocalRunner) emitCallback(name string, status TaskStatus) {
for _, callback := range d.config.Callbacks {
callback(name, status)
}
}
func (d *LocalRunner) updateTaskStatus(name string, status TaskStatus) {
d.tasksMtx.Lock()
defer d.tasksMtx.Unlock()
if status == TaskStatusHealthy {
d.tasks[name].ready = true
} else if status == TaskStatusUnhealty {
d.tasks[name].ready = false
} else {
d.tasks[name].status = status
}
if status == TaskStatusDie {
d.sendExitError(fmt.Errorf("container %s failed", name))
}
d.emitCallback(name, status)
d.checkAndUpdateReadiness()
}
func (d *LocalRunner) ExitErr() <-chan error {
return d.exitErr
}
func (d *LocalRunner) sendExitError(err error) {
d.exitErrOnce.Do(func() {
d.exitErr <- err
close(d.exitErr)
})
}
func (d *LocalRunner) Stop(keepResources bool) error {
forceKillCtx, cancel := context.WithCancel(context.Background())
defer cancel()
// Keep an eye on the force kill requests.
go func(ctx context.Context) {
select {
case <-ctx.Done():
return
case <-mainctx.GetForceKillCtx().Done():
d.stopAllProcessesWithSignal(os.Kill)
ForceKillSession(d.manifest.ID, keepResources)
}
}(forceKillCtx)
// Kill all the processes ran by playground on the host.
// Possible to make a more graceful exit with os.Interrupt here
// but preferring a quick exit for now.
d.stopAllProcessesWithSignal(os.Kill)
// Run lifecycle stop commands for all tracked lifecycle services
d.runAllLifecycleStopCommands()
return StopSession(d.manifest.ID, keepResources)
}
func (d *LocalRunner) stopAllProcessesWithSignal(signal os.Signal) {
d.handlesMu.Lock()
defer d.handlesMu.Unlock()
for _, handle := range d.handles {
stopProcessWithSignal(handle, signal)
}
}
// stopProcessWithSignal waits for the process to be set in the handle
// and avoids a panic, with a hard timeout.
func stopProcessWithSignal(handle *exec.Cmd, signal os.Signal) {
ticker := time.NewTicker(time.Millisecond * 200)
defer ticker.Stop()
timeout := time.After(time.Second * 5)
for {
select {
case <-ticker.C:
if handle.Process != nil {
handle.Process.Signal(signal)
return
}
case <-timeout:
return
}
}
}
func StopSession(id string, keepResources bool) error {
// stop the docker-compose
args := []string{"compose", "-p", id}
if keepResources {
args = append(args, "stop")
} else {
args = append(args, "down", "-v") // removes containers and volumes
}
cmd := exec.CommandContext(context.Background(), "docker", args...)
// Isolate terminal signals from the child process and avoid weird force-kill cases
// and leftovers.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
var outBuf bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &outBuf
if err := cmd.Run(); err != nil {
return fmt.Errorf("error taking docker-compose down: %w\n%s", err, outBuf.String())
}
return nil
}
// ForceKillSession stops all containers for a session with a short grace period (SIGTERM, wait, SIGKILL)
func ForceKillSession(id string, keepResources bool) {
cmd := exec.Command("sh", "-c",
fmt.Sprintf("docker ps -q --filter label=playground.session=%s | xargs -r docker stop -s SIGKILL", id))
_ = cmd.Run()
}
func GetLocalSessions() ([]string, error) {
var sessions []string
client, err := newDockerClient()
if err != nil {
return nil, err
}
containers, err := client.ContainerList(context.Background(), container.ListOptions{
All: true,
})
if err != nil {
return nil, err
}
for _, container := range containers {
if container.Labels["playground"] == "true" {
sessions = append(sessions, container.Labels["playground.session"])
}
}
// Return sorted unique occurences
slices.Sort(sessions)
return slices.Compact(sessions), nil
}
func GetSessionServices(session string) ([]string, error) {
client, err := newDockerClient()
if err != nil {
return nil, err
}
containers, err := client.ContainerList(context.Background(), container.ListOptions{
All: true,
})
if err != nil {
return nil, err
}
var serviceNames []string
for _, container := range containers {
if container.Labels["playground"] == "true" && container.Labels["playground.session"] == session {
serviceNames = append(serviceNames, container.Labels["com.docker.compose.service"])
}
}
return serviceNames, nil
}
// reservePort finds the first available port from the startPort and reserves it
// Note that we have to keep track of the port in 'reservedPorts' because
// the port allocation happens before the services uses it and binds to it.
func (d *LocalRunner) reservePort(startPort int, protocol string) int {
for i := startPort; i < startPort+1000; i++ {
if _, ok := d.reservedPorts[i]; ok {
continue
}
bindAddr := "0.0.0.0"
if d.config.BindHostPortsLocally {
bindAddr = "127.0.0.1"
}
if protocol == ProtocolUDP {
listener, err := net.ListenUDP("udp", &net.UDPAddr{
Port: i,
IP: net.ParseIP(bindAddr),
})
if err != nil {
continue
}
listener.Close()
} else if protocol == ProtocolTCP {
listener, err := net.Listen(protocol, fmt.Sprintf("%s:%d", bindAddr, i))
if err != nil {
continue
}
listener.Close()
} else {
panic(fmt.Sprintf("invalid protocol: %s", protocol))
}
d.reservedPorts[i] = true
return i
}
panic("BUG: could not reserve a port")
}
func (d *LocalRunner) getService(name string) *Service {
for _, svc := range d.manifest.Services {
if svc.Name == name {
return svc
}
}
return nil
}
// applyTemplate resolves the templates from the manifest (Dir, Port, Connect) into
// the actual values for this specific docker execution.
func (d *LocalRunner) applyTemplate(s *Service) ([]string, map[string]string, error) {
var input map[string]interface{}
resolvePort := func(name string, defaultPort int, protocol string) int {
// For {{Port "name" "defaultPort"}}:
// - Service runs on host: return the host port
// - Service runs inside docker: return the docker port
if d.isHostService(s.Name) {
return s.MustGetPort(name).HostPort
}
return defaultPort
}
resolveAddr := func(targetSvc *Service, port *Port, protocol, user string) string {
// - Service runs on host:
// A: target is inside docker: access with localhost:hostPort
// B: target is on the host: access with localhost:hostPort
// - Service runs inside docker:
// C: target is inside docker: access it with DNS service:port
// D: target is on the host: access it with host.docker.internal:hostPort
if d.isHostService(s.Name) {
// A and B
return printAddr(protocol, "localhost", port.HostPort, user)
} else {
if d.isHostService(targetSvc.Name) {
// D
return printAddr(protocol, "host.docker.internal", port.HostPort, user)
}
// C
return printAddr(protocol, targetSvc.Name, port.Port, user)
}
}
funcs := template.FuncMap{
"Service": func(name, portLabel, protocol, user string) string {
svc := d.manifest.MustGetService(name)
port := svc.MustGetPort(portLabel)
return resolveAddr(svc, port, protocol, user)
},
"Port": func(name string, defaultPort int) int {
return resolvePort(name, defaultPort, ProtocolTCP)
},
"PortUDP": func(name string, defaultPort int) int {
return resolvePort(name, defaultPort, ProtocolUDP)
},
"Bootnode": func() string {
if d.manifest.Bootnode == nil {
return ""
}
svc := d.manifest.MustGetService(d.manifest.Bootnode.Service)
port := svc.MustGetPort("rpc")
return resolveAddr(svc, port, "enode", d.manifest.Bootnode.ID)
},
}
runTemplate := func(arg string) (string, error) {
tpl, err := template.New("").Funcs(funcs).Parse(arg)
if err != nil {
return "", err
}
var out strings.Builder
if err := tpl.Execute(&out, input); err != nil {
return "", err
}
return out.String(), nil
}
// apply the templates to the arguments
var argsResult []string
for _, arg := range s.Args {
newArg, err := runTemplate(arg)
if err != nil {
return nil, nil, err
}
argsResult = append(argsResult, newArg)
}
// apply the templates to the environment variables
envs := map[string]string{}
for k, v := range s.Env {
newV, err := runTemplate(v)
if err != nil {
return nil, nil, err
}
envs[k] = newV
}
return argsResult, envs, nil
}
func printAddr(protocol, serviceName string, port int, user string) string {
var protocolPrefix string
if protocol != "" {
protocolPrefix = protocol + "://"
}
if user != "" {
return fmt.Sprintf("%s%s@%s:%d", protocolPrefix, user, serviceName, port)
}
return fmt.Sprintf("%s%s:%d", protocolPrefix, serviceName, port)
}
func (d *LocalRunner) validateImageExists(image string) error {
// check locally
_, err := d.client.ImageInspect(context.Background(), image)
if err == nil {
return nil
}
if !client.IsErrNotFound(err) {
return err
}
// check remotely
if _, err = d.client.DistributionInspect(context.Background(), image, ""); err == nil {
return nil
}
if !client.IsErrNotFound(err) {
return err
}
return fmt.Errorf("image %s not found", image)
}
func (d *LocalRunner) toDockerComposeService(s *Service) (map[string]interface{}, []string, error) {
// apply the template again on the arguments to figure out the connections
// at this point all of them are valid, we just have to resolve them again. We assume for now
// everyone is going to be on docker at the same network.
args, envs, err := d.applyTemplate(s)
if err != nil {
return nil, nil, fmt.Errorf("failed to apply template, err: %w", err)
}
// The containers have access to the full set of artifacts on the /artifacts folder
// so, we have to bind it as a volume on the container.
outputFolder := d.out.Dst()
// Validate that the image exists
imageName := fmt.Sprintf("%s:%s", s.Image, s.Tag)
if err := d.validateImageExists(imageName); err != nil {
return nil, nil, fmt.Errorf("failed to validate image %s: %w", imageName, err)
}
labels := map[string]string{
// It is important to use the playground label to identify the containers
// during the cleanup process
"playground": "true",
"playground.session": d.manifest.ID,
"service": s.Name,
}
// apply the user defined labels
maps.Copy(labels, d.config.Labels)
// add the local ports exposed by the service as labels
// we have to do this for now since we do not store the manifest in JSON yet.
// Otherwise, we could use that directly
for _, port := range s.Ports {
labels[fmt.Sprintf("port.%s", port.Name)] = fmt.Sprintf("%d", port.Port)
}
// Use files mapped to figure out which files from the artifacts is using the service
volumes := map[string]string{
outputFolder: "/artifacts", // placeholder
}
for k, v := range s.FilesMapped {
volumes[filepath.Join(outputFolder, v)] = k
}
// create the bind volumes
var createdVolumes []string
for localPath, volume := range s.VolumesMapped {
dockerVolumeName := d.createVolumeName(s.Name, volume.Name)
if volume.IsLocal {
absPath := utils.MustGetVolumeDir(d.manifest.ID, dockerVolumeName)
volumes[absPath] = localPath
} else {
volumes[dockerVolumeName] = localPath
createdVolumes = append(createdVolumes, dockerVolumeName)
}
}
volumesInLine := []string{}
for k, v := range volumes {
volumesInLine = append(volumesInLine, fmt.Sprintf("%s:%s", k, v))
}
// add the ports to the labels as well
service := map[string]interface{}{
"image": imageName,
"command": args,
// Add volume mount for the output directory
"volumes": volumesInLine,
// Add the ethereum network
"networks": []string{d.config.NetworkName},
"labels": labels,
"stop_grace_period": fmt.Sprintf("%ds", stopGracePeriodSecs),
}
if d.config.Platform != "" {
service["platform"] = d.config.Platform
}
if len(envs) > 0 {
service["environment"] = envs
}
if s.ReadyCheck != nil {
if s.ReadyCheck.Test == nil {
return nil, nil, fmt.Errorf("ready check for service %s must define either Test or QueryURL", s.Name)
}
service["healthcheck"] = map[string]interface{}{
"test": s.ReadyCheck.Test,
"interval": s.ReadyCheck.Interval.String(),
"timeout": s.ReadyCheck.Timeout.String(),
"retries": s.ReadyCheck.Retries,
"start_period": s.ReadyCheck.StartPeriod.String(),
}
}
if s.UngracefulShutdown {
service["stop_grace_period"] = "0s"
}
if s.DependsOn != nil {
depends := map[string]interface{}{}
for _, d := range s.DependsOn {
if d.Condition == "" {
depends[d.Name] = struct{}{}
} else {
depends[d.Name] = map[string]interface{}{
"condition": d.Condition,
}
}
}
service["depends_on"] = depends
}
if runtime.GOOS == "linux" {
// We rely on host.docker.internal as the DNS address for the host inside
// the container. But, this is only available on Macos and Windows.
// On Linux, you can use the IP address 172.17.0.1 to access the host.
// Thus, if we are running on Linux, we need to add an extra host entry.
service["extra_hosts"] = map[string]string{
"host.docker.internal": "172.17.0.1",
}
}
if s.Entrypoint != "" {
service["entrypoint"] = s.Entrypoint
}
if len(s.Ports) > 0 {
ports := []string{}
for _, p := range s.Ports {
protocol := ""
if p.Protocol == ProtocolUDP {
protocol = "/udp"
}
if d.config.BindHostPortsLocally {
ports = append(ports, fmt.Sprintf("127.0.0.1:%d:%d%s", p.HostPort, p.Port, protocol))
} else {
ports = append(ports, fmt.Sprintf("%d:%d%s", p.HostPort, p.Port, protocol))
}
}
service["ports"] = ports
}
return service, createdVolumes, nil
}
func (d *LocalRunner) isHostService(name string) bool {
return d.manifest.MustGetService(name).HostPath != ""
}
// isDockerService returns true if the service should run in Docker.
// Services with HostPath or LifecycleHooks run on the host, not in Docker.
func (d *LocalRunner) isDockerService(name string) bool {
svc := d.manifest.MustGetService(name)
return svc.HostPath == "" && !svc.LifecycleHooks
}
func (d *LocalRunner) generateDockerCompose() ([]byte, error) {
compose := map[string]interface{}{
// We create a new network to be used by all the services so that
// we can do DNS discovery between them.
"networks": map[string]interface{}{
d.config.NetworkName: map[string]interface{}{
"name": d.config.NetworkName,
},
},
}
services := map[string]interface{}{}
// for each service, reserve a port on the host machine. We use this ports
// both to have access to the services from localhost but also to do communication
// between services running inside docker and the ones running on the host machine.
for _, svc := range d.manifest.Services {
for _, port := range svc.Ports {
port.HostPort = d.reservePort(port.Port, port.Protocol)
}
}
volumes := map[string]struct{}{}
for _, svc := range d.manifest.Services {
if !d.isDockerService(svc.Name) {
// skip services that run on host (HostPath or LifecycleHooks)
continue
}
var (
err error
dockerVolumes []string
)
services[svc.Name], dockerVolumes, err = d.toDockerComposeService(svc)
if err != nil {
return nil, fmt.Errorf("failed to convert service %s to docker compose service: %w", svc.Name, err)
}
for _, volumeName := range dockerVolumes {
volumes[volumeName] = struct{}{}
}
}
compose["services"] = services
compose["volumes"] = volumes
yamlData, err := yaml.Marshal(compose)
if err != nil {
return nil, fmt.Errorf("failed to marshal docker compose: %w", err)
}
return yamlData, nil
}
func (d *LocalRunner) createVolumeName(service, volumeName string) string {
// Check if this is a shared volume (prefixed with "shared:")
if strings.HasPrefix(volumeName, "shared:") {
// Shared volumes don't include service name prefix
return fmt.Sprintf("volume-%s", strings.TrimPrefix(volumeName, "shared:"))
}
return fmt.Sprintf("volume-%s-%s", service, volumeName)
}
func (d *LocalRunner) createVolumeDir(service, volumeName string) (string, error) {
// create the volume in the output folder
var dirName string
if strings.HasPrefix(volumeName, "shared:") {
dirName = fmt.Sprintf("volume-%s", strings.TrimPrefix(volumeName, "shared:"))
} else {
dirName = fmt.Sprintf("volume-%s-%s", service, volumeName)
}
volumeDirAbsPath, err := d.out.CreateDir(dirName)
if err != nil {
return "", fmt.Errorf("failed to create volume dir %s: %w", volumeName, err)
}
return volumeDirAbsPath, nil
}
// waitForDependencies waits for all dependencies of a host service to be healthy
func (d *LocalRunner) waitForDependencies(ss *Service) error {
if len(ss.DependsOn) == 0 {
return nil
}
for _, dep := range ss.DependsOn {
if dep.Condition != DependsOnConditionHealthy {
continue
}
// The dependency name might be a healthmon sidecar (e.g., "el_healthmon")
// We need to check the original service name
depName := dep.Name
originalName := strings.TrimSuffix(depName, "_healthmon")
// Check if the original service is a host service
if d.isHostService(originalName) {
depSvc := d.manifest.MustGetService(originalName)
// Determine the URL to check for health
var checkURL string
if depSvc.ReadyCheck != nil && depSvc.ReadyCheck.QueryURL != "" {
checkURL = depSvc.ReadyCheck.QueryURL
} else if httpPort, ok := depSvc.GetPort("http"); ok {
checkURL = fmt.Sprintf("http://localhost:%d", httpPort.HostPort)
} else {
return fmt.Errorf("host service %s has no ready_check or http port defined", originalName)
}
// Poll until the dependency is healthy
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
slog.Info("Waiting for host dependency", "service", ss.Name, "dependency", originalName)
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for %s to be healthy", originalName)
default:
}
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get(checkURL)
if err == nil {
resp.Body.Close()
if resp.StatusCode < 500 {
slog.Info("Dependency is healthy", "service", ss.Name, "dependency", originalName)
break
}
}
time.Sleep(1 * time.Second)
}
} else {
// For Docker services, check the healthmon container
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
slog.Info("Waiting for container dependency", "service", ss.Name, "dependency", depName)
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for %s to be healthy", depName)
default:
}
resp, err := ExecuteHealthCheckManually(depName)
if err == nil && resp.ExitCode == 0 {
slog.Info("Dependency is healthy", "service", ss.Name, "dependency", depName)
break
}
time.Sleep(1 * time.Second)
}
}
}
return nil
}
// runOnHost runs the service on the host machine
func (d *LocalRunner) runOnHost(ctx context.Context, ss *Service) error {
// If this service has lifecycle hooks, start with them
if ss.LifecycleHooks {
return d.startWithLifecycleHooks(ctx, ss)
}
// Wait for dependencies to be healthy before starting
if err := d.waitForDependencies(ss); err != nil {
return fmt.Errorf("failed waiting for dependencies: %w", err)
}
// TODO: Use env vars in host processes
args, _, err := d.applyTemplate(ss)
if err != nil {
return fmt.Errorf("failed to apply template, err: %w", err)
}
// Create the volumes for this service
volumesMapped := map[string]string{}
for pathInDocker, volume := range ss.VolumesMapped {
volumeDirAbsPath, err := d.createVolumeDir(ss.Name, volume.Name)
if err != nil {
return err
}
volumesMapped[pathInDocker] = volumeDirAbsPath
}
// We have to replace the names of the files it is using as artifacts for the full names
// Just a string replacement should be enough
for i, arg := range args {
// If any of the args contains any of the files mapped, we need to replace it
for pathInDocker, artifactName := range ss.FilesMapped {
if strings.Contains(arg, pathInDocker) {
args[i] = strings.ReplaceAll(arg, pathInDocker, filepath.Join(d.out.dst, artifactName))
}
}
// If any of the args contains any of the volumes mapped, we need to create
// the volume and replace it
for pathInDocker, volumeAbsPath := range volumesMapped {
if strings.Contains(arg, pathInDocker) {
args[i] = strings.ReplaceAll(arg, pathInDocker, volumeAbsPath)
}
}
}
execPath := ss.HostPath
cmd := exec.Command(execPath, args...)
cmd.Dir = d.out.dst // Run from artifacts directory so relative paths work
logOutput, err := d.out.LogOutput(ss.Name)
if err != nil {
// this should not happen, log it
logOutput = os.Stdout
}
logPath := logOutput.Name()
// Output the command itself to the log output for debugging purposes
cmdLine := execPath + " " + strings.Join(args, " ")
fmt.Fprint(logOutput, cmdLine+"\n\n")
cmd.Stdout = logOutput
cmd.Stderr = logOutput
go func() {
if err := cmd.Run(); err != nil {
// If the playground is being exited, ignore the exit error info
// to make the outputs less confusing.
if mainctx.IsExiting() {
return
}
// Read last lines from log file for context
lastLines := readLastLines(logPath, 10)
slog.Error("Host service failed", "service", ss.Name, "error", err)
errMsg := fmt.Sprintf("service %s failed:\n Command: %s\n Log file: %s\n Exit error: %v",
ss.Name, execPath, logPath, err)
if lastLines != "" {
errMsg += fmt.Sprintf("\n Last output:\n%s", lastLines)
}
d.sendExitError(fmt.Errorf("%s", errMsg))
}
}()
d.handlesMu.Lock()
defer d.handlesMu.Unlock()
d.handles = append(d.handles, cmd)
return nil
}
// trackLogs tracks the logs of a container and writes them to the log output
func (d *LocalRunner) trackLogs(serviceName, containerID string) error {
d.tasksMtx.Lock()
log_output := d.tasks[serviceName].logs
d.tasksMtx.Unlock()
if log_output == nil {
panic("BUG: log output not found for service " + serviceName)
}
logs, err := d.client.ContainerLogs(context.Background(), containerID, container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
})
if err != nil {
return fmt.Errorf("error getting container logs: %w", err)
}
if _, err := stdcopy.StdCopy(log_output, log_output, logs); err != nil {