Skip to content

Commit

Permalink
[fix]: enhance kubelet package impl
Browse files Browse the repository at this point in the history
Signed-off-by: Sam Yuan <[email protected]>
  • Loading branch information
SamYuan1990 committed Dec 12, 2024
1 parent 89759b7 commit bfffe76
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 11 deletions.
42 changes: 31 additions & 11 deletions pkg/kubelet/kubelet_pod_lister.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package kubelet

import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
Expand All @@ -37,8 +36,9 @@ const (
)

var (
podURL string
client http.Client
podURL string
client http.Client
bearerToken string
)

func init() {
Expand All @@ -55,29 +55,49 @@ func init() {
client = http.Client{}
}

func httpGet(url string) (*http.Response, error) {
objToken, err := os.ReadFile(saPath)
func loadToken(path string) (string, error) {
objToken, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read from %q: %v", saPath, err)
return "", fmt.Errorf("failed to read from %q: %v", path, err)
}
token := string(objToken)
return "Bearer " + string(objToken), nil
}

var bearer = "Bearer " + token
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, http.NoBody)
func doFetchPod(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)

Check failure on line 67 in pkg/kubelet/kubelet_pod_lister.go

View workflow job for this annotation

GitHub Actions / golang / lint

should rewrite http.NewRequestWithContext or add (*Request).WithContext (noctx)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", bearer)
req.Header.Add("Authorization", bearerToken)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to get response from %q: %v", url, err)
}
return resp, err
}

func httpGet(path, url string) (*http.Response, error) {
var err error
if bearerToken == "" || len(bearerToken) == 0 {

Check failure on line 81 in pkg/kubelet/kubelet_pod_lister.go

View workflow job for this annotation

GitHub Actions / golang / lint

emptyStringTest: replace `len(bearerToken) == 0` with `bearerToken == ""` (gocritic)
bearerToken, err = loadToken(path)
if err != nil {
return nil, fmt.Errorf("failed to read from %q: %v", path, err)
}
}
resp, err := doFetchPod(url)
if resp != nil && resp.StatusCode > 399 && resp.StatusCode < 500 { // if response in 4xx retry once
bearerToken, err = loadToken(path)
if err != nil {
return nil, fmt.Errorf("failed to read from %q: %v", path, err)
}
resp, err = doFetchPod(url)
}
return resp, err
}

// ListPods obtains PodList
func (k *KubeletPodLister) ListPods() (*[]corev1.Pod, error) {
resp, err := httpGet(podURL)
resp, err := httpGet(saPath, podURL)
if err != nil {
return nil, fmt.Errorf("failed to get response: %v", err)
}
Expand Down
89 changes: 89 additions & 0 deletions pkg/kubelet/kubelet_pod_lister_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Copyright 2024.
Licensed 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 kubelet

import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"sync"
"testing"

. "github.com/onsi/gomega"
)

func TestDoFetchPod(t *testing.T) {
g := NewWithT(t)
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "dummy")
}))
defer svr.Close()
res, err := doFetchPod(svr.URL)

Check failure on line 36 in pkg/kubelet/kubelet_pod_lister_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

response body must be closed (bodyclose)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(res.StatusCode).To(Equal(http.StatusOK))
bearerToken = "dummy"
res, err = httpGet("", svr.URL)

Check failure on line 40 in pkg/kubelet/kubelet_pod_lister_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

response body must be closed (bodyclose)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(res.StatusCode).To(Equal(http.StatusOK))
}

func TestDoFetchPodWithError(t *testing.T) {
g := NewWithT(t)
svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "dummy")
}))
res, err := doFetchPod(svr.URL)

Check failure on line 50 in pkg/kubelet/kubelet_pod_lister_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

response body must be closed (bodyclose)
g.Expect(err).To(HaveOccurred())
g.Expect(res).To(BeNil())
bearerToken = "dummy"
res, err = httpGet("", svr.URL)
g.Expect(err).To(HaveOccurred())
g.Expect(res).To(BeNil())
}

func TestLoadToken(t *testing.T) {
g := NewWithT(t)
bearerToken = ""
tmpDir, err := os.MkdirTemp("", "kepler-tmp-")
g.Expect(err).NotTo(HaveOccurred())
defer os.RemoveAll(tmpDir)

TokenFile, err := os.CreateTemp(tmpDir, "kubeletToken")
g.Expect(err).NotTo(HaveOccurred())
_, err = TokenFile.Write([]byte("token"))

Check failure on line 68 in pkg/kubelet/kubelet_pod_lister_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

preferStringWriter: TokenFile.WriteString("token") should be preferred to the TokenFile.Write([]byte("token")) (gocritic)
g.Expect(err).NotTo(HaveOccurred())
TokenFile.Close()

bearerToken, err := loadToken(TokenFile.Name())
g.Expect(err).NotTo(HaveOccurred())
g.Expect(bearerToken).To(Equal("Bearer token"))

bearerToken = ""

Check failure on line 76 in pkg/kubelet/kubelet_pod_lister_test.go

View workflow job for this annotation

GitHub Actions / golang / lint

ineffectual assignment to bearerToken (ineffassign)
var once sync.Once
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
once.Do(func() {
w.WriteHeader(http.StatusUnauthorized)
})
fmt.Fprintf(w, "dummy")
}))
defer svr.Close()

res, err := httpGet(TokenFile.Name(), svr.URL)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(res.StatusCode).To(Equal(http.StatusOK))
}

0 comments on commit bfffe76

Please sign in to comment.