Skip to content

Commit

Permalink
fix: prevent panic and improve logging (#7)
Browse files Browse the repository at this point in the history
* added multiple open panics and wrapped them in normal logging

Signed-off-by: Aditya Sundaramurthy <[email protected]>

---------

Signed-off-by: Aditya Sundaramurthy <[email protected]>
Co-authored-by: Aditya Sundaramurthy <[email protected]>
  • Loading branch information
logicfox and Aditya Sundaramurthy authored May 22, 2024
1 parent b5b64d2 commit d3af063
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 16 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ COPY argocd-ado-awi-cred-sidecar manager
# Kubernetes runAsNonRoot requires USER to be numeric
USER 65532:65532

ENTRYPOINT ["/manager"]
ENTRYPOINT ["/manager"]
22 changes: 22 additions & 0 deletions Dockerfile.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
########## Builder ##########
FROM golang:1.22-alpine AS builder

# Copy local source
COPY . /build
WORKDIR /build

# Build the binary
RUN go build -o manager ./cmd/main.go

######## Binary ###########

FROM mcr.microsoft.com/cbl-mariner/distroless/minimal:2.0-nonroot

WORKDIR /

# Kubernetes runAsNonRoot requires USER to be numeric
USER 65532:65532

COPY --from=builder /build/manager /manager

ENTRYPOINT [ "/manager" ]
11 changes: 9 additions & 2 deletions pkg/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ func (a *AzureHelper) getAzureContainerRegistryAccessToken(acrServiceName string
ctx := context.Background()
aadToken, err := a.credential.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{AzureContainerRegistryScope}})
if err != nil {
panic(err)
a.log.Error(err, "Cannot fetch token for ACR scope", "name", acrServiceName)
return nil, err
}
aadTokenJWT, _, err := new(jwt.Parser).ParseUnverified(string(aadToken.Token), jwt.MapClaims{})
if err != nil {
Expand All @@ -79,7 +80,13 @@ func (a *AzureHelper) getAzureContainerRegistryAccessToken(acrServiceName string
}
jsonResponse, err := http.PostForm(fmt.Sprintf("https://%s/oauth2/exchange", acrServiceName), formData)
if err != nil {
panic(err)
a.log.Error(err, "Failed to fetch token from ACR with managed identity", "name", acrServiceName, "payload", formData.Encode())
return nil, err
}
if jsonResponse.StatusCode != 200 {
err = fmt.Errorf("unable to fetch token from ACR. name: %s, payload: %s, status, %s", acrServiceName, formData.Encode(), jsonResponse.Status)
a.log.Error(err, "ACR error")
return nil, err
}
var response map[string]interface{}
json.NewDecoder(jsonResponse.Body).Decode(&response)
Expand Down
4 changes: 2 additions & 2 deletions pkg/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package pkg

const (
// LabelSelector is the label selector for the secret
LabelSelector = "argocd.argoproj.io/secret-type=repo-creds"
LabelSelector = "argocd.argoproj.io/secret-type in (repo-creds, repository)"
// Scope for the Azure DevOps access token
AzureDevOpsScope = "499b84ac-1321-427f-aa17-267ca6975798/.default"
// Scope for Azure COntainer Registry access token
AzureContainerRegistryScope = "https://management.azure.com/.default"
// Default username for the access token
DefaultUsername = "00000000-0000-0000-0000-000000000000"
)
)
8 changes: 4 additions & 4 deletions pkg/coordinator.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,16 @@ func (c *Coordinator) EvaluateAccessTokenExpiration() error {
c.log.Error(err, "Failed to get access token")
return err
}
c.log.Info("Access token retrieved", "token", accessToken.Raw)
c.log.Info("Access token retrieved. Update expiration time", "expirationTime", time.Unix(int64(accessToken.Claims.(jwt.MapClaims)["exp"].(float64)), 0))
err = c.kubernetesHelper.UpdateSecret(accessToken.Raw, &secret)
if err != nil {
c.log.Error(err, "Failed to update secret")
return err
}
c.log.Info("Access token retrieved. Update expiration time", "expirationTime", time.Unix(int64(accessToken.Claims.(jwt.MapClaims)["exp"].(float64)), 0))
return nil
c.log.Info("Secret updated", "name", secret.Name, "namespace", secret.Namespace)
continue
}
c.log.Info("Access token is still valid", "remainingTime", remainingTime)
c.log.Info("Access token is still valid", "remainingTime", remainingTime, "name", secret.Name, "namespace", secret.Namespace)
}
return nil
}
Expand Down
16 changes: 9 additions & 7 deletions pkg/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pkg

import (
"context"
"os"
"strings"

"github.com/go-logr/logr"
Expand All @@ -13,16 +14,16 @@ import (
)

type KubernetesHelper struct {
logger logr.Logger
clientSet *kubernetes.Clientset
logger logr.Logger
clientSet *kubernetes.Clientset
defaultNamespace string
}

func NewKubernetesHelper(log logr.Logger, defaultNamespace string) (*KubernetesHelper, error) {
config, err := rest.InClusterConfig()
if err != nil {
log.Info("Failed to get in cluster config, trying kubeconfig")
config, err = clientcmd.BuildConfigFromFlags("", "kubeconfig")
config, err = clientcmd.BuildConfigFromFlags("", os.Getenv("KUBECONFIG"))
if err != nil {
log.Error(err, "Failed to get kubeconfig")
return nil, err
Expand All @@ -35,8 +36,8 @@ func NewKubernetesHelper(log logr.Logger, defaultNamespace string) (*KubernetesH
return nil, err
}
return &KubernetesHelper{
logger: log,
clientSet: clientSet,
logger: log,
clientSet: clientSet,
defaultNamespace: defaultNamespace,
}, nil
}
Expand All @@ -53,7 +54,6 @@ func (k *KubernetesHelper) SearchSecret(urls []string) (*[]corev1.Secret, error)
matchingSecrets := make([]corev1.Secret, 0)
for _, secret := range secretList.Items {
k.logger.Info("Checking secret", "secret", secret.Name)

secretUrl := string(secret.Data["url"])
for _, url := range urls {
if strings.Contains(secretUrl, url) {
Expand All @@ -69,11 +69,13 @@ func (k *KubernetesHelper) UpdateSecret(accessToken string, secret *corev1.Secre
updatedSecret := secret.DeepCopy()
updatedSecret.Data["password"] = []byte(accessToken)
updatedSecret.Data["username"] = []byte(DefaultUsername)
k.logger.Info("Updating secret", "namespace", updatedSecret.Namespace, "name", updatedSecret.Name)
_, err := k.clientSet.CoreV1().Secrets(updatedSecret.Namespace).Update(context.Background(), updatedSecret, v1.UpdateOptions{})
if err != nil {
k.logger.Error(err, "Failed to update secret", "namespace", updatedSecret.Namespace, "name", updatedSecret.Name)
return err
}
k.logger.Info("Updated secret", "namespace", updatedSecret.Namespace, "name", updatedSecret.Name)
return nil
}

Expand All @@ -90,4 +92,4 @@ func (k *KubernetesHelper) GetInClusterConfiguration(cmName string) ([]string, e
}
urls := strings.Split(matchUrls, ",")
return urls, nil
}
}

0 comments on commit d3af063

Please sign in to comment.