Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Debug Message Cleanup #511

Merged
merged 9 commits into from
Jul 18, 2022
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
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
13 changes: 7 additions & 6 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.Debug(string(out))
jeff-mccoy marked this conversation as resolved.
Show resolved Hide resolved
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.Debug(string(out))
return err
}

Expand All @@ -302,10 +303,10 @@ func addReadOnlyUserToRepo(tunnelUrl, repo string) error {

// 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 +320,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
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
11 changes: 6 additions & 5 deletions src/internal/k8s/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ 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", namespace, name)
message.Debug(message.JsonValue(conf))
jeff-mccoy marked this conversation as resolved.
Show resolved Hide resolved

if _, err := tls.X509KeyPair(conf.Cert, conf.Key); err != nil {
return nil, err
Expand All @@ -101,7 +102,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 +113,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 +127,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 +141,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.Debug(message.JsonValue(state))
jeff-mccoy marked this conversation as resolved.
Show resolved Hide resolved

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))
jeff-mccoy marked this conversation as resolved.
Show resolved Hide resolved

// 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
14 changes: 13 additions & 1 deletion src/internal/packager/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
const horizontalRule = "───────────────────────────────────────────────────────────────────────────────────────"

func getValidComponents(allComponents []types.ZarfComponent, requestedComponentNames []string) []types.ZarfComponent {
message.Debugf("packager.getValidComponents(%#v, %#v)", allComponents, requestedComponentNames)

var validComponentsList []types.ZarfComponent
var orderedKeys []string
var choiceComponents []string
Expand Down Expand Up @@ -90,6 +92,8 @@ func getValidComponents(allComponents []types.ZarfComponent, requestedComponentN

// Match on the first requested component that is not in the list of valid components and return the component name
func validateRequests(validComponentsList []types.ZarfComponent, requestedComponentNames, choiceComponents []string) error {
message.Debugf("packager.validateRequests(%#v, %#v, %#v)", validComponentsList, requestedComponentNames, choiceComponents)

// Loop through each requested component names
for _, componentName := range requestedComponentNames {
found := false
Expand Down Expand Up @@ -118,6 +122,8 @@ func validateRequests(validComponentsList []types.ZarfComponent, requestedCompon
}

func isRequiredOrRequested(component types.ZarfComponent, requestedComponentNames []string) bool {
message.Debugf("packager.isRequiredOrRequested(%#v, %#v)", component, requestedComponentNames)

// If the component is required, then just return true
if component.Required {
return true
Expand All @@ -139,6 +145,8 @@ func isRequiredOrRequested(component types.ZarfComponent, requestedComponentName

// Confirm optional component
func confirmOptionalComponent(component types.ZarfComponent) (confirmComponent bool) {
message.Debugf("packager.confirmOptionalComponent(%#v)", component)

// Confirm flag passed, just use defaults
if config.CommonOptions.Confirm {
return component.Default
Expand All @@ -164,6 +172,8 @@ func confirmOptionalComponent(component types.ZarfComponent) (confirmComponent b
}

func confirmChoiceGroup(componentGroup []types.ZarfComponent) types.ZarfComponent {
message.Debugf("packager.confirmChoiceGroup(%#v)", componentGroup)

// Confirm flag passed, just use defaults
if config.CommonOptions.Confirm {
var componentNames []string
Expand All @@ -176,7 +186,7 @@ func confirmChoiceGroup(componentGroup []types.ZarfComponent) types.ZarfComponen
componentNames = append(componentNames, component.Name)
}
// If no default component was found, give up
message.Fatalf(nil, "You must specify at least one component from the group %v when using the --confirm flag.", componentNames)
message.Fatalf(nil, "You must specify at least one component from the group %#v when using the --confirm flag.", componentNames)
}

pterm.Println(horizontalRule)
Expand All @@ -199,6 +209,8 @@ func confirmChoiceGroup(componentGroup []types.ZarfComponent) types.ZarfComponen
}

func appendIfNotExists(slice []string, item string) []string {
message.Debugf("packager.appendIfNotExists(%#v, %s)", slice, item)

for _, s := range slice {
if s == item {
return slice
Expand Down
Loading