Fix misc static check issues

This commit is contained in:
Tim Allclair 2019-08-08 18:07:03 -07:00
parent 3f510c69f6
commit 6510d26b6a
22 changed files with 54 additions and 55 deletions

View File

@ -146,7 +146,7 @@ type ContainerStats struct {
// User defined metrics that are exposed by containers in the pod. Typically, we expect only one container in the pod to be exposing user defined metrics. In the event of multiple containers exposing metrics, they will be combined here. // User defined metrics that are exposed by containers in the pod. Typically, we expect only one container in the pod to be exposing user defined metrics. In the event of multiple containers exposing metrics, they will be combined here.
// +patchMergeKey=name // +patchMergeKey=name
// +patchStrategy=merge // +patchStrategy=merge
UserDefinedMetrics []UserDefinedMetric `json:"userDefinedMetrics,omitmepty" patchStrategy:"merge" patchMergeKey:"name"` UserDefinedMetrics []UserDefinedMetric `json:"userDefinedMetrics,omitempty" patchStrategy:"merge" patchMergeKey:"name"`
} }
// PodReference contains enough information to locate the referenced pod. // PodReference contains enough information to locate the referenced pod.

View File

@ -91,9 +91,7 @@ func getPodKey(pod *v1.Pod) string {
func LoadPods(cpm checkpointmanager.CheckpointManager) ([]*v1.Pod, error) { func LoadPods(cpm checkpointmanager.CheckpointManager) ([]*v1.Pod, error) {
pods := make([]*v1.Pod, 0) pods := make([]*v1.Pod, 0)
var err error checkpointKeys, err := cpm.ListCheckpoints()
checkpointKeys := []string{}
checkpointKeys, err = cpm.ListCheckpoints()
if err != nil { if err != nil {
klog.Errorf("Failed to list checkpoints: %v", err) klog.Errorf("Failed to list checkpoints: %v", err)
} }

View File

@ -32,6 +32,7 @@ go_test(
"//pkg/kubelet/checkpointmanager:go_default_library", "//pkg/kubelet/checkpointmanager:go_default_library",
"//pkg/kubelet/cm/cpumanager/state/testing:go_default_library", "//pkg/kubelet/cm/cpumanager/state/testing:go_default_library",
"//pkg/kubelet/cm/cpuset:go_default_library", "//pkg/kubelet/cm/cpuset:go_default_library",
"//vendor/github.com/stretchr/testify/require:go_default_library",
], ],
) )

View File

