Skip to content

Commit

Permalink
Debug Message Cleanup (#511)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeff-mccoy authored Jul 18, 2022
1 parent a680d39 commit 2378154
Show file tree
Hide file tree
Showing 22 changed files with 68 additions and 57 deletions.
6 changes: 3 additions & 3 deletions src/cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ var destroyCmd = &cobra.Command{
// Check if we have the scripts to destory everything
fileInfo, err := os.Stat(config.ZarfCleanupScriptsPath)
if errors.Is(err, os.ErrNotExist) || !fileInfo.IsDir() {
message.Warnf("Unable to find the folder (%v) which has the scripts to cleanup the cluster. Do you have the right kube-context?\n", config.ZarfCleanupScriptsPath)
message.Warnf("Unable to find the folder (%#v) which has the scripts to cleanup the cluster. Do you have the right kube-context?\n", config.ZarfCleanupScriptsPath)
return
}

Expand All @@ -56,12 +56,12 @@ var destroyCmd = &cobra.Command{
// Run the matched script
_, _, err := utils.ExecCommandWithContext(context.TODO(), true, script)
if errors.Is(err, os.ErrPermission) {
message.Warnf("Got a 'permission denied' when trying to execute the script (%v). Are you the right user and/or do you have the right kube-context?\n", script)
message.Warnf("Got a 'permission denied' when trying to execute the script (%s). Are you the right user and/or do you have the right kube-context?\n", script)

// Don't remove scripts we can't execute so the user can try to manually run
continue
} else if err != nil {
message.Debugf("Received error when trying to execute the script (%v): %v", script, err)
message.Debugf("Received error when trying to execute the script (%s): %#v", script, err)
}

// Try to remove the script, but ignore any errors
Expand Down
4 changes: 2 additions & 2 deletions src/config/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var selectors = map[SecretSelector]SecretMap{
}

func GetSecret(selector SecretSelector) string {
message.Debugf("config.GetSecret(%v)", selector)
message.Debugf("config.GetSecret(%s)", selector)
if match, ok := selectors[selector]; ok {
return match.computed
}
Expand All @@ -57,7 +57,7 @@ func initSecrets() {
}

func loadSecret(filter SecretSelector, length int) (string, error) {
message.Debugf("config.loadSecret(%v, %v)", filter, length)
message.Debugf("config.loadSecret(%s, %d)", filter, length)
if state.Secret == "" {
return "", fmt.Errorf("invalid root secret in the ZarfState")
}
Expand Down
2 changes: 1 addition & 1 deletion src/internal/agent/hooks/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func parsePod(object []byte) (*corev1.Pod, error) {
}

func mutatePod(r *v1.AdmissionRequest) (*operations.Result, error) {
message.Debugf("hooks.mutateCreate()(*v1.AdmissionRequest) - %v , %s/%s: %v", r.Kind, r.Namespace, r.Name, r.Operation)
message.Debugf("hooks.mutateCreate()(*v1.AdmissionRequest) - %#v , %s/%s: %#v", r.Kind, r.Namespace, r.Name, r.Operation)

var patchOperations []operations.PatchOperation
pod, err := parsePod(r.Object.Raw)
Expand Down
12 changes: 6 additions & 6 deletions src/internal/agent/http/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ func newAdmissionHandler() *admissionHandler {

// Serve returns a http.HandlerFunc for an admission webhook
func (h *admissionHandler) Serve(hook operations.Hook) http.HandlerFunc {
message.Debugf("http.Serve(%v)", hook)
message.Debugf("http.Serve(%#v)", hook)
return func(w http.ResponseWriter, r *http.Request) {
message.Debugf("http.Serve()(writer, %v)", r.URL)
message.Debugf("http.Serve()(writer, %#v)", r.URL)

w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
Expand All @@ -45,13 +45,13 @@ func (h *admissionHandler) Serve(hook operations.Hook) http.HandlerFunc {

body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprintf("could not read request body: %v", err), http.StatusBadRequest)
http.Error(w, fmt.Sprintf("could not read request body: %#v", err), http.StatusBadRequest)
return
}

var review v1.AdmissionReview
if _, _, err := h.decoder.Decode(body, nil, &review); err != nil {
http.Error(w, fmt.Sprintf("could not deserialize request: %v", err), http.StatusBadRequest)
http.Error(w, fmt.Sprintf("could not deserialize request: %#v", err), http.StatusBadRequest)
return
}

Expand Down Expand Up @@ -85,7 +85,7 @@ func (h *admissionHandler) Serve(hook operations.Hook) http.HandlerFunc {
patchBytes, err := json.Marshal(result.PatchOps)
if err != nil {
message.Error(err, "unable to marshall the json patch")
http.Error(w, fmt.Sprintf("could not marshal JSON patch: %v", err), http.StatusInternalServerError)
http.Error(w, fmt.Sprintf("could not marshal JSON patch: %#v", err), http.StatusInternalServerError)
}
admissionResponse.Response.Patch = patchBytes
admissionResponse.Response.PatchType = &jsonPatchType
Expand All @@ -94,7 +94,7 @@ func (h *admissionHandler) Serve(hook operations.Hook) http.HandlerFunc {
jsonResponse, err := json.Marshal(admissionResponse)
if err != nil {
message.Error(err, "unable to marshal the admission response")
http.Error(w, fmt.Sprintf("could not marshal response: %v", err), http.StatusInternalServerError)
http.Error(w, fmt.Sprintf("could not marshal response: %#v", err), http.StatusInternalServerError)
return
}

Expand Down
2 changes: 1 addition & 1 deletion src/internal/agent/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

// NewServer creates and return a http.Server
func NewServer(port string) *http.Server {
message.Debugf("http.NewServer(%v)", port)
message.Debugf("http.NewServer(%s)", port)

// Instances hooks
podsMutation := hooks.NewPodMutationHook()
Expand Down
2 changes: 1 addition & 1 deletion src/internal/agent/operations/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type Hook struct {

// Execute evaluates the request and try to execute the function for operation specified in the request.
func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {
message.Debugf("operations.Execute(*admission.AdmissionRequest) - %v , %s/%s: %v", r.Kind, r.Namespace, r.Name, r.Operation)
message.Debugf("operations.Execute(*admission.AdmissionRequest) - %#v , %s/%s: %#v", r.Kind, r.Namespace, r.Name, r.Operation)

switch r.Operation {
case admission.Create:
Expand Down
2 changes: 1 addition & 1 deletion src/internal/git/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func PushAllDirectories(localPath string) error {
repoName := strings.Split(repoNameWithGitTag, ".git")[0]
err = addReadOnlyUserToRepo(tunnelUrl, repoName)
if err != nil {
message.Warnf("Unable to add the read-only user to the repo: %v\n", repoName)
message.Warnf("Unable to add the read-only user to the repo: %s\n", repoName)
return err
}
}
Expand Down
16 changes: 9 additions & 7 deletions src/internal/git/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
netHttp "net/http"
Expand Down Expand Up @@ -265,7 +264,8 @@ func CreateReadOnlyUser() error {
// Send API request to create the user
createUserEndpoint := fmt.Sprintf("http://%s/api/v1/admin/users", tunnelUrl)
createUserRequest, _ := netHttp.NewRequest("POST", createUserEndpoint, bytes.NewBuffer(createUserData))
_, err = DoHttpThings(createUserRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
out, err := DoHttpThings(createUserRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
message.Debugf("POST %s:\n%s", createUserEndpoint, string(out))
if err != nil {
return err
}
Expand All @@ -279,7 +279,8 @@ func CreateReadOnlyUser() error {
updateUserData, _ := json.Marshal(updateUserBody)
updateUserEndpoint := fmt.Sprintf("http://%s/api/v1/admin/users/%s", tunnelUrl, config.ZarfGitReadUser)
updateUserRequest, _ := netHttp.NewRequest("PATCH", updateUserEndpoint, bytes.NewBuffer(updateUserData))
_, err = DoHttpThings(updateUserRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
out, err = DoHttpThings(updateUserRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
message.Debugf("PATCH %s:\n%s", updateUserEndpoint, string(out))
return err
}

Expand All @@ -296,16 +297,17 @@ func addReadOnlyUserToRepo(tunnelUrl, repo string) error {
// Send API request to add a user as a read-only collaborator to a repo
addColabEndpoint := fmt.Sprintf("%s/api/v1/repos/%s/%s/collaborators/%s", tunnelUrl, config.ZarfGitPushUser, repo, config.ZarfGitReadUser)
addColabRequest, _ := netHttp.NewRequest("PUT", addColabEndpoint, bytes.NewBuffer(addColabData))
_, err = DoHttpThings(addColabRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
out, err := DoHttpThings(addColabRequest, config.ZarfGitPushUser, config.GetSecret(config.StateGitPush))
message.Debugf("PUT %s:\n%s", addColabEndpoint, string(out))
return err
}

// Add http request boilerplate and perform the request, checking for a successful response
func DoHttpThings(request *netHttp.Request, username, secret string) ([]byte, error) {
message.Debugf("Performing %v http request to %v", request.Method, request.URL)
message.Debugf("Performing %s http request to %#v", request.Method, request.URL)

// Prep the request with boilerplate
client := &netHttp.Client{Timeout: time.Second * 10}
client := &netHttp.Client{Timeout: time.Second * 20}
request.SetBasicAuth(username, secret)
request.Header.Add("accept", "application/json")
request.Header.Add("Content-Type", "application/json")
Expand All @@ -319,7 +321,7 @@ func DoHttpThings(request *netHttp.Request, username, secret string) ([]byte, er

// If we get a 'bad' status code we will have no error, create a useful one to return
if response.StatusCode < 200 || response.StatusCode >= 300 {
err = errors.New(fmt.Sprintf("Got status code of %v during http request with body of: %v", response.StatusCode, string(responseBody)))
err = fmt.Errorf("got status code of %d during http request with body of: %s", response.StatusCode, string(responseBody))
return []byte{}, err
}

Expand Down
2 changes: 1 addition & 1 deletion src/internal/images/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func PushToZarfRegistry(imageTarballPath string, buildImageList []string) error {
message.Debugf("images.PushToZarfRegistry(%v, %v)", imageTarballPath, buildImageList)
message.Debugf("images.PushToZarfRegistry(%s, %s)", imageTarballPath, buildImageList)

// Establish a registry tunnel to send the images to the zarf registry
tunnel := k8s.NewZarfTunnel()
Expand Down
10 changes: 5 additions & 5 deletions src/internal/k8s/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func GetContext() (string, error) {

// ProcessYamlFilesInPath iterates over all yaml files in a given path and performs Zarf templating + image swapping
func ProcessYamlFilesInPath(path string, component types.ZarfComponent) []string {
message.Debugf("k8s.ProcessYamlFilesInPath(%s, %v)", path, component)
message.Debugf("k8s.ProcessYamlFilesInPath(%s, %#v)", path, component)

// Only pull in yml and yaml files
pattern := regexp.MustCompile(`(?mi)\.ya?ml$`)
Expand All @@ -73,7 +73,7 @@ func SplitYAML(yamlData []byte) ([]*unstructured.Unstructured, error) {
for _, yml := range ymls {
u := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(yml), u); err != nil {
return objs, fmt.Errorf("failed to unmarshal manifest: %v", err)
return objs, fmt.Errorf("failed to unmarshal manifest: %#v", err)
}
objs = append(objs, u)
}
Expand All @@ -82,7 +82,7 @@ func SplitYAML(yamlData []byte) ([]*unstructured.Unstructured, error) {

// WaitForHealthyCluster checks for an available K8s cluster every second until timeout.
func WaitForHealthyCluster(timeout time.Duration) error {
message.Debugf("package.WaitForHealthyCluster(%v)", timeout)
message.Debugf("package.WaitForHealthyCluster(%#v)", timeout)

var err error
var nodes *v1.NodeList
Expand All @@ -103,7 +103,7 @@ func WaitForHealthyCluster(timeout time.Duration) error {
// Make sure there is at least one running Node
nodes, err = GetNodes()
if err != nil || len(nodes.Items) < 1 {
message.Debugf("No nodes reporting healthy yet: %v\n", err)
message.Debugf("No nodes reporting healthy yet: %#v\n", err)
continue
}

Expand Down Expand Up @@ -183,7 +183,7 @@ func splitYAMLToString(yamlData []byte) ([]string, error) {
if err == io.EOF {
break
}
return objs, fmt.Errorf("failed to unmarshal manifest: %v", err)
return objs, fmt.Errorf("failed to unmarshal manifest: %#v", err)
}
ext.Raw = bytes.TrimSpace(ext.Raw)
if len(ext.Raw) == 0 || bytes.Equal(ext.Raw, []byte("null")) {
Expand Down
2 changes: 1 addition & 1 deletion src/internal/k8s/configmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func DeleteConfigmap(namespace, name string) error {

// DeleteConfigMapsByLabel deletes a configmap by label(s)
func DeleteConfigMapsByLabel(namespace string, labels map[string]string) error {
message.Debugf("k8s.DeleteConfigMapsByLabel(%s, %v)", namespace, labels)
message.Debugf("k8s.DeleteConfigMapsByLabel(%s, %#v)", namespace, labels)
clientSet := getClientset()

labelSelector, _ := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
Expand Down
2 changes: 1 addition & 1 deletion src/internal/k8s/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func GetNamespaces() (*corev1.NamespaceList, error) {
}

func UpdateNamespace(namespace *corev1.Namespace) (*corev1.Namespace, error) {
message.Debugf("k8s.UpdateNamespace(%v)", namespace)
message.Debugf("k8s.UpdateNamespace(%s)", message.JsonValue(namespace))

clientset := getClientset()
updateOptions := metav1.UpdateOptions{}
Expand Down
10 changes: 5 additions & 5 deletions src/internal/k8s/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func GenerateRegistryPullCreds(namespace, name string) *corev1.Secret {
}

func GenerateTLSSecret(namespace, name string, conf types.GeneratedPKI) (*corev1.Secret, error) {
message.Debugf("k8s.GenerateTLSSecret(%s, %s, %v", namespace, name, conf)
message.Debugf("k8s.GenerateTLSSecret(%s, %s, %s)", namespace, name, message.JsonValue(conf))

if _, err := tls.X509KeyPair(conf.Cert, conf.Key); err != nil {
return nil, err
Expand All @@ -101,7 +101,7 @@ func GenerateTLSSecret(namespace, name string, conf types.GeneratedPKI) (*corev1
}

func ReplaceTLSSecret(namespace, name string, conf types.GeneratedPKI) error {
message.Debugf("k8s.ReplaceTLSSecret(%s, %s, %v)", namespace, name, conf)
message.Debugf("k8s.ReplaceTLSSecret(%s, %s, %s)", namespace, name, message.JsonValue(conf))

secret, err := GenerateTLSSecret(namespace, name, conf)
if err != nil {
Expand All @@ -112,7 +112,7 @@ func ReplaceTLSSecret(namespace, name string, conf types.GeneratedPKI) error {
}

func ReplaceSecret(secret *corev1.Secret) error {
message.Debugf("k8s.ReplaceSecret(%v)", secret)
message.Debugf("k8s.ReplaceSecret(%s, %s)", secret.Namespace, secret.Name)

if _, err := CreateNamespace(secret.Namespace, nil); err != nil {
return fmt.Errorf("unable to create or read the namespace: %w", err)
Expand All @@ -126,7 +126,7 @@ func ReplaceSecret(secret *corev1.Secret) error {
}

func DeleteSecret(secret *corev1.Secret) error {
message.Debugf("k8s.DeleteSecret(%v)", secret)
message.Debugf("k8s.DeleteSecret(%s, %s)", secret.Namespace, secret.Name)
clientSet := getClientset()

namespaceSecrets := clientSet.CoreV1().Secrets(secret.Namespace)
Expand All @@ -140,7 +140,7 @@ func DeleteSecret(secret *corev1.Secret) error {
}

func CreateSecret(secret *corev1.Secret) error {
message.Debugf("k8s.CreateSecret(%v)", secret)
message.Debugf("k8s.CreateSecret(%s, %s)", secret.Namespace, secret.Name)
clientSet := getClientset()

namespaceSecrets := clientSet.CoreV1().Secrets(secret.Namespace)
Expand Down
6 changes: 3 additions & 3 deletions src/internal/k8s/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (

// ReplaceService deletes and re-creates a service
func ReplaceService(service *corev1.Service) (*corev1.Service, error) {
message.Debugf("k8s.ReplaceService(%v)", service)
message.Debugf("k8s.ReplaceService(%#v)", service)

if err :=DeleteService(service.Namespace, service.Name); err != nil {
if err := DeleteService(service.Namespace, service.Name); err != nil {
return nil, err
}

Expand Down Expand Up @@ -49,7 +49,7 @@ func DeleteService(namespace, name string) error {

// CreateService creates the given service in the cluster.
func CreateService(service *corev1.Service) (*corev1.Service, error) {
message.Debugf("k8s.CreateService(%v)", service)
message.Debugf("k8s.CreateService(%#v)", service)
clientset := getClientset()
createOptions := metav1.CreateOptions{}
return clientset.CoreV1().Services(service.Namespace).Create(context.TODO(), service, createOptions)
Expand Down
7 changes: 3 additions & 4 deletions src/internal/k8s/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@ func LoadZarfState() types.ZarfState {
_ = json.Unmarshal(match.Data[ZarfStateDataKey], &state)
}

message.Debug(state)
message.Debugf("ZarfState = %s", message.JsonValue(state))

return state
}

// SaveZarfState takes a given state and makepersists it to the zarf/zarf-state secret
func SaveZarfState(state types.ZarfState) error {
message.Debugf("k8s.SaveZarfState(%v)", state)
message.Debugf("k8s.SaveZarfState()")
message.Debug(message.JsonValue(state))

// Convert the data back to JSON
data, err := json.Marshal(state)
Expand Down Expand Up @@ -71,8 +72,6 @@ func SaveZarfState(state types.ZarfState) error {
Data: dataWrapper,
}

message.Debug(secret)

// Attempt to create or replace the secret and return
if err := ReplaceSecret(secret); err != nil {
return fmt.Errorf("unable to create the zarf state secret")
Expand Down
4 changes: 2 additions & 2 deletions src/internal/k8s/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func StripZarfLabelsAndSecretsFromNamespaces() {
} else {
for _, namespace := range namespaces.Items {
if _, ok := namespace.Labels["zarf.dev/agent"]; ok {
spinner.Updatef("Removing Zarf Agent label for namespace %v", namespace.Name)
spinner.Updatef("Removing Zarf Agent label for namespace %s", namespace.Name)
delete(namespace.Labels, "zarf.dev/agent")
if _, err = UpdateNamespace(&namespace); err != nil {
// This is not a hard failure, but we should log it
Expand All @@ -32,7 +32,7 @@ func StripZarfLabelsAndSecretsFromNamespaces() {
}

for _, namespace := range namespaces.Items {
spinner.Updatef("Removing Zarf secrets for namespace %v", namespace.Name)
spinner.Updatef("Removing Zarf secrets for namespace %s", namespace.Name)
err := clientSet.CoreV1().
Secrets(namespace.Name).
DeleteCollection(context.TODO(), deleteOptions, listOptions)
Expand Down
2 changes: 1 addition & 1 deletion src/internal/message/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func HeaderInfof(format string, a ...any) {
func JsonValue(value any) string {
bytes, err := json.MarshalIndent(value, "", " ")
if err != nil {
Debugf("ERROR marshalling json: %v", err)
Debugf("ERROR marshalling json: %w", err)
}
return string(bytes)
}
Expand Down
Loading

0 comments on commit 2378154

Please sign in to comment.