Skip to content

Commit

Permalink
Merge pull request #31 from grid-x/fix_service_account_watch
Browse files Browse the repository at this point in the history
Fix service account watch
  • Loading branch information
sercand authored Dec 1, 2022
2 parents ec4d851 + 2ed01cf commit 2d2ae8e
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/fsnotify/fsnotify"
Expand All @@ -33,6 +34,7 @@ type K8sClient interface {
type k8sClient struct {
host string
token string
tokenLck sync.RWMutex
httpClient *http.Client
}

Expand All @@ -44,6 +46,8 @@ func (kc *k8sClient) GetRequest(url string) (*http.Request, error) {
if err != nil {
return nil, err
}
kc.tokenLck.RLock()
defer kc.tokenLck.RUnlock()
if len(kc.token) > 0 {
req.Header.Set("Authorization", "Bearer "+kc.token)
}
Expand All @@ -58,6 +62,12 @@ func (kc *k8sClient) Host() string {
return kc.host
}

func (kc *k8sClient) setToken(token string) {
kc.tokenLck.Lock()
defer kc.tokenLck.Unlock()
kc.token = token
}

// NewInClusterK8sClient creates K8sClient if it is inside Kubernetes
func NewInClusterK8sClient() (K8sClient, error) {
host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
Expand Down Expand Up @@ -99,10 +109,22 @@ func NewInClusterK8sClient() (K8sClient, error) {
if !ok {
return
}
// k8s configmaps uses symlinks, we need this workaround.
// original configmap file is removed
if event.Op == fsnotify.Remove || event.Op == fsnotify.Chmod {
// remove watcher since the file is removed
watcher.Remove(event.Name)
// add a new watcher pointing to the new symlink/file
watcher.Add(serviceAccountToken)
token, err := ioutil.ReadFile(serviceAccountToken)
if err == nil {
client.setToken(string(token))
}
}
if event.Op&fsnotify.Write == fsnotify.Write {
token, err := ioutil.ReadFile(serviceAccountToken)
if err == nil {
client.token = string(token)
client.setToken(string(token))
}
}
case _, ok := <-watcher.Errors:
Expand Down

0 comments on commit 2d2ae8e

Please sign in to comment.