@ -21,6 +21,7 @@ import (
"path" "path"
"testing" "testing"
"github.com/stretchr/testify/require"
"k8s.io/kubernetes/pkg/kubelet/checkpointmanager" "k8s.io/kubernetes/pkg/kubelet/checkpointmanager"
"k8s.io/kubernetes/pkg/kubelet/cm/cpuset" "k8s.io/kubernetes/pkg/kubelet/cm/cpuset"
) )
@ -68,6 +69,7 @@ func TestCheckpointToFileCompatibility(t *testing.T) {
defer cpm.RemoveCheckpoint(compatibilityTestingCheckpoint) defer cpm.RemoveCheckpoint(compatibilityTestingCheckpoint)
checkpointState, err := NewCheckpointState(testingDir, compatibilityTestingCheckpoint, "none") checkpointState, err := NewCheckpointState(testingDir, compatibilityTestingCheckpoint, "none")
require.NoError(t, err)
checkpointState.SetDefaultCPUSet(state.defaultCPUSet) checkpointState.SetDefaultCPUSet(state.defaultCPUSet)
checkpointState.SetCPUAssignments(state.assignments) checkpointState.SetCPUAssignments(state.assignments)

View File

@ -373,17 +373,14 @@ func TestUpdateCapacityAllocatable(t *testing.T) {
e1.setStopTime(time.Now().Add(-1*endpointStopGracePeriod - time.Duration(10)*time.Second)) e1.setStopTime(time.Now().Add(-1*endpointStopGracePeriod - time.Duration(10)*time.Second))
capacity, allocatable, removed := testManager.GetCapacity() capacity, allocatable, removed := testManager.GetCapacity()
as.Equal([]string{resourceName1}, removed) as.Equal([]string{resourceName1}, removed)
_, ok = capacity[v1.ResourceName(resourceName1)] as.NotContains(capacity, v1.ResourceName(resourceName1))
as.False(ok) as.NotContains(allocatable, v1.ResourceName(resourceName1))
val, ok := capacity[v1.ResourceName(resourceName2)] val, ok := capacity[v1.ResourceName(resourceName2)]
as.True(ok) as.True(ok)
as.Equal(int64(3), val.Value()) as.Equal(int64(3), val.Value())
_, ok = testManager.healthyDevices[resourceName1] as.NotContains(testManager.healthyDevices, resourceName1)
as.False(ok) as.NotContains(testManager.unhealthyDevices, resourceName1)
_, ok = testManager.unhealthyDevices[resourceName1] as.NotContains(testManager.endpoints, resourceName1)
as.False(ok)
_, ok = testManager.endpoints[resourceName1]
as.False(ok)
as.Equal(1, len(testManager.endpoints)) as.Equal(1, len(testManager.endpoints))
// Stops resourceName2 endpoint. Verifies its stopTime is set, allocate and // Stops resourceName2 endpoint. Verifies its stopTime is set, allocate and
@ -417,12 +414,14 @@ func TestUpdateCapacityAllocatable(t *testing.T) {
err = testManager.readCheckpoint() err = testManager.readCheckpoint()
as.Nil(err) as.Nil(err)
as.Equal(1, len(testManager.endpoints)) as.Equal(1, len(testManager.endpoints))
_, ok = testManager.endpoints[resourceName2] as.Contains(testManager.endpoints, resourceName2)
as.True(ok)
capacity, allocatable, removed = testManager.GetCapacity() capacity, allocatable, removed = testManager.GetCapacity()
val, ok = capacity[v1.ResourceName(resourceName2)] val, ok = capacity[v1.ResourceName(resourceName2)]
as.True(ok) as.True(ok)
as.Equal(int64(0), val.Value()) as.Equal(int64(0), val.Value())
val, ok = allocatable[v1.ResourceName(resourceName2)]
as.True(ok)
as.Equal(int64(0), val.Value())
as.Empty(removed) as.Empty(removed)
as.True(testManager.isDevicePluginResource(resourceName2)) as.True(testManager.isDevicePluginResource(resourceName2))
} }

View File

@ -271,14 +271,6 @@ func (f *FakeRuntime) KillContainerInPod(container v1.Container, pod *v1.Pod) er
f.CalledFunctions = append(f.CalledFunctions, "KillContainerInPod") f.CalledFunctions = append(f.CalledFunctions, "KillContainerInPod")
f.KilledContainers = append(f.KilledContainers, container.Name) f.KilledContainers = append(f.KilledContainers, container.Name)
var containers []v1.Container
for _, c := range pod.Spec.Containers {
if c.Name == container.Name {
continue
}
containers = append(containers, c)
}
return f.Err return f.Err
} }

View File

@ -52,6 +52,7 @@ go_test(
"//staging/src/k8s.io/client-go/util/testing:go_default_library", "//staging/src/k8s.io/client-go/util/testing:go_default_library",
"//vendor/github.com/containernetworking/cni/pkg/types/020:go_default_library", "//vendor/github.com/containernetworking/cni/pkg/types/020:go_default_library",
"//vendor/github.com/stretchr/testify/mock:go_default_library", "//vendor/github.com/stretchr/testify/mock:go_default_library",
"//vendor/github.com/stretchr/testify/require:go_default_library",
"//vendor/k8s.io/utils/exec:go_default_library", "//vendor/k8s.io/utils/exec:go_default_library",
"//vendor/k8s.io/utils/exec/testing:go_default_library", "//vendor/k8s.io/utils/exec/testing:go_default_library",
], ],

