Skip to content

Commit daff1b1

Browse files
committed
golangci-lint: fmt code
1 parent c46d2c4 commit daff1b1

File tree

30 files changed

+104
-105
lines changed

30 files changed

+104
-105
lines changed

.golangci.yaml

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
run:
2+
skip-files:
3+
- ".*_test.go"
4+
- pkg/utils/http/reverse_proxy.go
5+
- pkg/proxy/apiserver/options.go
6+
skip-dirs:
7+
- vendor/
8+
9+
linters:
10+
disable:
11+
- errcheck
12+
- unused

e2e/customoperator/app/controller/util.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,14 @@ func add(c client.Client, namespace, kind string) error {
6969
if cm.Data == nil {
7070
cm.Data = map[string]string{}
7171
}
72-
val, _ := cm.Data[key]
72+
val := cm.Data[key]
7373
sto := &store{}
7474
if val == "" {
7575
sto.Kinds = map[string]string{}
7676
} else {
7777
json.Unmarshal([]byte(val), sto)
7878
}
79-
names, _ := sto.Kinds[kind]
79+
names := sto.Kinds[kind]
8080
nameSet := list(names)
8181
if nameSet.Has(namespace) {
8282
return nil

e2e/customoperator/app/main.go

-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package main
1919
import (
2020
"flag"
2121
"fmt"
22-
"math/rand"
2322
_ "net/http/pprof"
2423
"os"
2524
"time"
@@ -60,8 +59,6 @@ func main() {
6059
pflag.Parse()
6160
ctrl.SetLogger(klogr.New())
6261

63-
rand.Seed(time.Now().UnixNano())
64-
6562
cfg := ctrl.GetConfigOrDie()
6663
cfg.UserAgent = "testapp"
6764

pkg/cmd/manager/main.go

-4
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@ package main
1818

1919
import (
2020
"flag"
21-
"math/rand"
2221
"net/http"
2322
_ "net/http/pprof"
2423
"os"
25-
"time"
2624

2725
"github.com/spf13/pflag"
2826
"k8s.io/apimachinery/pkg/runtime"
@@ -82,8 +80,6 @@ func main() {
8280
pflag.Parse()
8381
ctrl.SetLogger(klogr.New())
8482

85-
rand.Seed(time.Now().UnixNano())
86-
8783
go func() {
8884
if err := http.ListenAndServe(pprofAddr, nil); err != nil {
8985
setupLog.Error(err, "unable to start pprof")

pkg/cmd/proxy/main.go

+4-11
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,9 @@ import (
2020
"context"
2121
"flag"
2222
"fmt"
23-
"math/rand"
2423
"net"
2524
"net/http"
2625
"os"
27-
"time"
2826

2927
"github.com/prometheus/client_golang/prometheus/promhttp"
3028
"github.com/spf13/pflag"
@@ -53,7 +51,6 @@ var (
5351
)
5452

5553
func main() {
56-
rand.Seed(time.Now().UnixNano())
5754
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
5855
pflag.Parse()
5956

@@ -106,15 +103,11 @@ func main() {
106103

107104
serveHTTP(ctx, readyHandler)
108105
if stoppedWebhook != nil {
109-
select {
110-
case <-stoppedWebhook:
111-
klog.Infof("Webhook proxy stopped")
112-
}
113-
}
114-
select {
115-
case <-stoppedApiserver:
116-
klog.Infof("Apiserver proxy stopped")
106+
<-stoppedWebhook
107+
klog.Infof("Webhook proxy stopped")
117108
}
109+
<-stoppedApiserver
110+
klog.Infof("Apiserver proxy stopped")
118111
}
119112

120113
func serveHTTP(ctx context.Context, readyHandler *healthz.Handler) {

pkg/grpcregistry/grpc_registry.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,12 @@ func (r *grpcRegistry) Start(ctx context.Context) error {
9898
return fmt.Errorf("error listening grpc server address %s: %v", addr, err)
9999
}
100100
klog.Infof("Start listening gRPC server with leaderElection=%v on %s", r.needLeaderElection, addr)
101-
go grpcServer.Serve(lis)
101+
go func() {
102+
if err = grpcServer.Serve(lis); err != nil {
103+
klog.Errorf("serve gRPC error %v", err)
104+
}
105+
}()
106+
102107
<-ctx.Done()
103108
return nil
104109
}

pkg/manager/controllers/patchrunnable/labelpatch_runnable.go

-1
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,6 @@ func (p *PatchRunnable) setInvalid(gvk schema.GroupVersionKind) {
282282
p.invalidL.Lock()
283283
defer p.invalidL.Unlock()
284284
p.invalid.Insert(groupVersionKindKey(gvk))
285-
return
286285
}
287286

288287
func groupVersionKindKey(gvk schema.GroupVersionKind) string {

pkg/manager/controllers/patchrunnable/patchrunnable_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package patchrunnable
1919
import (
2020
"context"
2121
"fmt"
22+
"math/rand"
2223
"net/url"
2324
"path/filepath"
2425
"testing"
@@ -169,3 +170,10 @@ func TestEnv(t *testing.T) {
169170
err = testEnv.Stop()
170171
g.Expect(err).NotTo(gomega.HaveOccurred())
171172
}
173+
174+
func TestRand(t *testing.T) {
175+
176+
for i := 0; i < 10; i++ {
177+
fmt.Println(rand.Int31())
178+
}
179+
}

pkg/manager/controllers/rollout/expectation.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ func SetExpectedRevision(sts *appsv1.StatefulSet, podRevision map[string]string)
5656

5757
func isUpdatedRevision(sts *appsv1.StatefulSet, po *corev1.Pod) bool {
5858
expectedRevision := recentRevision(sts)
59-
revision, _ := po.Labels[appsv1.StatefulSetRevisionLabel]
59+
revision := po.Labels[appsv1.StatefulSetRevisionLabel]
6060
return revision == expectedRevision
6161
}
6262

pkg/manager/controllers/rollout/rollout_controller.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ func isLeader(po *corev1.Pod, identity string) bool {
298298
func updateRolloutAnno(sts *appsv1.StatefulSet, upgradedPods []string) (updated bool) {
299299
msg, _ := json.Marshal(upgradedPods)
300300
val := string(msg)
301-
if upgradedPods == nil || len(upgradedPods) == 0 {
301+
if len(upgradedPods) == 0 {
302302
val = ""
303303
}
304304
if sts.Annotations == nil {

pkg/manager/controllers/shardingconfigserver/shardingconfig_controller.go

-2
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ func (r *ShardingConfigReconciler) Reconcile(ctx context.Context, req ctrl.Reque
9999
}
100100

101101
// filter and wait for all pods satisfied
102-
var activePods []*v1.Pod
103102
var syncPods []syncPod
104103
for _, pod := range allPods {
105104
if !utils.IsPodActive(pod) {
@@ -114,7 +113,6 @@ func (r *ShardingConfigReconciler) Reconcile(ctx context.Context, req ctrl.Reque
114113
klog.Warningf("Skip reconcile shardingConfig %s for Pod %s is expected to be already deleted", req, pod.Name)
115114
return reconcile.Result{}, nil
116115
}
117-
activePods = append(activePods, pod)
118116

119117
var conn *grpcSrvConnection
120118
if v, ok := cachedGrpcSrvConnection.Load(pod.UID); !ok || v == nil {

pkg/proxy/apiserver/options.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ type Options struct {
4646
SecureServingOptions *options.SecureServingOptions
4747

4848
RequestInfoResolver apirequest.RequestInfoResolver
49-
LegacyAPIGroupPrefixes sets.String
49+
LegacyAPIGroupPrefixes sets.Set[string]
5050
LongRunningFunc apirequest.LongRunningRequestCheck
5151
HandlerChainWaitGroup *utilwaitgroup.SafeWaitGroup
5252

@@ -59,7 +59,7 @@ func NewOptions() *Options {
5959
o := &Options{
6060
Config: new(rest.Config),
6161
SecureServingOptions: options.NewSecureServingOptions(),
62-
LegacyAPIGroupPrefixes: sets.NewString(DefaultLegacyAPIPrefix),
62+
LegacyAPIGroupPrefixes: sets.New[string](DefaultLegacyAPIPrefix),
6363
LongRunningFunc: genericfilters.BasicLongRunningRequestCheck(
6464
sets.NewString("watch", "proxy"),
6565
sets.NewString("attach", "exec", "proxy", "log", "portforward"),

pkg/proxy/apiserver/request.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ limitations under the License.
1818
package apiserver
1919

2020
import (
21-
"errors"
2221
"fmt"
2322
"net/http"
2423
"net/url"
@@ -68,7 +67,7 @@ func TrimUrl(inUrl *url.URL, prePath string) (*url.URL, error) {
6867
segments := clear(strings.Split(inUrl.Path, "/"))
6968
preSegments := clear(strings.Split(prePath, "/"))
7069
if len(segments) < len(preSegments) {
71-
return inUrl, errors.New(fmt.Sprintf("%s is too long than %s", prePath, inUrl.Path))
70+
return inUrl, fmt.Errorf(fmt.Sprintf("%s is too long than %s", prePath, inUrl.Path))
7271
}
7372
resultPath := ""
7473
done := true
@@ -82,7 +81,7 @@ func TrimUrl(inUrl *url.URL, prePath string) (*url.URL, error) {
8281
}
8382
}
8483
if !done {
85-
return inUrl, errors.New(fmt.Sprintf("fail to trim url, %s is not %s prefix", prePath, inUrl.Path))
84+
return inUrl, fmt.Errorf(fmt.Sprintf("fail to trim url, %s is not %s prefix", prePath, inUrl.Path))
8685
}
8786
for i := len(preSegments); i < len(segments); i++ {
8887
resultPath += "/" + segments[i]

pkg/proxy/apiserver/serializer.go

-3
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,6 @@ func (s *responseSerializer) IsWatch() bool {
172172
}
173173

174174
func (s *responseSerializer) Release() {
175-
if s.buf != nil {
176-
//pool.BytesPool.Put(s.buf.Bytes()[:s.buf.Cap()])
177-
}
178175
if s.gzipReader != nil {
179176
s.gzipReader.Close()
180177
pool.GzipReaderPool.Put(s.gzipReader)

pkg/proxy/circuitbreaker/lease.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func (l *lease) registerState(st *state) {
4848
if _, ok := l.stateSet[st]; !ok {
4949
if st.recoverAt != nil {
5050
l.stateSet[st] = struct{}{}
51-
d := st.recoverAt.Sub(time.Now())
51+
d := time.Until(st.recoverAt.Time)
5252
l.stateQueue.AddAfter(st, d)
5353
}
5454
}
@@ -62,7 +62,7 @@ func (l *lease) processingLoop() {
6262
_, _, recoverAt := st.read()
6363
if recoverAt != nil && time.Now().Before(recoverAt.Time) {
6464
// recover time changed, requeue
65-
l.stateQueue.AddAfter(st, recoverAt.Sub(time.Now()))
65+
l.stateQueue.AddAfter(st, time.Until(recoverAt.Time))
6666
} else {
6767
l.mu.Lock()
6868
delete(l.stateSet, st)

pkg/proxy/circuitbreaker/manager.go

+15-20
Original file line numberDiff line numberDiff line change
@@ -136,17 +136,15 @@ func ValidateTrafficIntercept(URL string, method string) (result *ValidateResult
136136
if indexes == nil {
137137
indexes = defaultTrafficInterceptStore.normalIndexes[indexForRest(URL, "*")]
138138
}
139-
if indexes != nil {
140-
for key := range indexes {
141-
trafficInterceptRule := defaultTrafficInterceptStore.rules[key]
142-
if trafficInterceptRule != nil {
143-
if appsv1alpha1.InterceptTypeWhite == trafficInterceptRule.InterceptType {
144-
result = &ValidateResult{Allowed: true, Reason: "white", Message: fmt.Sprintf("Traffic is allow by white rule, name: %s", trafficInterceptRule.Name)}
145-
return result
146-
} else if appsv1alpha1.InterceptTypeBlack == trafficInterceptRule.InterceptType {
147-
result = &ValidateResult{Allowed: false, Reason: "black", Message: fmt.Sprintf("Traffic is intercept by black rule, name: %s", trafficInterceptRule.Name)}
148-
return result
149-
}
139+
for key := range indexes {
140+
trafficInterceptRule := defaultTrafficInterceptStore.rules[key]
141+
if trafficInterceptRule != nil {
142+
if appsv1alpha1.InterceptTypeWhite == trafficInterceptRule.InterceptType {
143+
result = &ValidateResult{Allowed: true, Reason: "white", Message: fmt.Sprintf("Traffic is allow by white rule, name: %s", trafficInterceptRule.Name)}
144+
return result
145+
} else if appsv1alpha1.InterceptTypeBlack == trafficInterceptRule.InterceptType {
146+
result = &ValidateResult{Allowed: false, Reason: "black", Message: fmt.Sprintf("Traffic is intercept by black rule, name: %s", trafficInterceptRule.Name)}
147+
return result
150148
}
151149
}
152150
}
@@ -182,7 +180,7 @@ func ValidateTrafficIntercept(URL string, method string) (result *ValidateResult
182180
func ValidateRest(URL string, method string) (result ValidateResult) {
183181
now := time.Now()
184182
defer func() {
185-
logger.Info("validate rest", "URL", URL, "method", method, "result", result, "cost time", time.Now().Sub(now).String())
183+
logger.Info("validate rest", "URL", URL, "method", method, "result", result, "cost time", time.Since(now).String())
186184
}()
187185

188186
if !EnableCircuitBreaker {
@@ -206,7 +204,7 @@ func ValidateRest(URL string, method string) (result ValidateResult) {
206204
func ValidateRestWithOption(URL string, method string, isPre bool) (result ValidateResult) {
207205
now := time.Now()
208206
defer func() {
209-
logger.Info("validate rest", "URL", URL, "method", method, "result", result, "cost time", time.Now().Sub(now).String())
207+
logger.Info("validate rest", "URL", URL, "method", method, "result", result, "cost time", time.Since(now).String())
210208
}()
211209

212210
if !EnableCircuitBreaker {
@@ -232,7 +230,7 @@ func ValidateRestWithOption(URL string, method string, isPre bool) (result Valid
232230
func ValidateResource(namespace, apiGroup, resource, verb string) (result ValidateResult) {
233231
now := time.Now()
234232
defer func() {
235-
logger.Info("validate resource", "namespace", namespace, "apiGroup", apiGroup, "resource", resource, "verb", verb, "result", result, "cost time", time.Now().Sub(now).String())
233+
logger.Info("validate resource", "namespace", namespace, "apiGroup", apiGroup, "resource", resource, "verb", verb, "result", result, "cost time", time.Since(now).String())
236234
}()
237235

238236
if !EnableCircuitBreaker {
@@ -256,7 +254,7 @@ func ValidateResource(namespace, apiGroup, resource, verb string) (result Valida
256254
func ValidateResourceWithOption(namespace, apiGroup, resource, verb string, isPre bool) (result ValidateResult) {
257255
now := time.Now()
258256
defer func() {
259-
logger.Info("validate resource", "namespace", namespace, "apiGroup", apiGroup, "resource", resource, "verb", verb, "result", result, "cost time", time.Now().Sub(now).String())
257+
logger.Info("validate resource", "namespace", namespace, "apiGroup", apiGroup, "resource", resource, "verb", verb, "result", result, "cost time", time.Since(now).String())
260258
}()
261259

262260
if !EnableCircuitBreaker {
@@ -280,9 +278,7 @@ func ValidateResourceWithOption(namespace, apiGroup, resource, verb string, isPr
280278
func generateWildcardUrls(URL string, method string) []string {
281279
var result []string
282280
result = append(result, indexForRest(URL, method))
283-
if strings.HasSuffix(URL, "/") {
284-
URL = strings.TrimSuffix(URL, "/")
285-
}
281+
URL = strings.TrimSuffix(URL, "/")
286282
u, err := url.Parse(URL)
287283
if err != nil {
288284
logger.Error(err, "failed to url", "URL", URL, "method", method)
@@ -312,8 +308,7 @@ func generateWildcardSeeds(namespace, apiGroup, resource, verb string) []string
312308
2、if wildcard number equal, the priority order is verb > resource > apiGroup > namespace.
313309
eg. verb exist first match verb, then match resource, after match apiGroup, last match namespace
314310
*/
315-
var result []string
316-
result = []string{
311+
result := []string{
317312
// zero wildcard
318313
indexForResource(namespace, apiGroup, resource, verb),
319314
// one wildcard

pkg/proxy/circuitbreaker/store.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ var (
4444
}
4545
)
4646

47-
type index map[string]sets.String
47+
type index map[string]sets.Set[string]
4848

4949
type indices map[string]index
5050

@@ -205,7 +205,7 @@ func (s *store) updateIndices(oldOne, newOne *appsv1alpha1.Limiting, key string)
205205
for _, indexValue := range indexValues {
206206
set := idx[indexValue]
207207
if set == nil {
208-
set = sets.String{}
208+
set = sets.New[string]()
209209
idx[indexValue] = set
210210
}
211211
set.Insert(key)
@@ -317,15 +317,15 @@ type trafficInterceptStore struct {
317317
// rules cache, key is {cb.namespace}:{cb.name}:{rule.name}
318318
rules map[string]*appsv1alpha1.TrafficInterceptRule
319319
// normalIndex cache, key is {trafficInterceptStore.Content}:{trafficInterceptStore.Method}, value is {cb.namespace}:{cb.name}:{rule.name}
320-
normalIndexes map[string]sets.String
320+
normalIndexes map[string]sets.Set[string]
321321
// regexpIndex cache, key is {cb.namespace}:{cb.name}:{rule.name}, value is regexpInfo
322322
regexpIndexes map[string][]*regexpInfo
323323
}
324324

325325
func newTrafficInterceptStore() *trafficInterceptStore {
326326
return &trafficInterceptStore{
327327
rules: make(map[string]*appsv1alpha1.TrafficInterceptRule),
328-
normalIndexes: make(map[string]sets.String),
328+
normalIndexes: make(map[string]sets.Set[string]),
329329
regexpIndexes: make(map[string][]*regexpInfo),
330330
}
331331
}
@@ -367,7 +367,7 @@ func (s *trafficInterceptStore) updateIndex(oldOne, newOne *appsv1alpha1.Traffic
367367
urlMethod := indexForRest(content, method)
368368
set := s.normalIndexes[urlMethod]
369369
if set == nil {
370-
set = sets.String{}
370+
set = sets.New[string]()
371371
s.normalIndexes[urlMethod] = set
372372
}
373373
set.Insert(key)

0 commit comments

Comments
 (0)