@@ -5,11 +5,18 @@ package container
55
66import (
77 "context"
8+ "encoding/json"
89 "fmt"
10+ "strconv"
11+ "strings"
912
13+ "github.com/containerd/nerdctl/v2/pkg/inspecttypes/dockercompat"
14+ "github.com/containerd/nerdctl/v2/pkg/labels"
1015 "github.com/runfinch/finch-daemon/api/types"
1116)
1217
18+ const networkPrefix = "unknown-eth"
19+
1320func (s * service ) Inspect (ctx context.Context , cid string , sizeFlag bool ) (* types.Container , error ) {
1421 c , err := s .getContainer (ctx , cid )
1522 if err != nil {
@@ -58,6 +65,12 @@ func (s *service) Inspect(ctx context.Context, cid string, sizeFlag bool) (*type
5865 Labels : inspect .Config .Labels ,
5966 }
6067
68+ l , err := c .Labels (ctx )
69+ if err != nil {
70+ return nil , fmt .Errorf ("failed to get container labels: %s" , err )
71+ }
72+ updateNetworkSettings (ctx , cont .NetworkSettings , l )
73+
6174 // make sure it passes the default time value for time fields otherwise the goclient fails.
6275 if inspect .Created == "" {
6376 cont .Created = "0001-01-01T00:00:00Z"
@@ -69,3 +82,46 @@ func (s *service) Inspect(ctx context.Context, cid string, sizeFlag bool) (*type
6982
7083 return & cont , nil
7184}
85+
86+ // updateNetworkSettings updates the settings in the network to match that
87+ // of docker as docker identifies networks by their name in "NetworkSettings",
88+ // but nerdctl uses a sequential ordering "unknown-eth0", "unknown-eth1",...
89+ // we use container labels to find corresponding name for each network in "NetworkSettings".
90+ func updateNetworkSettings (ctx context.Context , ns * dockercompat.NetworkSettings , labels map [string ]string ) error {
91+ if ns != nil && ns .Networks != nil {
92+ networks := map [string ]* dockercompat.NetworkEndpointSettings {}
93+
94+ for network , settings := range ns .Networks {
95+ networkName := getNetworkName (labels , network )
96+ networks [networkName ] = settings
97+ }
98+ ns .Networks = networks
99+ }
100+ return nil
101+ }
102+
103+ // getNetworkName gets network name from container labels using the index specified by the network prefix.
104+ // returns the default prefix if network name was not found.
105+ func getNetworkName (lab map [string ]string , network string ) string {
106+ namesJSON , ok := lab [labels .Networks ]
107+ if ! ok {
108+ return network
109+ }
110+ var names []string
111+ if err := json .Unmarshal ([]byte (namesJSON ), & names ); err != nil {
112+ return network
113+ }
114+
115+ if strings .HasPrefix (network , networkPrefix ) {
116+ prefixLen := len (networkPrefix )
117+ index , err := strconv .ParseUint (network [prefixLen :], 10 , 64 )
118+ if err != nil {
119+ return network
120+ }
121+ if int (index ) < len (names ) {
122+ return names [index ]
123+ }
124+ }
125+
126+ return network
127+ }
0 commit comments