View File

@ -34,6 +34,7 @@ import (
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
clientset "k8s.io/client-go/kubernetes" clientset "k8s.io/client-go/kubernetes"
utiltesting "k8s.io/client-go/util/testing" utiltesting "k8s.io/client-go/util/testing"
@ -73,6 +74,7 @@ func installPluginUnderTest(t *testing.T, testBinDir, testConfDir, testDataDir,
pluginExec := path.Join(testBinDir, binName) pluginExec := path.Join(testBinDir, binName)
f, err = os.Create(pluginExec) f, err = os.Create(pluginExec)
require.NoError(t, err)
const execScriptTempl = `#!/usr/bin/env bash const execScriptTempl = `#!/usr/bin/env bash
cat > {{.InputFile}} cat > {{.InputFile}}
@ -329,6 +331,7 @@ func TestCNIPlugin(t *testing.T) {
t.Errorf("Expected nil: %v", err) t.Errorf("Expected nil: %v", err)
} }
output, err = ioutil.ReadFile(outputFile) output, err = ioutil.ReadFile(outputFile)
require.NoError(t, err)
expectedOutput = "DEL /proc/12345/ns/net podNamespace podName test_infra_container" expectedOutput = "DEL /proc/12345/ns/net podNamespace podName test_infra_container"
if string(output) != expectedOutput { if string(output) != expectedOutput {
t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output)) t.Errorf("Mismatch in expected output for setup hook. Expected '%s', got '%s'", expectedOutput, string(output))

View File

@ -497,7 +497,7 @@ func (m *managerImpl) podEphemeralStorageLimitEviction(podStats statsapi.PodStat
} }
podEphemeralStorageTotalUsage := &resource.Quantity{} podEphemeralStorageTotalUsage := &resource.Quantity{}
fsStatsSet := []fsStatsType{} var fsStatsSet []fsStatsType
if *m.dedicatedImageFs { if *m.dedicatedImageFs {
fsStatsSet = []fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource} fsStatsSet = []fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource}
} else { } else {

View File

@ -538,6 +538,7 @@ func TestUpdateExistingNodeStatusTimeout(t *testing.T) {
kubelet := testKubelet.kubelet kubelet := testKubelet.kubelet
kubelet.kubeClient = nil // ensure only the heartbeat client is used kubelet.kubeClient = nil // ensure only the heartbeat client is used
kubelet.heartbeatClient, err = clientset.NewForConfig(config) kubelet.heartbeatClient, err = clientset.NewForConfig(config)
require.NoError(t, err)
kubelet.onRepeatedHeartbeatFailure = func() { kubelet.onRepeatedHeartbeatFailure = func() {
atomic.AddInt64(&failureCallbacks, 1) atomic.AddInt64(&failureCallbacks, 1)
} }

View File

@ -23,6 +23,7 @@ import (
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
@ -35,6 +36,7 @@ import (
// TestRemoveContainer tests removing the container and its corresponding container logs. // TestRemoveContainer tests removing the container and its corresponding container logs.
func TestRemoveContainer(t *testing.T) { func TestRemoveContainer(t *testing.T) {
fakeRuntime, _, m, err := createTestRuntimeManager() fakeRuntime, _, m, err := createTestRuntimeManager()
require.NoError(t, err)
pod := &v1.Pod{ pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
UID: "12345678", UID: "12345678",

View File

@ -396,10 +396,10 @@ func (c *Configurer) SetupDNSinContainerizedMounter(mounterPath string) {
} }
if c.ResolverConfig != "" { if c.ResolverConfig != "" {
f, err := os.Open(c.ResolverConfig) f, err := os.Open(c.ResolverConfig)
defer f.Close()
if err != nil { if err != nil {
klog.Error("Could not open resolverConf file") klog.Error("Could not open resolverConf file")
} else { } else {
defer f.Close()
_, hostSearch, _, err := parseResolvConf(f) _, hostSearch, _, err := parseResolvConf(f)
if err != nil { if err != nil {
klog.Errorf("Error for parsing the resolv.conf file: %v", err) klog.Errorf("Error for parsing the resolv.conf file: %v", err)

View File

@ -46,7 +46,6 @@ go_test(
deps = [ deps = [
"//pkg/kubelet/apis/pluginregistration/v1:go_default_library", "//pkg/kubelet/apis/pluginregistration/v1:go_default_library",
"//pkg/kubelet/config:go_default_library", "//pkg/kubelet/config:go_default_library",
"//pkg/kubelet/pluginmanager/cache:go_default_library",
"//pkg/kubelet/pluginmanager/pluginwatcher:go_default_library", "//pkg/kubelet/pluginmanager/pluginwatcher:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library",

View File

@ -134,11 +134,9 @@ func (e *examplePlugin) Serve(services ...string) error {
case "v1beta1": case "v1beta1":
v1beta1 := &pluginServiceV1Beta1{server: e} v1beta1 := &pluginServiceV1Beta1{server: e}
v1beta1.RegisterService() v1beta1.RegisterService()
break
case "v1beta2": case "v1beta2":
v1beta2 := &pluginServiceV1Beta2{server: e} v1beta2 := &pluginServiceV1Beta2{server: e}
v1beta2.RegisterService() v1beta2.RegisterService()
break
default: default:
return fmt.Errorf("Unsupported service: '%s'", service) return fmt.Errorf("Unsupported service: '%s'", service)
} }

View File

@ -208,8 +208,6 @@ func (f *RemoteRuntime) ExecSync(ctx context.Context, req *kubeapi.ExecSyncReque
return nil, err return nil, err
} }
exitCode = int32(exitError.ExitStatus()) exitCode = int32(exitError.ExitStatus())
return nil, err
} }
return &kubeapi.ExecSyncResponse{ return &kubeapi.ExecSyncResponse{

View File

@ -316,29 +316,29 @@ func (p *criStatsProvider) ImageFsStats() (*statsapi.FsStats, error) {
// return the first one. // return the first one.
// //
// TODO(yguo0905): Support returning stats of multiple image filesystems. // TODO(yguo0905): Support returning stats of multiple image filesystems.
for _, fs := range resp { if len(resp) == 0 {
s := &statsapi.FsStats{ return nil, fmt.Errorf("imageFs information is unavailable")
Time: metav1.NewTime(time.Unix(0, fs.Timestamp)),
UsedBytes: &fs.UsedBytes.Value,
}
if fs.InodesUsed != nil {
s.InodesUsed = &fs.InodesUsed.Value
}
imageFsInfo := p.getFsInfo(fs.GetFsId())
if imageFsInfo != nil {
// The image filesystem id is unknown to the local node or there's
// an error on retrieving the stats. In these cases, we omit those
// stats and return the best-effort partial result. See
// https://github.com/kubernetes/heapster/issues/1793.
s.AvailableBytes = &imageFsInfo.Available
s.CapacityBytes = &imageFsInfo.Capacity
s.InodesFree = imageFsInfo.InodesFree
s.Inodes = imageFsInfo.Inodes
}
return s, nil
} }
fs := resp[0]
return nil, fmt.Errorf("imageFs information is unavailable") s := &statsapi.FsStats{
Time: metav1.NewTime(time.Unix(0, fs.Timestamp)),
UsedBytes: &fs.UsedBytes.Value,
}
if fs.InodesUsed != nil {
s.InodesUsed = &fs.InodesUsed.Value
}
imageFsInfo := p.getFsInfo(fs.GetFsId())
if imageFsInfo != nil {
// The image filesystem id is unknown to the local node or there's
// an error on retrieving the stats. In these cases, we omit those
// stats and return the best-effort partial result. See
// https://github.com/kubernetes/heapster/issues/1793.
s.AvailableBytes = &imageFsInfo.Available
s.CapacityBytes = &imageFsInfo.Capacity
s.InodesFree = imageFsInfo.InodesFree
s.Inodes = imageFsInfo.Inodes
}
return s, nil
} }
// ImageFsDevice returns name of the device where the image filesystem locates, // ImageFsDevice returns name of the device where the image filesystem locates,

View File

@ -150,6 +150,7 @@ func (m *manager) Start() {
} }
klog.Info("Starting to sync pod status with apiserver") klog.Info("Starting to sync pod status with apiserver")
//lint:ignore SA1015 Ticker can link since this is only called once and doesn't handle termination.
syncTicker := time.Tick(syncPeriod) syncTicker := time.Tick(syncPeriod)
// syncPod and syncBatch share the same go routine to avoid sync races. // syncPod and syncBatch share the same go routine to avoid sync races.
go wait.Forever(func() { go wait.Forever(func() {

View File

@ -88,9 +88,8 @@ func GetValidatedSources(sources []string) ([]string, error) {
return []string{FileSource, HTTPSource, ApiserverSource}, nil return []string{FileSource, HTTPSource, ApiserverSource}, nil
case FileSource, HTTPSource, ApiserverSource: case FileSource, HTTPSource, ApiserverSource:
validated = append(validated, source) validated = append(validated, source)
break
case "": case "":
break // Skip
default: default:
return []string{}, fmt.Errorf("unknown pod source %q", source) return []string{}, fmt.Errorf("unknown pod source %q", source)
} }

View File

@ -42,7 +42,7 @@ func TestGetValidatedSources(t *testing.T) {
require.Len(t, sources, 3) require.Len(t, sources, 3)
// Unknown source. // Unknown source.
sources, err = GetValidatedSources([]string{"taco"}) _, err = GetValidatedSources([]string{"taco"})
require.Error(t, err) require.Error(t, err)
} }

View File

@ -68,5 +68,5 @@ func aggregatePods(pods []*v1.Pod, handler podHandler) string {
for _, pod := range pods { for _, pod := range pods {
podStrings = append(podStrings, handler(pod)) podStrings = append(podStrings, handler(pod))
} }
return fmt.Sprintf(strings.Join(podStrings, ", ")) return strings.Join(podStrings, ", ")
} }

View File

@ -43,6 +43,7 @@ go_test(
"//pkg/volume/util/types:go_default_library", "//pkg/volume/util/types:go_default_library",
"//staging/src/k8s.io/api/core/v1:go_default_library", "//staging/src/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/github.com/stretchr/testify/require:go_default_library",
], ],
) )

View File

@ -19,6 +19,7 @@ package cache
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume"
@ -359,8 +360,10 @@ func Test_AddTwoPodsToVolume_Positive(t *testing.T) {
volumeSpec2 := &volume.Spec{Volume: &pod2.Spec.Volumes[0]} volumeSpec2 := &volume.Spec{Volume: &pod2.Spec.Volumes[0]}
generatedVolumeName1, err := util.GetUniqueVolumeNameFromSpec( generatedVolumeName1, err := util.GetUniqueVolumeNameFromSpec(
plugin, volumeSpec1) plugin, volumeSpec1)
require.NoError(t, err)
generatedVolumeName2, err := util.GetUniqueVolumeNameFromSpec( generatedVolumeName2, err := util.GetUniqueVolumeNameFromSpec(
plugin, volumeSpec2) plugin, volumeSpec2)
require.NoError(t, err)
if generatedVolumeName1 != generatedVolumeName2 { if generatedVolumeName1 != generatedVolumeName2 {
t.Fatalf( t.Fatalf(
@ -466,6 +469,7 @@ func Test_AddPodToVolume_Negative_VolumeDoesntExist(t *testing.T) {
volumeName, err := util.GetUniqueVolumeNameFromSpec( volumeName, err := util.GetUniqueVolumeNameFromSpec(
plugin, volumeSpec) plugin, volumeSpec)
require.NoError(t, err)
podName := util.GetUniquePodName(pod) podName := util.GetUniquePodName(pod)