From 2b0838ba37d35e5fb9e364376be184032b49d0b0 Mon Sep 17 00:00:00 2001 From: liyao Date: Wed, 5 Apr 2023 23:14:58 +0800 Subject: [PATCH] chore(ci): add golangci-lint and refactor according to the result (#294) * chore: add golangci-lint check config and update Makefile for check * fix: fix according to golangci-lint * fix: rename Api to API * fix: fix sharedVolumeAndMountBuild SetVolumeMountSize non-zero slice * fix: remove overlapped Build method from shardingSphereProxyContainerBuilder * chore: add license header --- shardingsphere-operator/.golangci.yml | 85 ++++++++++++++ shardingsphere-operator/Makefile | 9 ++ .../api/v1alpha1/compute_node_types.go | 3 +- .../api/v1alpha1/proxy_status.go | 7 +- .../controllers/compute_node_controller.go | 4 +- .../compute_node_controller_test.go | 111 ++++++++++++++++++ .../pkg/controllers/proxy_controller.go | 2 +- .../pkg/controllers/proxyconfig_controller.go | 2 +- .../pkg/reconcile/computenode/configmap.go | 4 +- .../reconcile/computenode/configmap_test.go | 4 +- .../pkg/reconcile/computenode/deployment.go | 26 ++-- .../reconcile/computenode/deployment_test.go | 27 ++--- .../pkg/reconcile/computenode/service.go | 19 ++- .../pkg/reconcile/computenode/service_test.go | 3 +- .../pkg/reconcile/proxy/deployment.go | 12 +- .../pkg/reconcile/proxy/deployment_test.go | 2 +- .../pkg/reconcile/proxy/service.go | 2 +- .../pkg/webhook/webhook.go | 11 +- 18 files changed, 265 insertions(+), 68 deletions(-) create mode 100644 shardingsphere-operator/.golangci.yml create mode 100644 shardingsphere-operator/pkg/controllers/compute_node_controller_test.go diff --git a/shardingsphere-operator/.golangci.yml b/shardingsphere-operator/.golangci.yml new file mode 100644 index 00000000..1b9b6ce0 --- /dev/null +++ b/shardingsphere-operator/.golangci.yml @@ -0,0 +1,85 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +run: + timeout: 10m +linters: + disable-all: true + enable: + - ineffassign + - typecheck + - varcheck + - unused + - structcheck + - deadcode + - gosimple + - goimports + - errcheck + - staticcheck + - stylecheck + - gosec + - asciicheck + - bodyclose + - exportloopref + - rowserrcheck + - makezero + - durationcheck + - prealloc + - predeclared + +# Refers: https://gist.github.com/maratori/47a4d00457a92aa426dbd48a18776322 +linters-settings: + cyclop: + # The maximal code complexity to report. + # Default: 10 + max-complexity: 30 + # The maximal average package complexity. + # If it's higher than 0.0 (float) the check is enabled + # Default: 0.0 + package-average: 10.0 + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 100 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: 50 + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 20 +issues: + exclude-rules: + - path: _test\.go + linters: + - errcheck + - gosec + - rowserrcheck + - makezero diff --git a/shardingsphere-operator/Makefile b/shardingsphere-operator/Makefile index 00096d0a..3fc269a2 100644 --- a/shardingsphere-operator/Makefile +++ b/shardingsphere-operator/Makefile @@ -111,6 +111,7 @@ $(LOCALBIN): KUSTOMIZE ?= $(LOCALBIN)/kustomize CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen ENVTEST ?= $(LOCALBIN)/setup-envtest +CHECK_LINT?= $(LOCALBIN)/setup-golangci-lint ## Tool Versions KUSTOMIZE_VERSION ?= v4.5.7 @@ -131,3 +132,11 @@ $(CONTROLLER_GEN): $(LOCALBIN) envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. $(ENVTEST): $(LOCALBIN) GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest + +.PHONY: check +check: check-lint + +.PHONY: check-lint +check-lint: $(CHECK_LINT) ## Download golangci-lint-setup locally if necessary. +$(CHECK_LINT): $(LOCALBIN) + GOBIN=$(LOCALBIN) CGO_ENABLED=0 golangci-lint run -v diff --git a/shardingsphere-operator/api/v1alpha1/compute_node_types.go b/shardingsphere-operator/api/v1alpha1/compute_node_types.go index 7e9a5501..9f073853 100644 --- a/shardingsphere-operator/api/v1alpha1/compute_node_types.go +++ b/shardingsphere-operator/api/v1alpha1/compute_node_types.go @@ -19,7 +19,6 @@ package v1alpha1 import ( corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -274,7 +273,7 @@ type ComputeNodeSpec struct { // +optional Env []corev1.EnvVar `json:"env,omitempty"` // +optional - Resources v1.ResourceRequirements `json:"resources,omitempty"` + Resources corev1.ResourceRequirements `json:"resources,omitempty"` // +optional PortBindings []PortBinding `json:"portBindings,omitempty" yaml:"portBinding"` diff --git a/shardingsphere-operator/api/v1alpha1/proxy_status.go b/shardingsphere-operator/api/v1alpha1/proxy_status.go index 30641419..238230f3 100644 --- a/shardingsphere-operator/api/v1alpha1/proxy_status.go +++ b/shardingsphere-operator/api/v1alpha1/proxy_status.go @@ -19,7 +19,6 @@ package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type PhaseStatus string @@ -67,7 +66,7 @@ type Conditions []Condition // | NotReady | Failed | ShardingSphere-Proxy failed to start correctly due to some problems| type Condition struct { - Type ConditionType `json:"type"` - Status v1.ConditionStatus `json:"status"` - LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty"` + Type ConditionType `json:"type"` + Status metav1.ConditionStatus `json:"status"` + LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty"` } diff --git a/shardingsphere-operator/pkg/controllers/compute_node_controller.go b/shardingsphere-operator/pkg/controllers/compute_node_controller.go index cb1a3891..6582d9a7 100644 --- a/shardingsphere-operator/pkg/controllers/compute_node_controller.go +++ b/shardingsphere-operator/pkg/controllers/compute_node_controller.go @@ -299,7 +299,7 @@ func newConditions(conditions []v1alpha1.ComputeNodeCondition, cond v1alpha1.Com } found := false - for idx, _ := range conditions { + for idx := range conditions { if conditions[idx].Type == cond.Type { conditions[idx].LastUpdateTime = cond.LastUpdateTime conditions[idx].Status = cond.Status @@ -322,7 +322,7 @@ func updateReadyConditions(conditions []v1alpha1.ComputeNodeCondition, cond v1al func updateNotReadyConditions(conditions []v1alpha1.ComputeNodeCondition, cond v1alpha1.ComputeNodeCondition) []v1alpha1.ComputeNodeCondition { cur := newConditions(conditions, cond) - for idx, _ := range cur { + for idx := range cur { if cur[idx].Type == v1alpha1.ComputeNodeConditionReady { cur[idx].LastUpdateTime = metav1.Now() cur[idx].Status = v1alpha1.ConditionStatusFalse diff --git a/shardingsphere-operator/pkg/controllers/compute_node_controller_test.go b/shardingsphere-operator/pkg/controllers/compute_node_controller_test.go new file mode 100644 index 00000000..7b791f43 --- /dev/null +++ b/shardingsphere-operator/pkg/controllers/compute_node_controller_test.go @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package controllers + +import ( + "testing" + + v1 "k8s.io/api/core/v1" +) + +func Test_GetReadyProxyInstances(t *testing.T) { + // create sample PodList + podlist := v1.PodList{ + Items: []v1.Pod{ + { + Status: v1.PodStatus{ + Phase: v1.PodRunning, + Conditions: []v1.PodCondition{ + { + Type: v1.PodReady, + Status: v1.ConditionTrue, + }, + }, + ContainerStatuses: []v1.ContainerStatus{ + { + Name: "shardingsphere-proxy", + Ready: true, + }, + }, + }, + }, + { + Status: v1.PodStatus{ + Phase: v1.PodRunning, + Conditions: []v1.PodCondition{ + { + Type: v1.PodReady, + Status: v1.ConditionTrue, + }, + }, + ContainerStatuses: []v1.ContainerStatus{ + { + Name: "another-container", + Ready: true, + }, + }, + }, + }, + { + Status: v1.PodStatus{ + Phase: v1.PodRunning, + Conditions: []v1.PodCondition{ + { + Type: v1.PodReady, + Status: v1.ConditionFalse, + }, + }, + ContainerStatuses: []v1.ContainerStatus{ + { + Name: "shardingsphere-proxy", + Ready: false, + }, + }, + }, + }, + { + Status: v1.PodStatus{ + Phase: v1.PodPending, + Conditions: []v1.PodCondition{ + { + Type: v1.PodReady, + Status: v1.ConditionTrue, + }, + }, + ContainerStatuses: []v1.ContainerStatus{ + { + Name: "shardingsphere-proxy", + Ready: true, + }, + }, + }, + }, + }, + } + + // expected result is 1 because only one pod has a ready shardingsphere-proxy container + expected := int32(1) + + // call the function to get the actual result + actual := getReadyProxyInstances(podlist) + + // compare the expected and actual results + if actual != expected { + t.Errorf("getReadyInstances returned %d, expected %d", actual, expected) + } +} diff --git a/shardingsphere-operator/pkg/controllers/proxy_controller.go b/shardingsphere-operator/pkg/controllers/proxy_controller.go index c9703930..3bddc73d 100644 --- a/shardingsphere-operator/pkg/controllers/proxy_controller.go +++ b/shardingsphere-operator/pkg/controllers/proxy_controller.go @@ -66,7 +66,7 @@ type ProxyReconciler struct { // move the current state of the cluster closer to the desired state. func (r *ProxyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := r.Log.WithValues(computeNodeControllerName, req.NamespacedName) + logger := r.Log.WithValues(proxyControllerName, req.NamespacedName) rt, err := r.getRuntimeShardingSphereProxy(ctx, req.NamespacedName) if apierrors.IsNotFound(err) { diff --git a/shardingsphere-operator/pkg/controllers/proxyconfig_controller.go b/shardingsphere-operator/pkg/controllers/proxyconfig_controller.go index 2cb41bcb..cb960ab1 100644 --- a/shardingsphere-operator/pkg/controllers/proxyconfig_controller.go +++ b/shardingsphere-operator/pkg/controllers/proxyconfig_controller.go @@ -60,7 +60,7 @@ type ProxyConfigReconciler struct { // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.11.0/pkg/reconcile func (r *ProxyConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { - logger := r.Log.WithValues(computeNodeControllerName, req.NamespacedName) + logger := r.Log.WithValues(proxyConfigControllerName, req.NamespacedName) run := &shardingspherev1alpha1.ShardingSphereProxyServerConfig{} err := r.Get(ctx, req.NamespacedName, run) diff --git a/shardingsphere-operator/pkg/reconcile/computenode/configmap.go b/shardingsphere-operator/pkg/reconcile/computenode/configmap.go index 8a2d5326..f59ccb38 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/configmap.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/configmap.go @@ -61,7 +61,9 @@ func NewConfigMap(cn *v1alpha1.ComputeNode) *v1.ConfigMap { servconf := cn.Spec.Bootstrap.ServerConfig.DeepCopy() if cn.Spec.Bootstrap.ServerConfig.Mode.Type == v1alpha1.ModeTypeCluster { if len(cluster) > 0 { - json.Unmarshal([]byte(cluster), &servconf.Mode.Repository) + if err := json.Unmarshal([]byte(cluster), &servconf.Mode.Repository); err != nil { + return &v1.ConfigMap{} + } } } if y, err := yaml.Marshal(servconf); err == nil { diff --git a/shardingsphere-operator/pkg/reconcile/computenode/configmap_test.go b/shardingsphere-operator/pkg/reconcile/computenode/configmap_test.go index d2fd027c..3574a683 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/configmap_test.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/configmap_test.go @@ -28,8 +28,8 @@ import ( var _ = Describe("ConfigMap", func() { var ( - expect *corev1.ConfigMap = &corev1.ConfigMap{} - cn *v1alpha1.ComputeNode = &v1alpha1.ComputeNode{ + expect = &corev1.ConfigMap{} + cn = &v1alpha1.ComputeNode{ ObjectMeta: metav1.ObjectMeta{ Name: "test_name", Namespace: "test_namespace", diff --git a/shardingsphere-operator/pkg/reconcile/computenode/deployment.go b/shardingsphere-operator/pkg/reconcile/computenode/deployment.go index f54d81cb..96c655d3 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/deployment.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/deployment.go @@ -22,7 +22,6 @@ import ( "github.com/apache/shardingsphere-on-cloud/shardingsphere-operator/api/v1alpha1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -94,11 +93,6 @@ func NewShardingSphereProxyContainerBuilder() ShardingSphereProxyContainerBuilde } } -// Build returns a Container -func (b *shardingSphereProxyContainerBuilder) Build() *corev1.Container { - return b.ContainerBuilder.Build() -} - // BootstrapContainerBuilder returns a Container for initialization // The container will handle initilialization in Pod's InitContainer type BootstrapContainerBuilder interface { @@ -406,7 +400,7 @@ func (b *sharedVolumeAndMountBuilder) SetVolumeMountSize(size int) SharedVolumeA if len(b.volumeMounts) != size { vms := make([]*corev1.VolumeMount, size) for vm := range b.volumeMounts { - vms = append(vms, b.volumeMounts[vm].DeepCopy()) + vms[vm] = b.volumeMounts[vm].DeepCopy() } b.volumeMounts = vms } @@ -541,7 +535,7 @@ func (d *deploymentBuilder) Build() *appsv1.Deployment { } // NewDeployment creates a new Deployment -func NewDeployment(cn *v1alpha1.ComputeNode) *v1.Deployment { +func NewDeployment(cn *v1alpha1.ComputeNode) *appsv1.Deployment { builder := NewDeploymentBuilder(cn.GetObjectMeta(), cn.GetObjectKind().GroupVersionKind()) builder.SetName(cn.Name).SetNamespace(cn.Namespace).SetLabelsAndSelectors(cn.Labels, cn.Spec.Selector).SetAnnotations(cn.Annotations).SetReplicas(&cn.Spec.Replicas) @@ -681,11 +675,11 @@ func (d *deploymentBuilder) SetAgentBin(scb ContainerBuilder, cn *v1alpha1.Compu } // DefaultDeployment describes the default deployment -func DefaultDeployment(meta metav1.Object, gvk schema.GroupVersionKind) *v1.Deployment { +func DefaultDeployment(meta metav1.Object, gvk schema.GroupVersionKind) *appsv1.Deployment { defaultMaxUnavailable := intstr.FromInt(0) defaultMaxSurge := intstr.FromInt(3) - return &v1.Deployment{ + return &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "shardingsphere-proxy", Namespace: "default", @@ -694,10 +688,10 @@ func DefaultDeployment(meta metav1.Object, gvk schema.GroupVersionKind) *v1.Depl *metav1.NewControllerRef(meta, gvk), }, }, - Spec: v1.DeploymentSpec{ - Strategy: v1.DeploymentStrategy{ - Type: v1.RollingUpdateDeploymentStrategyType, - RollingUpdate: &v1.RollingUpdateDeployment{ + Spec: appsv1.DeploymentSpec{ + Strategy: appsv1.DeploymentStrategy{ + Type: appsv1.RollingUpdateDeploymentStrategyType, + RollingUpdate: &appsv1.RollingUpdateDeployment{ MaxUnavailable: &defaultMaxUnavailable, MaxSurge: &defaultMaxSurge, }, @@ -742,8 +736,8 @@ func DefaultDeployment(meta metav1.Object, gvk schema.GroupVersionKind) *v1.Depl } // UpdateDeployment updates the deployment -func UpdateDeployment(cn *v1alpha1.ComputeNode, cur *v1.Deployment) *v1.Deployment { - exp := &v1.Deployment{} +func UpdateDeployment(cn *v1alpha1.ComputeNode, cur *appsv1.Deployment) *appsv1.Deployment { + exp := &appsv1.Deployment{} exp.ObjectMeta = cur.ObjectMeta exp.ObjectMeta.ResourceVersion = "" exp.Labels = cur.Labels diff --git a/shardingsphere-operator/pkg/reconcile/computenode/deployment_test.go b/shardingsphere-operator/pkg/reconcile/computenode/deployment_test.go index 5cfb738e..c49e1b1f 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/deployment_test.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/deployment_test.go @@ -24,7 +24,6 @@ import ( "github.com/apache/shardingsphere-on-cloud/shardingsphere-operator/api/v1alpha1" "github.com/stretchr/testify/assert" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" @@ -38,7 +37,7 @@ func Test_NewDeployment(t *testing.T) { cases := []struct { id int cn *v1alpha1.ComputeNode - exp *v1.Deployment + exp *appsv1.Deployment message string }{ { @@ -105,7 +104,7 @@ func Test_NewDeployment(t *testing.T) { }, }, }, - exp: &v1.Deployment{ + exp: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", Namespace: "test-namespace", @@ -117,11 +116,11 @@ func Test_NewDeployment(t *testing.T) { "anno1": "value1", }, }, - Spec: v1.DeploymentSpec{ + Spec: appsv1.DeploymentSpec{ Replicas: &defaultReplicas, - Strategy: v1.DeploymentStrategy{ - Type: v1.RollingUpdateDeploymentStrategyType, - RollingUpdate: &v1.RollingUpdateDeployment{ + Strategy: appsv1.DeploymentStrategy{ + Type: appsv1.RollingUpdateDeploymentStrategyType, + RollingUpdate: &appsv1.RollingUpdateDeployment{ MaxUnavailable: &defaultMaxUnavailable, MaxSurge: &defaultMaxSurge, }, @@ -265,7 +264,7 @@ func Test_NewDeployment(t *testing.T) { }, }, }, - exp: &v1.Deployment{ + exp: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "test-java-agent", Namespace: "test-namespace", @@ -276,11 +275,11 @@ func Test_NewDeployment(t *testing.T) { "anno1": "value1", }, }, - Spec: v1.DeploymentSpec{ + Spec: appsv1.DeploymentSpec{ Replicas: &defaultReplicas, - Strategy: v1.DeploymentStrategy{ - Type: v1.RollingUpdateDeploymentStrategyType, - RollingUpdate: &v1.RollingUpdateDeployment{ + Strategy: appsv1.DeploymentStrategy{ + Type: appsv1.RollingUpdateDeploymentStrategyType, + RollingUpdate: &appsv1.RollingUpdateDeployment{ MaxUnavailable: &defaultMaxUnavailable, MaxSurge: &defaultMaxSurge, }, @@ -432,14 +431,14 @@ func assertObjectMeta(t *testing.T, exp, act metav1.ObjectMeta) bool { assert.Equal(t, exp.Labels, act.Labels, "labels should be equal") } -func assertDeploymentSpec(t *testing.T, exp, act v1.DeploymentSpec) bool { +func assertDeploymentSpec(t *testing.T, exp, act appsv1.DeploymentSpec) bool { return assertRollingUpdateDeployment(t, *exp.Strategy.RollingUpdate, *act.Strategy.RollingUpdate) && assert.Equal(t, exp.Selector, act.Selector, "selectors should be equal") && assert.Equal(t, exp.Replicas, act.Replicas, "replicas should be equal") && assertTemplateSpec(t, exp.Template, act.Template) } -func assertRollingUpdateDeployment(t *testing.T, exp, act v1.RollingUpdateDeployment) bool { +func assertRollingUpdateDeployment(t *testing.T, exp, act appsv1.RollingUpdateDeployment) bool { return assert.Equal(t, exp.MaxSurge, act.MaxSurge, "maxSurge should be equal") && assert.Equal(t, exp.MaxUnavailable, act.MaxUnavailable, "maxUnavailable should be equal") } diff --git a/shardingsphere-operator/pkg/reconcile/computenode/service.go b/shardingsphere-operator/pkg/reconcile/computenode/service.go index 4b01c952..0f52225d 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/service.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/service.go @@ -20,18 +20,17 @@ package computenode import ( "github.com/apache/shardingsphere-on-cloud/shardingsphere-operator/api/v1alpha1" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/intstr" ) // NewService returns a new Service -func NewService(cn *v1alpha1.ComputeNode) *v1.Service { +func NewService(cn *v1alpha1.ComputeNode) *corev1.Service { builder := NewServiceBuilder(cn.GetObjectMeta(), cn.GetObjectKind().GroupVersionKind()) builder.SetName(cn.Name).SetNamespace(cn.Namespace).SetLabelsAndSelectors(cn.Labels, cn.Spec.Selector).SetAnnotations(cn.Annotations).SetType(cn.Spec.ServiceType) - ports := []v1.ServicePort{} + ports := []corev1.ServicePort{} for _, pb := range cn.Spec.PortBindings { ports = append(ports, corev1.ServicePort{ Name: pb.Name, @@ -100,7 +99,7 @@ func (s *serviceBuilder) SetType(t corev1.ServiceType) ServiceBuilder { // SetPorts sets ports of Service func (s *serviceBuilder) SetPorts(ports []corev1.ServicePort) ServiceBuilder { if s.service.Spec.Ports == nil { - s.service.Spec.Ports = []v1.ServicePort{} + s.service.Spec.Ports = []corev1.ServicePort{} } s.service.Spec.Ports = ports return s @@ -112,8 +111,8 @@ func (s *serviceBuilder) Build() *corev1.Service { } // DefaultService returns the default Service -func DefaultService(meta metav1.Object, gvk schema.GroupVersionKind) *v1.Service { - return &v1.Service{ +func DefaultService(meta metav1.Object, gvk schema.GroupVersionKind) *corev1.Service { + return &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "shardingsphere-proxy", Namespace: "default", @@ -122,16 +121,16 @@ func DefaultService(meta metav1.Object, gvk schema.GroupVersionKind) *v1.Service *metav1.NewControllerRef(meta, gvk), }, }, - Spec: v1.ServiceSpec{ + Spec: corev1.ServiceSpec{ Selector: map[string]string{}, - Type: v1.ServiceTypeClusterIP, + Type: corev1.ServiceTypeClusterIP, }, } } // UpdateService update Service -func UpdateService(cn *v1alpha1.ComputeNode, cur *v1.Service) *v1.Service { - exp := &v1.Service{} +func UpdateService(cn *v1alpha1.ComputeNode, cur *corev1.Service) *corev1.Service { + exp := &corev1.Service{} exp.ObjectMeta = cur.ObjectMeta exp.Labels = cur.Labels exp.Annotations = cur.Annotations diff --git a/shardingsphere-operator/pkg/reconcile/computenode/service_test.go b/shardingsphere-operator/pkg/reconcile/computenode/service_test.go index 84db296a..924b8085 100644 --- a/shardingsphere-operator/pkg/reconcile/computenode/service_test.go +++ b/shardingsphere-operator/pkg/reconcile/computenode/service_test.go @@ -25,7 +25,6 @@ import ( "github.com/apache/shardingsphere-on-cloud/shardingsphere-operator/api/v1alpha1" "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" ) @@ -239,7 +238,7 @@ func TestUpdateService(t *testing.T) { cur.ObjectMeta = metav1.ObjectMeta{Name: "test-service", Namespace: "test-ns"} cur.Labels = map[string]string{"key": "val"} cur.Annotations = map[string]string{"anno": "val"} - cur.Spec = corev1.ServiceSpec{ClusterIP: "10.96.0.1", Ports: []v1.ServicePort{{Name: "test-port", Port: 80}}} + cur.Spec = corev1.ServiceSpec{ClusterIP: "10.96.0.1", Ports: []corev1.ServicePort{{Name: "test-port", Port: 80}}} exp := &corev1.Service{} // Setting up some expected data for exp instance diff --git a/shardingsphere-operator/pkg/reconcile/proxy/deployment.go b/shardingsphere-operator/pkg/reconcile/proxy/deployment.go index 604a52d5..22027e87 100644 --- a/shardingsphere-operator/pkg/reconcile/proxy/deployment.go +++ b/shardingsphere-operator/pkg/reconcile/proxy/deployment.go @@ -259,7 +259,7 @@ func updatePodTemplateSpec(proxy *v1alpha1.ShardingSphereProxy, act *v1.Deployme exp := act.Spec.Template.DeepCopy() SSProxyContainer := updateSSProxyContainer(proxy, act) - for i, _ := range exp.Spec.Containers { + for i := range exp.Spec.Containers { if exp.Spec.Containers[i].Name == "proxy" { exp.Spec.Containers[i] = *SSProxyContainer } @@ -267,7 +267,7 @@ func updatePodTemplateSpec(proxy *v1alpha1.ShardingSphereProxy, act *v1.Deployme if proxy.Spec.MySQLDriver != nil { initContainer := updateInitContainer(proxy, act) - for i, _ := range exp.Spec.InitContainers { + for i := range exp.Spec.InitContainers { if exp.Spec.InitContainers[i].Name == "download-mysql-connect" { exp.Spec.InitContainers[i] = *initContainer } @@ -292,7 +292,7 @@ func updateInitContainer(proxy *v1alpha1.ShardingSphereProxy, act *v1.Deployment for _, c := range act.Spec.Template.Spec.InitContainers { if c.Name == "download-mysql-connect" { - for i, _ := range c.Env { + for i := range c.Env { if c.Env[i].Name == "VERSION" { if c.Env[i].Value != proxy.Spec.MySQLDriver.Version { c.Env[i].Value = proxy.Spec.MySQLDriver.Version @@ -332,7 +332,7 @@ func updateSSProxyContainer(proxy *v1alpha1.ShardingSphereProxy, act *v1.Deploym exp.StartupProbe = proxy.Spec.StartupProbe } - for i, _ := range c.Env { + for i := range c.Env { if c.Env[i].Name == "PORT" { proxyPort := strconv.FormatInt(int64(proxy.Spec.Port), 10) if c.Env[i].Value != proxyPort { @@ -403,7 +403,7 @@ func newConditions(conditions []v1alpha1.Condition, cond v1alpha1.Condition) []v } found := false - for idx, _ := range conditions { + for idx := range conditions { if conditions[idx].Type == cond.Type { conditions[idx].LastUpdateTime = cond.LastUpdateTime conditions[idx].Status = cond.Status @@ -426,7 +426,7 @@ func updateReadyConditions(conditions []v1alpha1.Condition, cond v1alpha1.Condit func updateNotReadyConditions(conditions []v1alpha1.Condition, cond v1alpha1.Condition) []v1alpha1.Condition { cur := newConditions(conditions, cond) - for idx, _ := range cur { + for idx := range cur { if cur[idx].Type == v1alpha1.ConditionReady { cur[idx].LastUpdateTime = metav1.Now() cur[idx].Status = metav1.ConditionFalse diff --git a/shardingsphere-operator/pkg/reconcile/proxy/deployment_test.go b/shardingsphere-operator/pkg/reconcile/proxy/deployment_test.go index 0c8b6d82..78dc4b35 100644 --- a/shardingsphere-operator/pkg/reconcile/proxy/deployment_test.go +++ b/shardingsphere-operator/pkg/reconcile/proxy/deployment_test.go @@ -760,7 +760,7 @@ func assertConditions(t *testing.T, exp, act []v1alpha1.Condition, message strin if !assert.Equal(t, len(exp), len(act), message) { return false } - for idx, _ := range exp { + for idx := range exp { if !assert.Equal(t, exp[idx].Type, act[idx].Type, message) { return false } diff --git a/shardingsphere-operator/pkg/reconcile/proxy/service.go b/shardingsphere-operator/pkg/reconcile/proxy/service.go index 4a3c8529..33157dac 100644 --- a/shardingsphere-operator/pkg/reconcile/proxy/service.go +++ b/shardingsphere-operator/pkg/reconcile/proxy/service.go @@ -66,7 +66,7 @@ func ConstructCascadingService(proxy *v1alpha1.ShardingSphereProxy) *v1.Service // UpdateService updates the specified service with ShardingSphereProxy func UpdateService(proxy *v1alpha1.ShardingSphereProxy, runtimeService *v1.Service) *v1.Service { - exp := &v1.Service{} + var exp *v1.Service runtimeService.Spec.Type = proxy.Spec.ServiceType.Type runtimeService.Spec.Ports[0].Port = proxy.Spec.Port runtimeService.Spec.Ports[0].TargetPort = fromInt32(proxy.Spec.Port) diff --git a/shardingsphere-operator/pkg/webhook/webhook.go b/shardingsphere-operator/pkg/webhook/webhook.go index 64df3384..4144677a 100644 --- a/shardingsphere-operator/pkg/webhook/webhook.go +++ b/shardingsphere-operator/pkg/webhook/webhook.go @@ -19,17 +19,18 @@ package webhook import ( "errors" + "net/http" + "net/url" + "strings" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/rest" - "net/http" - "net/url" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "sigs.k8s.io/controller-runtime/pkg/webhook/conversion" - "strings" ) var log = logf.Log.WithName("builder") @@ -205,10 +206,10 @@ func (blder *WebhookBuilder) isAlreadyHandled(path string) bool { } func (blder *WebhookBuilder) registerApiservice() { - blder.mgr.GetWebhookServer().Register(apiPath, getApiService()) + blder.mgr.GetWebhookServer().Register(apiPath, getAPIService()) } -func getApiService() http.HandlerFunc { +func getAPIService() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte("{}"))