1717package run
1818
1919import (
20+ "context"
2021 gocontext "context"
2122 "encoding/csv"
2223 "fmt"
@@ -28,7 +29,9 @@ import (
2829 "github.com/containerd/containerd/cmd/ctr/commands"
2930 "github.com/containerd/containerd/cmd/ctr/commands/tasks"
3031 "github.com/containerd/containerd/containers"
32+ "github.com/containerd/containerd/namespaces"
3133 "github.com/containerd/containerd/oci"
34+ gocni "github.com/containerd/go-cni"
3235 specs "github.com/opencontainers/runtime-spec/specs-go"
3336 "github.com/pkg/errors"
3437 "github.com/sirupsen/logrus"
@@ -126,9 +129,10 @@ var Command = cli.Command{
126129 id string
127130 ref string
128131
129- tty = context .Bool ("tty" )
130- detach = context .Bool ("detach" )
131- config = context .IsSet ("config" )
132+ tty = context .Bool ("tty" )
133+ detach = context .Bool ("detach" )
134+ config = context .IsSet ("config" )
135+ enableCNI = context .Bool ("cni" )
132136 )
133137
134138 if config {
@@ -167,15 +171,31 @@ var Command = cli.Command{
167171 return err
168172 }
169173 }
174+ var network gocni.CNI
175+ if enableCNI {
176+ if network , err = gocni .New (gocni .WithDefaultConf ); err != nil {
177+ return err
178+ }
179+ }
180+
170181 opts := getNewTaskOpts (context )
171182 ioOpts := []cio.Opt {cio .WithFIFODir (context .String ("fifo-dir" ))}
172183 task , err := tasks .NewTask (ctx , client , container , context .String ("checkpoint" ), con , context .Bool ("null-io" ), context .String ("log-uri" ), ioOpts , opts ... )
173184 if err != nil {
174185 return err
175186 }
187+
176188 var statusC <- chan containerd.ExitStatus
177189 if ! detach {
178- defer task .Delete (ctx )
190+ defer func () {
191+ if enableCNI {
192+ if err := network .Remove (ctx , fullID (ctx , container ), "" ); err != nil {
193+ logrus .WithError (err ).Error ("network review" )
194+ }
195+ }
196+ task .Delete (ctx )
197+ }()
198+
179199 if statusC , err = task .Wait (ctx ); err != nil {
180200 return err
181201 }
@@ -185,6 +205,11 @@ var Command = cli.Command{
185205 return err
186206 }
187207 }
208+ if enableCNI {
209+ if _ , err := network .Setup (ctx , fullID (ctx , container ), fmt .Sprintf ("/proc/%d/ns/net" , task .Pid ())); err != nil {
210+ return err
211+ }
212+ }
188213 if err := task .Start (ctx ); err != nil {
189214 return err
190215 }
@@ -213,3 +238,12 @@ var Command = cli.Command{
213238 return nil
214239 },
215240}
241+
242+ func fullID (ctx context.Context , c containerd.Container ) string {
243+ id := c .ID ()
244+ ns , ok := namespaces .Namespace (ctx )
245+ if ! ok {
246+ return id
247+ }
248+ return fmt .Sprintf ("%s-%s" , ns , id )
249+ }
0 commit comments