Skip to content

Commit

Permalink
Update golangci-lint, add more linters
Browse files Browse the repository at this point in the history
Fix minor issues, but plenty of them. Add new linters.
Most changes come from gocritic. Performance was optimised for changing
copy of big structures like GameServerSpec into to using a pointer.
  • Loading branch information
aLekSer committed Jan 11, 2020
1 parent e2132cc commit f1bc763
Show file tree
Hide file tree
Showing 40 changed files with 255 additions and 209 deletions.
27 changes: 26 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,48 @@ output:

linters:
enable:
- deadcode
- megacheck
- govet
- golint
- interfacer
- unconvert
- dupl
- goconst
- gocritic
- gocyclo
- goimports
- interfacer
- maligned
- megacheck
- scopelint
- staticcheck
- structcheck
- misspell
- unparam
- nakedret
- bodyclose

linters-settings:
gocritic:
enabled-tags:
- performance
- opinionated
- diagnostic
disabled-checks:
- ifElseChain
- paramTypeCombine
- unnamedResult
settings: # settings passed to gocritic
hugeParam:
sizeThreshold: 512
rangeValCopy:
sizeThreshold: 512
skipTestFuncs: true

issues:
# This turns off the default excludes - which was causing the linter
# to miss things like erroneous comments
exclude-use-default: false
exclude-use-default: false
exclude:
- Using the variable on range scope .* in function literal
2 changes: 1 addition & 1 deletion build/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ build-controller-binary: $(ensure-build-image)
lint: LINT_TIMEOUT ?= 15m
lint: $(ensure-build-image)
docker run -t -e "TERM=xterm-256color" -e "$(gomod_on)" --rm $(common_mounts) -w $(workdir_path) $(DOCKER_RUN_ARGS) $(build_tag) bash -c \
"golangci-lint run ./examples/... && golangci-lint run --deadline $(LINT_TIMEOUT) ./..."
"golangci-lint run ./examples/... && golangci-lint run --timeout $(LINT_TIMEOUT) ./..."

# Extract licenses from source tree
build-licenses:
Expand Down
2 changes: 1 addition & 1 deletion build/build-image/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ RUN curl -L ${HELM_URL} > /tmp/helm.tar.gz \
RUN echo "source <(helm completion bash)" >> /root/.bashrc

# install golang-ci linter
RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $GOPATH/bin v1.18.0
RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $GOPATH/bin v1.22.2

#
# \ \ / /__| |__ ___(_) |_ ___
Expand Down
26 changes: 14 additions & 12 deletions cmd/allocator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,19 +243,20 @@ func getCACertPool(path string) (*x509.CertPool, error) {
}

