-
Notifications
You must be signed in to change notification settings - Fork 564
/
remove.go
247 lines (224 loc) · 7.34 KB
/
remove.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
/*
Copyright The containerd Authors.
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 container
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"runtime"
"syscall"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/log"
"github.com/containerd/nerdctl/v2/pkg/api/types"
"github.com/containerd/nerdctl/v2/pkg/clientutil"
"github.com/containerd/nerdctl/v2/pkg/cmd/volume"
"github.com/containerd/nerdctl/v2/pkg/containerutil"
"github.com/containerd/nerdctl/v2/pkg/dnsutil/hostsstore"
"github.com/containerd/nerdctl/v2/pkg/idutil/containerwalker"
"github.com/containerd/nerdctl/v2/pkg/ipcutil"
"github.com/containerd/nerdctl/v2/pkg/labels"
"github.com/containerd/nerdctl/v2/pkg/namestore"
)
var _ error = ErrContainerStatus{}
// ErrContainerStatus represents an error that container is in a status unexpected
// by the caller. E.g., remove a non-stoped/non-created container without force.
type ErrContainerStatus struct {
ID string
Status containerd.ProcessStatus
}
func (e ErrContainerStatus) Error() string {
return fmt.Sprintf("container %s is in %v status", e.ID, e.Status)
}
// NewStatusError creates an ErrContainerStatus from container id and status.
func NewStatusError(id string, status containerd.ProcessStatus) error {
return ErrContainerStatus{
ID: id,
Status: status,
}
}
// Remove removes a list of `containers`.
func Remove(ctx context.Context, client *containerd.Client, containers []string, options types.ContainerRemoveOptions) error {
walker := &containerwalker.ContainerWalker{
Client: client,
OnFound: func(ctx context.Context, found containerwalker.Found) error {
if found.MatchCount > 1 {
return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req)
}
if err := RemoveContainer(ctx, found.Container, options.GOptions, options.Force, options.Volumes, client); err != nil {
if errors.As(err, &ErrContainerStatus{}) {
err = fmt.Errorf("%s. unpause/stop container first or force removal", err)
}
return err
}
_, err := fmt.Fprintln(options.Stdout, found.Req)
return err
},
}
err := walker.WalkAll(ctx, containers, true)
if err != nil && options.Force {
log.G(ctx).Error(err)
return nil
}
return err
}
// RemoveContainer removes a container from containerd store.
func RemoveContainer(ctx context.Context, c containerd.Container, globalOptions types.GlobalCommandOptions, force bool, removeAnonVolumes bool, client *containerd.Client) (retErr error) {
// defer the storage of remove error in the dedicated label
defer func() {
if retErr != nil {
containerutil.UpdateErrorLabel(ctx, c, retErr)
}
}()
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return err
}
id := c.ID()
l, err := c.Labels(ctx)
if err != nil {
return err
}
ipc, err := ipcutil.DecodeIPCLabel(l[labels.IPC])
if err != nil {
return err
}
err = ipcutil.CleanUp(ipc)
if err != nil {
return err
}
stateDir := l[labels.StateDir]
name := l[labels.Name]
dataStore, err := clientutil.DataStore(globalOptions.DataRoot, globalOptions.Address)
if err != nil {
return err
}
namst, err := namestore.New(dataStore, ns)
if err != nil {
return err
}
defer func() {
if errdefs.IsNotFound(retErr) {
retErr = nil
}
if retErr != nil {
return
}
if err := os.RemoveAll(stateDir); err != nil {
log.G(ctx).WithError(err).Warnf("failed to remove container state dir %s", stateDir)
}
// enforce release name here in case the poststop hook name release fails
if name != "" {
if err := namst.Release(name, id); err != nil {
log.G(ctx).WithError(err).Warnf("failed to release container name %s", name)
}
}
if err := hostsstore.DeallocHostsFile(dataStore, ns, id); err != nil {
log.G(ctx).WithError(err).Warnf("failed to remove hosts file for container %q", id)
}
}()
// volume removal is not handled by the poststop hook lifecycle because it depends on removeAnonVolumes option
if anonVolumesJSON, ok := l[labels.AnonymousVolumes]; ok && removeAnonVolumes {
var anonVolumes []string
if err := json.Unmarshal([]byte(anonVolumesJSON), &anonVolumes); err != nil {
return err
}
volStore, err := volume.Store(globalOptions.Namespace, globalOptions.DataRoot, globalOptions.Address)
if err != nil {
return err
}
defer func() {
if _, errs, err := volStore.Remove(anonVolumes); err != nil || len(errs) > 0 {
log.G(ctx).WithError(err).Warnf("failed to remove anonymous volumes %v", anonVolumes)
}
}()
}
task, err := c.Task(ctx, cio.Load)
if err != nil {
if errdefs.IsNotFound(err) {
if c.Delete(ctx, containerd.WithSnapshotCleanup) != nil {
return c.Delete(ctx)
}
}
return err
}
status, err := task.Status(ctx)
if err != nil {
if errdefs.IsNotFound(err) {
return nil
}
return err
}
// NOTE: on non-Windows platforms, network cleanup is performed by OCI hooks.
// Seeing as though Windows does not currently support OCI hooks, we must explicitly
// perform the network cleanup from the main nerdctl executable.
if runtime.GOOS == "windows" {
spec, err := c.Spec(ctx)
if err != nil {
return err
}
netOpts, err := containerutil.NetworkOptionsFromSpec(spec)
if err != nil {
return fmt.Errorf("failed to load container networking options from specs: %s", err)
}
networkManager, err := containerutil.NewNetworkingOptionsManager(globalOptions, netOpts, client)
if err != nil {
return fmt.Errorf("failed to instantiate network options manager: %s", err)
}
if err := networkManager.CleanupNetworking(ctx, c); err != nil {
log.G(ctx).WithError(err).Warnf("failed to clean up container networking: %s", err)
}
}
switch status.Status {
case containerd.Created, containerd.Stopped:
if _, err := task.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
return fmt.Errorf("failed to delete task %v: %w", id, err)
}
case containerd.Paused:
if !force {
return NewStatusError(id, status.Status)
}
_, err := task.Delete(ctx, containerd.WithProcessKill)
if err != nil && !errdefs.IsNotFound(err) {
return fmt.Errorf("failed to delete task %v: %w", id, err)
}
// default is the case, when status.Status = containerd.Running
default:
if !force {
return NewStatusError(id, status.Status)
}
if err := task.Kill(ctx, syscall.SIGKILL); err != nil {
log.G(ctx).WithError(err).Warnf("failed to send SIGKILL")
}
es, err := task.Wait(ctx)
if err == nil {
<-es
}
_, err = task.Delete(ctx, containerd.WithProcessKill)
if err != nil && !errdefs.IsNotFound(err) {
log.G(ctx).WithError(err).Warnf("failed to delete task %v", id)
}
}
var delOpts []containerd.DeleteOpts
if _, err := c.Image(ctx); err == nil {
delOpts = append(delOpts, containerd.WithSnapshotCleanup)
}
if err := c.Delete(ctx, delOpts...); err != nil {
return err
}
return err
}