@@ -219,10 +219,22 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) (resultError error) {
219219 // Apply the Network Policy for Endpoint
220220 epInfo .Policies = append (epInfo .Policies , networkInfo .Policies ... )
221221
222- // If LoopbackDSR is set, add to policies
222+ hnsIPAM := false
223+ // If LoopbackDSR is set and IP is already allocated via IPAM, add to policies before endpoint creation
223224 if cniConfig .OptionalFlags .LoopbackDSR {
224- hcnLoopbackRoute , _ := network .GetLoopbackDSRPolicy (& epInfo .IPAddress )
225- epInfo .Policies = append (epInfo .Policies , hcnLoopbackRoute )
225+ if epInfo .IPAddress != nil && len (epInfo .IPAddress ) > 0 {
226+ hcnLoopbackRoute , err := network .GetLoopbackDSRPolicy (epInfo .IPAddress )
227+ if err != nil {
228+ logrus .Errorf ("[cni-net] Failed to create loopbackDSR policy: %v, IPAddress: %v" , err , epInfo .IPAddress )
229+ return err
230+ }
231+ logrus .Debugf ("[cni-net] Created loopbackDSR policy for IP: %v" , epInfo .IPAddress )
232+ epInfo .Policies = append (epInfo .Policies , hcnLoopbackRoute )
233+ } else {
234+ // IP will be assigned by HCN, add the loopbackDSR policy after endpoint creation
235+ hnsIPAM = true
236+ logrus .Debugf ("[cni-net] IP not yet assigned, add loopbackDSR policy after endpoint creation" )
237+ }
226238 }
227239
228240 epInfo , err = plugin .nm .CreateEndpoint (nwConfig .ID , epInfo , args .Netns )
@@ -231,6 +243,28 @@ func (plugin *netPlugin) Add(args *cniSkel.CmdArgs) (resultError error) {
231243 return err
232244 }
233245
246+ // If LoopbackDSR is set but IP wasn't allocated via IPAM, add the policy after endpoint creation
247+ if hnsIPAM {
248+ if epInfo .IPAddress == nil || len (epInfo .IPAddress ) == 0 {
249+ logrus .Errorf ("[cni-net] LoopbackDSR is enabled but endpoint IP address is not set after endpoint creation" )
250+ return errors .New ("loopbackDSR requires IP address to be allocated" )
251+ }
252+
253+ logrus .Debugf ("[cni-net] Adding loopbackDSR policy for IP: %v after endpoint creation" , epInfo .IPAddress )
254+ hcnLoopbackRoute , err := network .GetLoopbackDSRPolicy (epInfo .IPAddress )
255+ if err != nil {
256+ logrus .Errorf ("[cni-net] Failed to create loopbackDSR policy after endpoint creation: %v, IPAddress: %v" , err , epInfo .IPAddress )
257+ return err
258+ }
259+
260+ err = plugin .nm .ApplyPolicy (epInfo .ID , hcnLoopbackRoute )
261+ if err != nil {
262+ logrus .Errorf ("[cni-net] Failed to apply loopbackDSR policy to endpoint: %v" , err )
263+ return err
264+ }
265+ logrus .Debugf ("[cni-net] Successfully applied loopbackDSR policy to endpoint" )
266+ }
267+
234268 // Convert result to the requested CNI version.
235269 res := cni .GetCurrResult (nwConfig , epInfo , args .IfName , cniConfig )
236270 result , err := res .GetAsVersion (cniConfig .CniVersion )
0 commit comments