for _, file := range filesInfo {
if strings.HasSuffix(file.Name(), ".crt") || strings.HasSuffix(file.Name(), ".pem") {
certFile := filepath.Join(path, file.Name())
caCert, err := ioutil.ReadFile(certFile)
if err != nil {
logger.Errorf("ca cert is not readable or missing: %s", err.Error())
continue
}
if !caCertPool.AppendCertsFromPEM(caCert) {
logger.Errorf("client cert %s cannot be installed", certFile)
continue
}
logger.Infof("client cert %s is installed", certFile)
if !strings.HasSuffix(file.Name(), ".crt") && !strings.HasSuffix(file.Name(), ".pem") {
continue
}
certFile := filepath.Join(path, file.Name())
caCert, err := ioutil.ReadFile(certFile)
if err != nil {
logger.Errorf("ca cert is not readable or missing: %s", err.Error())
continue
}
if !caCertPool.AppendCertsFromPEM(caCert) {
logger.Errorf("client cert %s cannot be installed", certFile)
continue
}
logger.Infof("client cert %s is installed", certFile)
}

return caCertPool, nil
Expand Down Expand Up @@ -323,6 +324,7 @@ func (h *httpHandler) allocateHandler(w http.ResponseWriter, r *http.Request) {

func httpCode(err error) int {
code := http.StatusInternalServerError
// nolint: gocritic
switch t := err.(type) {
case k8serror.APIStatus:
code = int(t.Status().Code)
Expand Down
2 changes: 1 addition & 1 deletion cmd/controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ type config struct {
}

// validate ensures the ctlConfig data is valid.
func (c config) validate() error {
func (c *config) validate() error {
if c.MinPort <= 0 || c.MaxPort <= 0 {
return errors.New("min Port and Max Port values are required")
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/ping/udp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ func TestUDPServerHealth(t *testing.T) {
assert.Nil(t, err)
}

func defaultFixture(clock clock.Clock) (*udpServer, error) {
func defaultFixture(cl clock.Clock) (*udpServer, error) {
u := newUDPServer(5)
u.clock = clock
u.clock = cl
var err error
u.conn, err = net.ListenPacket("udp", ":0")
return u, err
Expand Down
1 change: 1 addition & 0 deletions pkg/allocation/converters/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ func convertInternalLabelSelectorToLabelSelector(in *metav1.LabelSelector) *pb.L
func convertInternalLabelSelectorsToLabelSelectors(in []metav1.LabelSelector) []*pb.LabelSelector {
var result []*pb.LabelSelector
for _, l := range in {
l := l
c := convertInternalLabelSelectorToLabelSelector(&l)
result = append(result, c)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/apis/agones/v1/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func validateGSSpec(gs gsSpec) []metav1.StatusCause {

// validateObjectMeta Check ObjectMeta specification
// Used by Fleet, GameServerSet and GameServer
func validateObjectMeta(objMeta metav1.ObjectMeta) []metav1.StatusCause {
func validateObjectMeta(objMeta *metav1.ObjectMeta) []metav1.StatusCause {
var causes []metav1.StatusCause

errs := metav1validation.ValidateLabels(objMeta.Labels, field.NewPath("labels"))
Expand Down
2 changes: 1 addition & 1 deletion pkg/apis/agones/v1/fleet.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (f *Fleet) Validate() ([]metav1.StatusCause, bool) {
if len(gsCauses) > 0 {
causes = append(causes, gsCauses...)
}
objMetaCauses := validateObjectMeta(f.Spec.Template.ObjectMeta)
objMetaCauses := validateObjectMeta(&f.Spec.Template.ObjectMeta)
if len(objMetaCauses) > 0 {
causes = append(causes, objMetaCauses...)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/agones/v1/gameserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func (gss *GameServerSpec) applySchedulingDefaults() {
// devAddress is a specific IP address used for local Gameservers, for fleets "" is used
// If a GameServer Spec is invalid there will be > 0 values in
// the returned array
func (gss GameServerSpec) Validate(devAddress string) ([]metav1.StatusCause, bool) {
func (gss *GameServerSpec) Validate(devAddress string) ([]metav1.StatusCause, bool) {
var causes []metav1.StatusCause
if devAddress != "" {
// verify that the value is a valid IP address.
Expand Down Expand Up @@ -342,7 +342,7 @@ func (gss GameServerSpec) Validate(devAddress string) ([]metav1.StatusCause, boo
}
} else {
// make sure a name is specified when there is multiple containers in the pod.
if len(gss.Container) == 0 && len(gss.Template.Spec.Containers) > 1 {
if gss.Container == "" && len(gss.Template.Spec.Containers) > 1 {
causes = append(causes, metav1.StatusCause{
Type: metav1.CauseTypeFieldValueInvalid,
Field: "container",
Expand Down Expand Up @@ -389,7 +389,7 @@ func (gss GameServerSpec) Validate(devAddress string) ([]metav1.StatusCause, boo
})
}
}
objMetaCauses := validateObjectMeta(gss.Template.ObjectMeta)
objMetaCauses := validateObjectMeta(&gss.Template.ObjectMeta)
if len(objMetaCauses) > 0 {
causes = append(causes, objMetaCauses...)
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/apis/agones/v1/gameserverset.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ type GameServerSetStatus struct {

// ValidateUpdate validates when updates occur. The argument
// is the new GameServerSet, being passed into the old GameServerSet
func (gsSet *GameServerSet) ValidateUpdate(new *GameServerSet) ([]metav1.StatusCause, bool) {
causes := validateName(new)
if !apiequality.Semantic.DeepEqual(gsSet.Spec.Template, new.Spec.Template) {
func (gsSet *GameServerSet) ValidateUpdate(newGSS *GameServerSet) ([]metav1.StatusCause, bool) {
causes := validateName(newGSS)
if !apiequality.Semantic.DeepEqual(gsSet.Spec.Template, newGSS.Spec.Template) {
causes = append(causes, metav1.StatusCause{
Type: metav1.CauseTypeFieldValueInvalid,
Field: "template",
Expand All @@ -102,7 +102,7 @@ func (gsSet *GameServerSet) Validate() ([]metav1.StatusCause, bool) {
causes = append(causes, gsCauses...)
}

objMetaCauses := validateObjectMeta(gsSet.Spec.Template.ObjectMeta)
objMetaCauses := validateObjectMeta(&gsSet.Spec.Template.ObjectMeta)
if len(objMetaCauses) > 0 {
causes = append(causes, objMetaCauses...)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/agones/v1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ func init() {
}

// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *k8sruntime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
func addKnownTypes(apiScheme *k8sruntime.Scheme) error {
apiScheme.AddKnownTypes(SchemeGroupVersion,
&GameServer{},
&GameServerList{},
&GameServerSet{},
&GameServerSetList{},
&Fleet{},
&FleetList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
metav1.AddToGroupVersion(apiScheme, SchemeGroupVersion)
return nil
}
1 change: 1 addition & 0 deletions pkg/apis/allocation/v1/gameserverallocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ func (gsas *GameServerAllocationSpec) PreferredSelectors() ([]labels.Selector, e

var err error
for i, p := range gsas.Preferred {
p := p
list[i], err = metav1.LabelSelectorAsSelector(&p)
if err != nil {
break
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/allocation/v1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func init() {
}

// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *k8sruntime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
func addKnownTypes(apiScheme *k8sruntime.Scheme) error {
apiScheme.AddKnownTypes(SchemeGroupVersion,
&GameServerAllocation{},
&GameServerAllocationList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
metav1.AddToGroupVersion(apiScheme, SchemeGroupVersion)
return nil
}
6 changes: 3 additions & 3 deletions pkg/apis/autoscaling/v1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func init() {
}

// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *k8sruntime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
func addKnownTypes(apiScheme *k8sruntime.Scheme) error {
apiScheme.AddKnownTypes(SchemeGroupVersion,
&FleetAutoscaler{},
&FleetAutoscalerList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
metav1.AddToGroupVersion(apiScheme, SchemeGroupVersion)
return nil
}
4 changes: 2 additions & 2 deletions pkg/apis/multicluster/v1alpha1/gameserverallocationpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,11 @@ func selectRandomWeighted(connections []*ClusterConnectionInfo, weights []int) *
return nil
}

rand := rand.Intn(sum)
randValue := rand.Intn(sum)
sum = 0
for i, weight := range weights {
sum += weight
if rand < sum {
if randValue < sum {
return connections[i]
}
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/multicluster/v1alpha1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func init() {
}

// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *k8sruntime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
func addKnownTypes(apiScheme *k8sruntime.Scheme) error {
apiScheme.AddKnownTypes(SchemeGroupVersion,
&GameServerAllocationPolicy{},
&GameServerAllocationPolicyList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
metav1.AddToGroupVersion(apiScheme, SchemeGroupVersion)
return nil
}
19 changes: 10 additions & 9 deletions pkg/fleets/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,16 +386,17 @@ func (c *Controller) deleteEmptyGameServerSets(fleet *agonesv1.Fleet, list []*ag
// GameServerSets, and return the replica count for the active GameServerSet
func (c *Controller) recreateDeployment(fleet *agonesv1.Fleet, rest []*agonesv1.GameServerSet) (int32, error) {
for _, gsSet := range rest {
if gsSet.Spec.Replicas != 0 {
c.loggerForFleet(fleet).WithField("gameserverset", gsSet.ObjectMeta.Name).Info("applying recreate deployment: scaling to 0")
gsSetCopy := gsSet.DeepCopy()
gsSetCopy.Spec.Replicas = 0
if _, err := c.gameServerSetGetter.GameServerSets(gsSetCopy.ObjectMeta.Namespace).Update(gsSetCopy); err != nil {
return 0, errors.Wrapf(err, "error updating gameserverset %s", gsSetCopy.ObjectMeta.Name)
}
c.recorder.Eventf(fleet, corev1.EventTypeNormal, "ScalingGameServerSet",
"Scaling inactive GameServerSet %s from %d to %d", gsSetCopy.ObjectMeta.Name, gsSet.Spec.Replicas, gsSetCopy.Spec.Replicas)
if gsSet.Spec.Replicas == 0 {
continue
}
c.loggerForFleet(fleet).WithField("gameserverset", gsSet.ObjectMeta.Name).Info("applying recreate deployment: scaling to 0")
gsSetCopy := gsSet.DeepCopy()
gsSetCopy.Spec.Replicas = 0
if _, err := c.gameServerSetGetter.GameServerSets(gsSetCopy.ObjectMeta.Namespace).Update(gsSetCopy); err != nil {
return 0, errors.Wrapf(err, "error updating gameserverset %s", gsSetCopy.ObjectMeta.Name)
}
c.recorder.Eventf(fleet, corev1.EventTypeNormal, "ScalingGameServerSet",
"Scaling inactive GameServerSet %s from %d to %d", gsSetCopy.ObjectMeta.Name, gsSet.Spec.Replicas, gsSetCopy.Spec.Replicas)
}

return fleet.LowerBoundReplicas(fleet.Spec.Replicas - agonesv1.SumStatusAllocatedReplicas(rest)), nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/fleets/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ func TestControllerRun(t *testing.T) {

// test updating fleet
fCopy := fleet.DeepCopy()
fCopy.Spec.Replicas = fCopy.Spec.Replicas + 10
fCopy.Spec.Replicas += 10
fleetWatch.Modify(fCopy)
assert.Equal(t, expected, f())

Expand Down
2 changes: 1 addition & 1 deletion pkg/gameserverallocations/allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ func (c *Allocator) allocationUpdateWorkers(workerCount int, stop <-chan struct{
for {
select {
case res := <-updateQueue:
gs, err := c.readyGameServerCache.PatchGameServerMetadata(res.request.gsa.Spec.MetaPatch, *res.gs)
gs, err := c.readyGameServerCache.PatchGameServerMetadata(res.request.gsa.Spec.MetaPatch, res.gs)
if err != nil {
// since we could not allocate, we should put it back
c.readyGameServerCache.AddToReadyGameServer(gs)
Expand Down
7 changes: 2 additions & 5 deletions pkg/gameserverallocations/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,8 @@ func TestGameServerCacheEntry(t *testing.T) {

count := 0
cache.Range(func(key string, gs *agonesv1.GameServer) bool {
if count++; count == 2 {
return false
}

return true
count++
return count != 2
})

assert.Equal(t, 2, count, "Should only process one item")
Expand Down
Loading

0 comments on commit f1bc763

Please sign in to comment.