@@ -22,12 +22,11 @@ func init() {
2222}
2323
2424type DockerAttachConnection struct {
25- conn * config.TaskConnection
26- log * zap.Logger
27- cli * client.Client
28- execCFG * container.ExecOptions
29- containerID string
30- ctx context.Context
25+ conn * config.TaskConnection
26+ log * zap.Logger
27+ cli * client.Client
28+ execCFG * container.ExecOptions
29+ ctx context.Context
3130}
3231
3332// NewDockerAttachConnection creates a new DockerAttachConnection instance.
@@ -66,33 +65,6 @@ func (d *DockerAttachConnection) Prepare(ctx context.Context, task *config.Task)
6665 d .log .Debug ("No explicit docker connection specified, using default: `unix:///var/run/docker.sock`" )
6766 d .conn .DockerConnection = "unix:///var/run/docker.sock"
6867 }
69- cid := d .conn .ContainerName
70- if cid == "" {
71- label := d .conn .ContainerLabel
72- if label == "" {
73- return errors .New ("neither container name nor label provided" )
74- }
75-
76- args := filters .NewArgs ()
77- args .Add ("label" , label )
78-
79- containers , err := d .cli .ContainerList (ctx , container.ListOptions {
80- Filters : args ,
81- })
82- if err != nil {
83- return err
84- }
85-
86- if len (containers ) == 0 {
87- return fmt .Errorf ("no container found with label %q" , label )
88- }
89-
90- if len (containers ) != 1 {
91- return fmt .Errorf ("more than one container found with label %q" , label )
92- }
93- cid = containers [0 ].ID
94- }
95- d .containerID = cid
9668 shell , shellArgs , environments := cmdCtx .BuildExecuteParams (task .Command )
9769 cmd := append (
9870 []string {shell },
@@ -135,8 +107,35 @@ func (d *DockerAttachConnection) Connect() error {
135107// - A byte slice containing the command output.
136108// - An error if the execution fails, otherwise nil.
137109func (d * DockerAttachConnection ) Execute () ([]byte , error ) {
110+ cid := d .conn .ContainerName
111+ if cid == "" {
112+ label := d .conn .ContainerLabel
113+ if label == "" {
114+ return nil , errors .New ("neither container name nor label provided" )
115+ }
116+
117+ args := filters .NewArgs ()
118+ args .Add ("label" , label )
119+
120+ containers , err := d .cli .ContainerList (d .ctx , container.ListOptions {
121+ Filters : args ,
122+ })
123+ if err != nil {
124+ return nil , err
125+ }
126+
127+ if len (containers ) == 0 {
128+ return nil , fmt .Errorf ("no container found with label %q" , label )
129+ }
130+
131+ if len (containers ) != 1 {
132+ return nil , fmt .Errorf ("more than one container found with label %q" , label )
133+ }
134+ cid = containers [0 ].ID
135+ }
136+
138137 // Create the exec instance
139- exec , err := d .cli .ContainerExecCreate (d .ctx , d . containerID , * d .execCFG )
138+ exec , err := d .cli .ContainerExecCreate (d .ctx , cid , * d .execCFG )
140139 if err != nil {
141140 return nil , err
142141 }
0 commit comments