Repository navigation
Expand file tree
/
Copy pathsession.go
More file actions
226 lines (209 loc) · 7.55 KB
/
Copy pathsession.go
File metadata and controls
226 lines (209 loc) · 7.55 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
// Copyright 2024 Harald Albrecht.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package morbyd
import (
"context"
"fmt"
"os"
"strings"
"github.com/containerd/errdefs"
"github.com/moby/moby/client"
"github.com/thediveo/morbyd/v2/moby"
"github.com/thediveo/morbyd/v2/session"
)
// Session represents a Docker API client connection, together with additional
// configuration options that are inherited to newly created images, containers,
// and networks.
type Session struct {
opts session.Options
moby moby.Client
}
// NewSession creates a new Docker client and test session, returning a Session
// object on success, or an error otherwise.
//
// When [sess.WithAutoCleaning] has been specified, then NewSession will then
// forcefully remove all containers and then networks matching the specified
// auto-cleaning label. In this case, [Session.Close] will then run a
// post-session cleaning.
//
// Note: the Docker client is created using the options [client.FromEnv] and
// [client.WithAPIVersionNegotiation].
func NewSession(ctx context.Context, opts ...session.Opt) (*Session, error) {
s := &Session{}
for _, opt := range opts {
if err := opt(&s.opts); err != nil {
return nil, fmt.Errorf("cannot create new test session, reason: %w",
err)
}
}
clientOpts := append([]client.Opt{
client.FromEnv,
}, s.opts.DockerClientOpts...)
moby, err := client.New(clientOpts...)
if err != nil {
return nil, err
}
s.moby = moby
if s.opts.Wrapper != nil {
s.moby = s.opts.Wrapper(s.moby)
}
s.AutoClean(ctx)
return s, nil
}
// Client returns the Docker client used in this test session.
func (s *Session) Client() moby.Client { return s.moby }
// Close removes left-over containers and networks if auto-cleaning has been
// enabled, and then closes idle HTTP connections to the Docker daemon.
func (s *Session) Close(ctx context.Context) {
s.AutoClean(ctx)
s.moby.Close() //nolint:errcheck // any error is irrelevant at this point
}
// AutoClean forcefully removes all left-over containers and networks that are
// labelled with the auto-cleaning label specified when creating this session.
// If no auto-cleaning label was specified, AutoClean simply returns, doing
// nothing. (Well, it does something: it returns ... but that is now too meta).
func (s *Session) AutoClean(ctx context.Context) {
if s.opts.AutoCleaningLabel == "" {
return
}
s.autoClean(ctx, s.opts.AutoCleaningLabel)
}
func (s *Session) autoClean(ctx context.Context, aclabel string) {
// Assemble a filter based on the auto-cleaning label.
key, value, _ := strings.Cut(aclabel, "=")
if value == "" {
aclabel = key // just the key, no trailing "=" in case of a zero value.
}
f := make(client.Filters).Add("label", aclabel)
// List all matching containers and then kill them.
cntrs, err := s.moby.ContainerList(ctx, client.ContainerListOptions{
Filters: f,
})
if err != nil {
return
}
for _, cntr := range cntrs.Items {
_, err := s.moby.ContainerRemove(ctx, cntr.ID, client.ContainerRemoveOptions{
Force: true,
RemoveVolumes: true,
})
if err != nil {
return
}
}
// List all matching networks (which by now should not have any test
// containers attached to them anymore) and then remove them.
nets, err := s.moby.NetworkList(ctx, client.NetworkListOptions{
Filters: f,
})
if err != nil {
return
}
for _, net := range nets.Items {
_, _ = s.moby.NetworkRemove(ctx, net.ID, client.NetworkRemoveOptions{})
}
}
// Container returns a *Container object for the specified name or ID if it
// exists, otherwise it returns an error. Please note that multiple calls for
// the same name or ID will return different *Container objects, as there is no
// caching.
func (s *Session) Container(ctx context.Context, nameID string) (*Container, error) {
details, err := s.moby.ContainerInspect(ctx, nameID, client.ContainerInspectOptions{})
if err != nil {
return nil, err
}
cntr := &Container{
Name: details.Container.Name[1:],
ID: details.Container.ID,
Session: s,
Details: details,
}
return cntr, nil
}
// MyContainer returns a *Container object if we're inside a container and we
// can identify and locate our container; otherwise, it returns an error. Please
// note that multiple calls will return different *Container objects.
//
// Please note that MyContainer works also correctly when inside a devcontainer
// inside a Github codespace. In fact, MyContainer does not simply try to lookup
// a container with the same name as our $HOSTNAME but instead sifts through all
// containers to find the one that has its “hostname” configured as our
// $HOSTNAME.
func (s *Session) MyContainer(ctx context.Context) (*Container, error) {
info, err := os.Stat("/.dockerenv")
if os.IsNotExist(err) || !info.Mode().IsRegular() {
return nil, fmt.Errorf("not in a container: %w", errdefs.ErrNotFound)
}
hostname := os.Getenv("HOSTNAME")
return s.containerByHostname(ctx, hostname)
}
func (s *Session) containerByHostname(ctx context.Context, hostname string) (*Container, error) {
// try the lucky guess first, but check that a potential find has the
// correct hostname configured.
cntr, err := s.Container(ctx, hostname)
if err == nil && cntr.Details.Container.Config != nil && cntr.Details.Container.Config.Hostname == hostname {
return cntr, nil
}
// ...no way, let's go down through the looking glass (and mix metaphors)
cntrs, err := s.Client().ContainerList(ctx, client.ContainerListOptions{})
if err != nil {
return nil, err
}
for _, cntr := range cntrs.Items {
details, err := s.Client().ContainerInspect(ctx, cntr.ID, client.ContainerInspectOptions{})
if err != nil || details.Container.Config == nil {
continue
}
if details.Container.Config.Hostname == hostname {
cntr := &Container{
Name: details.Container.Name[1:],
ID: details.Container.ID,
Session: s,
Details: details,
}
return cntr, nil
}
}
return nil, fmt.Errorf("cannot determine my own container from hostname %q: %w",
hostname, errdefs.ErrNotFound)
}
// Network returns a *Network object for the specified name or ID if it exists,
// otherwise it returns an error. Please note that multiple calls for the same
// name or ID will return different *Network objects, as there is no caching.
func (s *Session) Network(ctx context.Context, nameID string) (*Network, error) {
details, err := s.moby.NetworkInspect(ctx, nameID, client.NetworkInspectOptions{
Verbose: true,
})
if err != nil {
return nil, err
}
netw := &Network{
Name: details.Network.Name,
ID: details.Network.ID,
Session: s,
Details: details,
}
return netw, nil
}
// IsDockerDesktop returns true if the Docker engine is the Docker Desktop
// engine, as opposed to a “plain” Docker engine. This differentiation is
// important in some situation, as containers managed by Docker Desktop cannot
// be directly reached from the host, but always require ports to be published.
func (s *Session) IsDockerDesktop(ctx context.Context) bool {
info, err := s.moby.ServerVersion(ctx, client.ServerVersionOptions{})
if err != nil {
return false
}
return strings.Contains(info.Platform.Name, "Desktop")
}