@@ -6,10 +6,14 @@ package backend
66import (
77 "context"
88 "encoding/json"
9+ "fmt"
910
11+ containerd "github.com/containerd/containerd/v2/client"
1012 "github.com/containerd/nerdctl/v2/pkg/api/types"
13+ "github.com/containerd/nerdctl/v2/pkg/containerinspector"
1114 "github.com/containerd/nerdctl/v2/pkg/inspecttypes/dockercompat"
1215 "github.com/containerd/nerdctl/v2/pkg/inspecttypes/native"
16+ "github.com/containerd/nerdctl/v2/pkg/labels"
1317 "github.com/containerd/nerdctl/v2/pkg/netutil"
1418 "github.com/containernetworking/cni/libcni"
1519 cnitypes "github.com/containernetworking/cni/pkg/types"
@@ -54,11 +58,18 @@ func (w *NerdctlWrapper) RemoveNetwork(networkConfig *netutil.NetworkConfig) err
5458}
5559
5660func (w * NerdctlWrapper ) InspectNetwork (ctx context.Context , networkConfig * netutil.NetworkConfig ) (* dockercompat.Network , error ) {
61+ // Get containers associated with this network
62+ containers , err := getContainersFromNetConfig (ctx , networkConfig , w .clientWrapper )
63+ if err != nil {
64+ return nil , fmt .Errorf ("failed to get containers for network: %w" , err )
65+ }
66+
5767 network := & native.Network {
5868 CNI : json .RawMessage (networkConfig .Bytes ),
5969 NerdctlID : networkConfig .NerdctlID ,
6070 NerdctlLabels : networkConfig .NerdctlLabels ,
6171 File : networkConfig .File ,
72+ Containers : containers ,
6273 }
6374 return dockercompat .NetworkFromNative (network )
6475}
@@ -74,3 +85,27 @@ func (w *NerdctlWrapper) NetconfPath() string {
7485func (w * NerdctlWrapper ) Namespace () string {
7586 return w .netClient .Namespace
7687}
88+
89+ // getContainersFromNetConfig returns containers associated with the given network
90+ func getContainersFromNetConfig (ctx context.Context , networkConfig * netutil.NetworkConfig , client ContainerdClient ) ([]* native.Container , error ) {
91+ filters := []string {fmt .Sprintf (`labels.%q~="\\\"%s\\\""` , labels .Networks , networkConfig .Name )}
92+ filteredContainers , err := client .GetContainers (ctx , filters ... )
93+ if err != nil {
94+ return nil , err
95+ }
96+
97+ var containers []* native.Container
98+ for _ , container := range filteredContainers {
99+ nativeContainer , err := containerinspector .Inspect (ctx , container )
100+ if err != nil {
101+ continue
102+ }
103+ if nativeContainer .Process == nil || nativeContainer .Process .Status .Status != containerd .Running {
104+ continue
105+ }
106+
107+ containers = append (containers , nativeContainer )
108+ }
109+
110+ return containers , nil
111+ }
0 commit comments