Skip to content

Commit

Permalink
chore: replace deprecated ioutil methods (flant#444)
Browse files Browse the repository at this point in the history
Signed-off-by: Ivan Mikheykin <[email protected]>
  • Loading branch information
diafour authored Dec 12, 2022
1 parent 2c84c7a commit f9f8333
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 60 deletions.
11 changes: 8 additions & 3 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
run:
timeout: 15m
linters:
include:
- bodyclose
- asciicheck
- dogsled
- durationcheck
issues:
exclude:
- ST1005.*
- SA1019.* # "io/ioutil" has been deprecated since Go 1.16
max-issues-per-linter: 0
max-same-issues: 0
35 changes: 17 additions & 18 deletions pkg/hook/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package hook
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -83,7 +82,7 @@ func (h *Hook) WithHookController(hookController controller.HookController) {
h.HookController = hookController
}

func (h *Hook) Run(bindingType BindingType, context []BindingContext, logLabels map[string]string) (*HookResult, error) {
func (h *Hook) Run(_ BindingType, context []BindingContext, logLabels map[string]string) (*HookResult, error) {
// Refresh snapshots
freshBindingContext := h.HookController.UpdateSnapshots(context)

Expand Down Expand Up @@ -117,15 +116,15 @@ func (h *Hook) Run(bindingType BindingType, context []BindingContext, logLabels
// remove tmp file on hook exit
defer func() {
if app.DebugKeepTmpFiles != "yes" {
os.Remove(contextPath)
os.Remove(metricsPath)
os.Remove(conversionPath)
os.Remove(validatingPath)
os.Remove(kubernetesPatchPath)
_ = os.Remove(contextPath)
_ = os.Remove(metricsPath)
_ = os.Remove(conversionPath)
_ = os.Remove(validatingPath)
_ = os.Remove(kubernetesPatchPath)
}
}()

envs := []string{}
envs := make([]string, 0)
envs = append(envs, os.Environ()...)
if contextPath != "" {
envs = append(envs, fmt.Sprintf("BINDING_CONTEXT_PATH=%s", contextPath))
Expand Down Expand Up @@ -159,7 +158,7 @@ func (h *Hook) Run(bindingType BindingType, context []BindingContext, logLabels
return result, fmt.Errorf("got bad conversion response: %s", err)
}

result.KubernetesPatchBytes, err = ioutil.ReadFile(kubernetesPatchPath)
result.KubernetesPatchBytes, err = os.ReadFile(kubernetesPatchPath)
if err != nil {
return result, fmt.Errorf("can't read object patch file: %s", err)
}
Expand All @@ -172,7 +171,7 @@ func (h *Hook) SafeName() string {
}

func (h *Hook) GetConfigDescription() string {
msgs := []string{}
msgs := make([]string, 0)
if h.Config.OnStartup != nil {
msgs = append(msgs, fmt.Sprintf("OnStartup:%d", int64(h.Config.OnStartup.Order)))
}
Expand Down Expand Up @@ -246,7 +245,7 @@ func (h *Hook) prepareBindingContextJsonFile(context BindingContextList) (string

bindingContextPath := filepath.Join(h.TmpDir, fmt.Sprintf("hook-%s-binding-context-%s.json", h.SafeName(), uuid.NewV4().String()))

err = ioutil.WriteFile(bindingContextPath, data, 0644)
err = os.WriteFile(bindingContextPath, data, 0644)
if err != nil {
return "", err
}
Expand All @@ -257,7 +256,7 @@ func (h *Hook) prepareBindingContextJsonFile(context BindingContextList) (string
func (h *Hook) prepareMetricsFile() (string, error) {
metricsPath := filepath.Join(h.TmpDir, fmt.Sprintf("hook-%s-metrics-%s.json", h.SafeName(), uuid.NewV4().String()))

err := ioutil.WriteFile(metricsPath, []byte{}, 0644)
err := os.WriteFile(metricsPath, []byte{}, 0644)
if err != nil {
return "", err
}
Expand All @@ -268,7 +267,7 @@ func (h *Hook) prepareMetricsFile() (string, error) {
func (h *Hook) prepareValidatingResponseFile() (string, error) {
validatingPath := filepath.Join(h.TmpDir, fmt.Sprintf("hook-%s-validating-response-%s.json", h.SafeName(), uuid.NewV4().String()))

err := ioutil.WriteFile(validatingPath, []byte{}, 0644)
err := os.WriteFile(validatingPath, []byte{}, 0644)
if err != nil {
return "", err
}
Expand All @@ -279,7 +278,7 @@ func (h *Hook) prepareValidatingResponseFile() (string, error) {
func (h *Hook) prepareConversionResponseFile() (string, error) {
conversionPath := filepath.Join(h.TmpDir, fmt.Sprintf("hook-%s-conversion-response-%s.json", h.SafeName(), uuid.NewV4().String()))

err := ioutil.WriteFile(conversionPath, []byte{}, 0644)
err := os.WriteFile(conversionPath, []byte{}, 0644)
if err != nil {
return "", err
}
Expand All @@ -288,9 +287,9 @@ func (h *Hook) prepareConversionResponseFile() (string, error) {
}

func CreateRateLimiter(cfg *config.HookConfig) *rate.Limiter {
// Create rate limiter
limit := rate.Inf // no rate limit by default
burst := 1 // no more then 1 event at time
// Create rate limiter.
limit := rate.Inf // No rate limit by default.
burst := 1 // No more than 1 event at time.
if cfg.Settings != nil {
if cfg.Settings.ExecutionMinInterval != 0 {
limit = rate.Every(cfg.Settings.ExecutionMinInterval)
Expand All @@ -305,7 +304,7 @@ func CreateRateLimiter(cfg *config.HookConfig) *rate.Limiter {
func (h *Hook) prepareObjectPatchFile() (string, error) {
objectPatchPath := filepath.Join(h.TmpDir, fmt.Sprintf("%s-object-patch-%s", h.SafeName(), uuid.NewV4().String()))

err := ioutil.WriteFile(objectPatchPath, []byte{}, 0644)
err := os.WriteFile(objectPatchPath, []byte{}, 0644)
if err != nil {
return "", err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/kube/object_patch/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package object_patch
import (
"context"
"fmt"
"io/ioutil"
"os"
"testing"

"github.com/flant/kube-client/fake"
Expand All @@ -18,7 +18,7 @@ import (

func mustReadFile(t *testing.T, filePath string) []byte {
t.Helper()
content, err := ioutil.ReadFile(filePath)
content, err := os.ReadFile(filePath)
require.NoError(t, err)
return content
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/metric_storage/operation/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strings"

"github.com/hashicorp/go-multierror"
Expand Down Expand Up @@ -89,7 +89,7 @@ func MetricOperationsFromBytes(data []byte) ([]MetricOperation, error) {
}

func MetricOperationsFromFile(filePath string) ([]MetricOperation, error) {
data, err := ioutil.ReadFile(filePath)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("cannot read %s: %s", filePath, err)
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/utils/checksum/checksum.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package checksum
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
"os"
"path/filepath"
"sort"
Expand All @@ -19,7 +18,7 @@ func CalculateChecksum(stringArr ...string) string {
}

func CalculateChecksumOfFile(path string) (string, error) {
content, err := ioutil.ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
return "", err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/webhook/conversion/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package conversion
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"

Expand Down Expand Up @@ -41,7 +41,7 @@ func NewWebhookHandler() *WebhookHandler {
func (h *WebhookHandler) ServeReviewRequest(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()

bodyBytes, err := ioutil.ReadAll(r.Body)
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Error reading request body"))
Expand Down
19 changes: 10 additions & 9 deletions pkg/webhook/conversion/manager.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package conversion

import (
"io/ioutil"
"os"

log "github.com/sirupsen/logrus"

Expand All @@ -14,14 +14,15 @@ type EventHandlerFn func(event Event) (*Response, error)
// WebhookManager is a public interface to be used from operator.go.
//
// No dynamic configuration for now. The steps are:
// - Init():
// - Create a router to distinguish conversion requests between CRDs
// - Create a handler to handle ConversionReview
// - Create a server that listens for Kubernetes requests
// - Init():
// - Create a router to distinguish conversion requests between CRDs
// - Create a handler to handle ConversionReview
// - Create a server that listens for Kubernetes requests
// - Call AddWebhook() to register a CRD name in conversion bindings in hooks
// - Start():
// - Start server loop.
// - Update clientConfig in each registered CRD.
//
// - Start():
// - Start server loop.
// - Update clientConfig in each registered CRD.
type WebhookManager struct {
KubeClient klient.Client

Expand All @@ -45,7 +46,7 @@ func (m *WebhookManager) Init() error {
log.Info("Initialize conversion webhooks manager. Load certificates.")

// settings
caBundleBytes, err := ioutil.ReadFile(m.Settings.CAPath)
caBundleBytes, err := os.ReadFile(m.Settings.CAPath)
if err != nil {
return err
}
Expand Down
27 changes: 16 additions & 11 deletions pkg/webhook/conversion/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,30 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

/*
Response is a holder of the conversion hook response.
Unlike ConverionsResponse, only one filed (FailedMessage) is used to determine success or fail:
Response is Success if FailedMessage is empty:
"result": {
"status": "Success"
},
FailedMessage:
Response is Success if empty string:
"result": {
"status": "Success"
},
Response is Failed:
"result": {
"status": "Failed",
"message": FailedMessage
}
"result": {
"status": "Failed",
"message": FailedMessage
}
ConvertedObjects:
# Objects must match the order of request.objects, and have apiVersion set to <request.desiredAPIVersion>.
Expand All @@ -37,7 +42,7 @@ type Response struct {
}

func ResponseFromFile(filePath string) (*Response, error) {
data, err := ioutil.ReadFile(filePath)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("cannot read %s: %s", filePath, err)
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/webhook/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -48,7 +47,7 @@ func (s *WebhookServer) Start() error {
roots := x509.NewCertPool()

for _, caPath := range s.Settings.ClientCAPaths {
caBytes, err := ioutil.ReadFile(caPath)
caBytes, err := os.ReadFile(caPath)
if err != nil {
return fmt.Errorf("load client CA '%s': %v", caPath, err)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/webhook/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package server

import (
"crypto/x509"
"io/ioutil"
"os"
"testing"

"github.com/go-chi/chi/v5"
Expand Down Expand Up @@ -36,7 +36,7 @@ func Test_Client_CA(t *testing.T) {
}

for _, caPath := range s.ClientCAPaths {
caBytes, err := ioutil.ReadFile(caPath)
caBytes, err := os.ReadFile(caPath)
if err != nil {
t.Fatalf("ca '%s' should be read: %v", caPath, err)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/webhook/validating/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package validating
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"

Expand Down Expand Up @@ -39,7 +39,7 @@ func NewWebhookHandler() *WebhookHandler {
func (h *WebhookHandler) ServeReviewRequest(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()

bodyBytes, err := ioutil.ReadAll(r.Body)
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Error reading request body"))
Expand Down Expand Up @@ -130,7 +130,7 @@ func (h *WebhookHandler) HandleReviewRequest(path string, body []byte) (*v1.Admi
// DetectConfigurationAndWebhook extracts configurationID and a webhookID from the url path.
func DetectConfigurationAndWebhook(path string) (configurationID string, webhookID string) {
parts := strings.Split(path, "/")
webhookParts := []string{}
webhookParts := make([]string, 0)
for _, p := range parts {
if p == "" {
continue
Expand Down
4 changes: 2 additions & 2 deletions pkg/webhook/validating/manager.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package validating

import (
"io/ioutil"
"os"

log "github.com/sirupsen/logrus"

Expand Down Expand Up @@ -60,7 +60,7 @@ func (m *WebhookManager) Init() error {
m.DefaultConfigurationId = DefaultConfigurationId
}
// settings
caBundleBytes, err := ioutil.ReadFile(m.Settings.CAPath)
caBundleBytes, err := os.ReadFile(m.Settings.CAPath)
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/webhook/validating/types/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
)
Expand All @@ -17,7 +17,7 @@ type ValidatingResponse struct {
}

func ValidatingResponseFromFile(filePath string) (*ValidatingResponse, error) {
data, err := ioutil.ReadFile(filePath)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("cannot read %s: %s", filePath, err)
}
Expand Down

0 comments on commit f9f8333

Please sign in to comment.