Skip to content

Commit 1c50930

Browse files
minor fixes
1 parent 0346cc8 commit 1c50930

File tree

5 files changed

+107
-111
lines changed

5 files changed

+107
-111
lines changed

cns/fakes/imdsclientfake.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,4 @@ func (m *MockIMDSClient) GetIMDSVersions(ctx context.Context) (*imds.APIVersions
9494
"2025-07-24",
9595
},
9696
}, nil
97-
}
97+
}

cns/imds/client.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,7 @@ func (c *Client) GetNetworkInterfaces(ctx context.Context) ([]NetworkInterface,
114114
return errors.Wrap(err, "error getting IMDS network metadata")
115115
}
116116

117-
// Try to parse the network metadata as the expected structure
118-
// Convert the map to JSON and back to properly unmarshal into struct
117+
// Parse the network metadata to the expected structure
119118
jsonData, err := json.Marshal(networkInterfaces)
120119
if err != nil {
121120
return errors.Wrap(err, "error marshaling network metadata")
@@ -133,7 +132,8 @@ func (c *Client) GetNetworkInterfaces(ctx context.Context) ([]NetworkInterface,
133132
return networkData.Interface, nil
134133
}
135134

136-
func (c *Client) getInstanceMetadata(ctx context.Context, imdsMetadataPath string, imdsAPIVersion string) (map[string]any, error) {
135+
136+
func (c *Client) getInstanceMetadata(ctx context.Context, imdsMetadataPath, imdsAPIVersion string) (map[string]any, error) {
137137
imdsRequestURL, err := url.JoinPath(c.config.endpoint, imdsMetadataPath)
138138
if err != nil {
139139
return nil, errors.Wrap(err, "unable to build path to IMDS metadata for path"+imdsMetadataPath)

cns/imds/client_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ func TestGetVMUniqueID(t *testing.T) {
2121
require.NoError(t, err, "error reading testdata compute metadata file")
2222

2323
mockIMDSServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
24-
// request header "Metadata: true" must be present
2524
metadataHeader := r.Header.Get("Metadata")
2625
assert.Equal(t, "true", metadataHeader)
2726

@@ -271,7 +270,7 @@ func TestGetIMDSVersionsInternalServerError(t *testing.T) {
271270
versionsResp, err := imdsClient.GetIMDSVersions(context.Background())
272271

273272
require.Error(t, err, "expected error for 500")
274-
assert.Nil(t, versionsResp, "response should be nil on error")
273+
assert.Nil(t, versionsResp, "response should be nil or error")
275274
}
276275

277276
func TestGetIMDSVersionsMissingAPIVersionsField(t *testing.T) {
@@ -295,4 +294,4 @@ func TestGetIMDSVersionsInvalidEndpoint(t *testing.T) {
295294
imdsClient := imds.NewClient(imds.Endpoint(string([]byte{0x7f})), imds.RetryAttempts(1))
296295
_, err := imdsClient.GetIMDSVersions(context.Background())
297296
require.Error(t, err, "expected error for invalid endpoint")
298-
}
297+
}

cns/restserver/internalapi.go

Lines changed: 101 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -195,113 +195,113 @@ var errNonExistentContainerStatus = errors.New("nonExistantContainerstatus")
195195
// all NCs and update the CNS state accordingly. This function returns the the total number of NCs on this VM that have been programmed to
196196
// some version, NOT the number of NCs that are up-to-date.
197197
func (service *HTTPRestService) syncHostNCVersion(ctx context.Context, channelMode string) (int, error) {
198-
outdatedNCs := map[string]struct{}{}
199-
programmedNCs := map[string]struct{}{}
200-
for idx := range service.state.ContainerStatus {
201-
// Will open a separate PR to convert all the NC version related variable to int. Change from string to int is a pain.
202-
localNCVersion, err := strconv.Atoi(service.state.ContainerStatus[idx].HostVersion)
203-
if err != nil {
204-
logger.Errorf("Received err when change containerstatus.HostVersion %s to int, err msg %v", service.state.ContainerStatus[idx].HostVersion, err)
205-
continue
206-
}
207-
dncNCVersion, err := strconv.Atoi(service.state.ContainerStatus[idx].CreateNetworkContainerRequest.Version)
208-
if err != nil {
209-
logger.Errorf("Received err when change nc version %s in containerstatus to int, err msg %v", service.state.ContainerStatus[idx].CreateNetworkContainerRequest.Version, err)
210-
continue
211-
}
212-
// host NC version is the NC version from NMAgent, if it's smaller than NC version from DNC, then append it to indicate it needs update.
213-
if localNCVersion < dncNCVersion {
214-
outdatedNCs[service.state.ContainerStatus[idx].ID] = struct{}{}
215-
} else if localNCVersion > dncNCVersion {
216-
logger.Errorf("NC version from NMAgent is larger than DNC, NC version from NMAgent is %d, NC version from DNC is %d", localNCVersion, dncNCVersion)
217-
}
198+
outdatedNCs := map[string]struct{}{}
199+
programmedNCs := map[string]struct{}{}
200+
for idx := range service.state.ContainerStatus {
201+
// Will open a separate PR to convert all the NC version related variable to int. Change from string to int is a pain.
202+
localNCVersion, err := strconv.Atoi(service.state.ContainerStatus[idx].HostVersion)
203+
if err != nil {
204+
logger.Errorf("Received err when change containerstatus.HostVersion %s to int, err msg %v", service.state.ContainerStatus[idx].HostVersion, err)
205+
continue
206+
}
207+
dncNCVersion, err := strconv.Atoi(service.state.ContainerStatus[idx].CreateNetworkContainerRequest.Version)
208+
if err != nil {
209+
logger.Errorf("Received err when change nc version %s in containerstatus to int, err msg %v", service.state.ContainerStatus[idx].CreateNetworkContainerRequest.Version, err)
210+
continue
211+
}
212+
// host NC version is the NC version from NMAgent, if it's smaller than NC version from DNC, then append it to indicate it needs update.
213+
if localNCVersion < dncNCVersion {
214+
outdatedNCs[service.state.ContainerStatus[idx].ID] = struct{}{}
215+
} else if localNCVersion > dncNCVersion {
216+
logger.Errorf("NC version from NMAgent is larger than DNC, NC version from NMAgent is %d, NC version from DNC is %d", localNCVersion, dncNCVersion)
217+
}
218218

219-
if localNCVersion > -1 {
220-
programmedNCs[service.state.ContainerStatus[idx].ID] = struct{}{}
221-
}
222-
}
223-
if len(outdatedNCs) == 0 {
224-
return len(programmedNCs), nil
225-
}
226-
ncVersionListResp, err := service.nma.GetNCVersionList(ctx)
227-
if err != nil {
228-
return len(programmedNCs), errors.Wrap(err, "failed to get nc version list from nmagent")
229-
}
219+
if localNCVersion > -1 {
220+
programmedNCs[service.state.ContainerStatus[idx].ID] = struct{}{}
221+
}
222+
}
223+
if len(outdatedNCs) == 0 {
224+
return len(programmedNCs), nil
225+
}
226+
ncVersionListResp, err := service.nma.GetNCVersionList(ctx)
227+
if err != nil {
228+
return len(programmedNCs), errors.Wrap(err, "failed to get nc version list from nmagent")
229+
}
230230

231-
// Get IMDS NC details for delegated NIC
232-
imdsNCs, err := service.GetIMDSNCs(ctx)
233-
if err != nil {
234-
// If any of the NMA API check calls, imds calls fails assume that nma build doesn't have the latest changes and create empty map
235-
imdsNCs = make(map[string]string)
236-
}
231+
// Get IMDS NC versions for delegated NIC scenarios
232+
imdsNCVersions, err := service.GetIMDSNCVersions(ctx)
233+
if err != nil {
234+
// If any of the NMA API check calls, imds calls fails assume that nma build doesn't have the latest changes and create empty map
235+
imdsNCVersions = make(map[string]string)
236+
}
237237

238-
nmaNCs := map[string]string{}
239-
for _, nc := range ncVersionListResp.Containers {
240-
nmaNCs[strings.ToLower(nc.NetworkContainerID)] = nc.Version
241-
}
238+
nmaNCs := map[string]string{}
239+
for _, nc := range ncVersionListResp.Containers {
240+
nmaNCs[strings.ToLower(nc.NetworkContainerID)] = nc.Version
241+
}
242242

243-
// Consolidate both nc's from NMA and IMDS calls
244-
nmaProgrammedNCs := make(map[string]string)
245-
for ncID, version := range nmaNCs {
246-
nmaProgrammedNCs[ncID] = version
247-
}
248-
for ncID, version := range imdsNCs {
249-
if _, exists := nmaProgrammedNCs[ncID]; !exists {
250-
nmaProgrammedNCs[strings.ToLower(ncID)] = version
251-
}
252-
}
253-
hasNC.Set(float64(len(nmaProgrammedNCs)))
254-
for ncID := range outdatedNCs {
255-
nmaProgrammedNCVersionStr, ok := nmaProgrammedNCs[ncID]
256-
if !ok {
257-
// Neither NMA nor IMDS has this NC that we need programmed yet, bail out
258-
continue
259-
}
260-
nmaProgrammedNCVersion, err := strconv.Atoi(nmaProgrammedNCVersionStr)
261-
if err != nil {
262-
logger.Errorf("failed to parse container version of %s: %s", ncID, err)
263-
continue
264-
}
265-
// Check whether it exist in service state and get the related nc info
266-
ncInfo, exist := service.state.ContainerStatus[ncID]
267-
if !exist {
268-
// if we marked this NC as needs update, but it no longer exists in internal state when we reach
269-
// this point, our internal state has changed unexpectedly and we should bail out and try again.
270-
return len(programmedNCs), errors.Wrapf(errNonExistentContainerStatus, "can't find NC with ID %s in service state, stop updating this host NC version", ncID)
271-
}
272-
// if the NC still exists in state and is programmed to some version (doesn't have to be latest), add it to our set of NCs that have been programmed
273-
if nmaProgrammedNCVersion > -1 {
274-
programmedNCs[ncID] = struct{}{}
275-
}
243+
// Consolidate both nc's from NMA and IMDS calls
244+
nmaProgrammedNCs := make(map[string]string)
245+
for ncID, version := range nmaNCs {
246+
nmaProgrammedNCs[ncID] = version
247+
}
248+
for ncID, version := range imdsNCVersions {
249+
if _, exists := nmaProgrammedNCs[ncID]; !exists {
250+
nmaProgrammedNCs[strings.ToLower(ncID)] = version
251+
}
252+
}
253+
hasNC.Set(float64(len(nmaProgrammedNCs)))
254+
for ncID := range outdatedNCs {
255+
nmaProgrammedNCVersionStr, ok := nmaProgrammedNCs[ncID]
256+
if !ok {
257+
// Neither NMA nor IMDS has this NC that we need programmed yet, bail out
258+
continue
259+
}
260+
nmaProgrammedNCVersion, err := strconv.Atoi(nmaProgrammedNCVersionStr)
261+
if err != nil {
262+
logger.Errorf("failed to parse container version of %s: %s", ncID, err)
263+
continue
264+
}
265+
// Check whether it exist in service state and get the related nc info
266+
ncInfo, exist := service.state.ContainerStatus[ncID]
267+
if !exist {
268+
// if we marked this NC as needs update, but it no longer exists in internal state when we reach
269+
// this point, our internal state has changed unexpectedly and we should bail out and try again.
270+
return len(programmedNCs), errors.Wrapf(errNonExistentContainerStatus, "can't find NC with ID %s in service state, stop updating this host NC version", ncID)
271+
}
272+
// if the NC still exists in state and is programmed to some version (doesn't have to be latest), add it to our set of NCs that have been programmed
273+
if nmaProgrammedNCVersion > -1 {
274+
programmedNCs[ncID] = struct{}{}
275+
}
276276

277-
localNCVersion, err := strconv.Atoi(ncInfo.HostVersion)
278-
if err != nil {
279-
logger.Errorf("failed to parse host nc version string %s: %s", ncInfo.HostVersion, err)
280-
continue
281-
}
282-
if localNCVersion > nmaProgrammedNCVersion {
283-
//nolint:staticcheck // SA1019: suppress deprecated logger.Printf usage. Todo: legacy logger usage is consistent in cns repo. Migrates when all logger usage is migrated
284-
logger.Errorf("NC version from consolidated sources is decreasing: have %d, got %d", localNCVersion, nmaProgrammedNCVersion)
285-
continue
286-
}
287-
if channelMode == cns.CRD {
288-
service.MarkIpsAsAvailableUntransacted(ncInfo.ID, nmaProgrammedNCVersion)
289-
}
290-
//nolint:staticcheck // SA1019: suppress deprecated logger.Printf usage. Todo: legacy logger usage is consistent in cns repo. Migrates when all logger usage is migrated
291-
logger.Printf("Updating NC %s host version from %s to %s", ncID, ncInfo.HostVersion, nmaProgrammedNCVersionStr)
292-
ncInfo.HostVersion = nmaProgrammedNCVersionStr
293-
logger.Printf("Updated NC %s host version to %s", ncID, ncInfo.HostVersion)
294-
service.state.ContainerStatus[ncID] = ncInfo
295-
// if we successfully updated the NC, pop it from the needs update set.
296-
delete(outdatedNCs, ncID)
297-
}
298-
// if we didn't empty out the needs update set, NMA has not programmed all the NCs we are expecting, and we
299-
// need to return an error indicating that
300-
if len(outdatedNCs) > 0 {
301-
return len(programmedNCs), errors.Errorf("unable to update some NCs: %v, missing or bad response from NMA or IMDS", outdatedNCs)
302-
}
277+
localNCVersion, err := strconv.Atoi(ncInfo.HostVersion)
278+
if err != nil {
279+
logger.Errorf("failed to parse host nc version string %s: %s", ncInfo.HostVersion, err)
280+
continue
281+
}
282+
if localNCVersion > nmaProgrammedNCVersion {
283+
//nolint:staticcheck // SA1019: suppress deprecated logger.Printf usage. Todo: legacy logger usage is consistent in cns repo. Migrates when all logger usage is migrated
284+
logger.Errorf("NC version from consolidated sources is decreasing: have %d, got %d", localNCVersion, nmaProgrammedNCVersion)
285+
continue
286+
}
287+
if channelMode == cns.CRD {
288+
service.MarkIpsAsAvailableUntransacted(ncInfo.ID, nmaProgrammedNCVersion)
289+
}
290+
//nolint:staticcheck // SA1019: suppress deprecated logger.Printf usage. Todo: legacy logger usage is consistent in cns repo. Migrates when all logger usage is migrated
291+
logger.Printf("Updating NC %s host version from %s to %s", ncID, ncInfo.HostVersion, nmaProgrammedNCVersionStr)
292+
ncInfo.HostVersion = nmaProgrammedNCVersionStr
293+
logger.Printf("Updated NC %s host version to %s", ncID, ncInfo.HostVersion)
294+
service.state.ContainerStatus[ncID] = ncInfo
295+
// if we successfully updated the NC, pop it from the needs update set.
296+
delete(outdatedNCs, ncID)
297+
}
298+
// if we didn't empty out the needs update set, NMA has not programmed all the NCs we are expecting, and we
299+
// need to return an error indicating that
300+
if len(outdatedNCs) > 0 {
301+
return len(programmedNCs), errors.Errorf("unable to update some NCs: %v, missing or bad response from NMA or IMDS", outdatedNCs)
302+
}
303303

304-
return len(programmedNCs), nil
304+
return len(programmedNCs), nil
305305
}
306306

307307
func (service *HTTPRestService) ReconcileIPAssignment(podInfoByIP map[string]cns.PodInfo, ncReqs []*cns.CreateNetworkContainerRequest) types.ResponseCode {

cns/restserver/internalapi_test.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,6 @@ func TestSyncHostNCVersion(t *testing.T) {
230230
// cns.KubernetesCRD has one more logic compared to other orchestrator type, so test both of them
231231
orchestratorTypes := []string{cns.Kubernetes, cns.KubernetesCRD}
232232
for _, orchestratorType := range orchestratorTypes {
233-
orchestratorType := orchestratorType
234233
t.Run(orchestratorType, func(t *testing.T) {
235234
req := createNCReqeustForSyncHostNCVersion(t)
236235
containerStatus := svc.state.ContainerStatus[req.NetworkContainerid]
@@ -531,7 +530,6 @@ func TestSyncHostNCVersionNMAgentAPICallFailed(t *testing.T) {
531530
}
532531

533532
func TestSyncHostNCVersionSwiftV2APINotSupported(t *testing.T) {
534-
// Test scenario where NMAgent doesn't support SwiftV2 API
535533
req := createNCReqeustForSyncHostNCVersion(t)
536534

537535
svc.Lock()
@@ -581,7 +579,6 @@ func TestSyncHostNCVersionSwiftV2APINotSupported(t *testing.T) {
581579
func TestSyncHostNCVersionIMDSAPIVersionNotSupported(t *testing.T) {
582580
orchestratorTypes := []string{cns.Kubernetes, cns.KubernetesCRD}
583581
for _, orchestratorType := range orchestratorTypes {
584-
orchestratorType := orchestratorType
585582
t.Run(orchestratorType, func(t *testing.T) {
586583
req := createNCReqeustForSyncHostNCVersion(t)
587584

0 commit comments

Comments
 (0)