Skip to content

Commit

Permalink
refactor: remove message.Fatal and spinner.Fatal (#2676)
Browse files Browse the repository at this point in the history
  • Loading branch information
phillebaba authored Jul 1, 2024
2 parents b84cf3f + 9c3532c commit 5a2ada1
Show file tree
Hide file tree
Showing 15 changed files with 97 additions and 98 deletions.
17 changes: 13 additions & 4 deletions src/cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ var devDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

if err := pkgClient.DevDeploy(cmd.Context()); err != nil {
Expand All @@ -72,10 +75,13 @@ var devGenerateCmd = &cobra.Command{
pkgConfig.CreateOpts.BaseDir = "."
pkgConfig.FindImagesOpts.RepoHelmChartPath = pkgConfig.GenerateOpts.GitPath

pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

err := pkgClient.Generate()
err = pkgClient.Generate()
if err != nil {
return err
}
Expand Down Expand Up @@ -217,7 +223,10 @@ var devFindImagesCmd = &cobra.Command{
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)
pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

if _, err := pkgClient.FindImages(cmd.Context()); err != nil {
Expand Down
5 changes: 4 additions & 1 deletion src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ var initCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient := packager.NewOrDie(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

err = pkgClient.Deploy(cmd.Context())
Expand Down
35 changes: 28 additions & 7 deletions src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ var packageCreateCmd = &cobra.Command{
pkgConfig.CreateOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)

pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

if err := pkgClient.Create(cmd.Context()); err != nil {
Expand All @@ -81,7 +84,10 @@ var packageDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

ctx := cmd.Context()
Expand All @@ -106,7 +112,10 @@ var packageMirrorCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()
if err := pkgClient.Mirror(cmd.Context()); err != nil {
return fmt.Errorf("failed to mirror package: %w", err)
Expand All @@ -131,7 +140,10 @@ var packageInspectCmd = &cobra.Command{
if err != nil {
return err
}
pkgClient := packager.NewOrDie(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()
if err := pkgClient.Inspect(cmd.Context()); err != nil {
return fmt.Errorf("failed to inspect package: %w", err)
Expand Down Expand Up @@ -200,7 +212,10 @@ var packageRemoveCmd = &cobra.Command{
if err != nil {
return err
}
pkgClient := packager.NewOrDie(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()
if err := pkgClient.Remove(cmd.Context()); err != nil {
return fmt.Errorf("unable to remove the package with an error of: %w", err)
Expand Down Expand Up @@ -238,7 +253,10 @@ var packagePublishCmd = &cobra.Command{

pkgConfig.PublishOpts.PackageDestination = ref.String()

pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()

if err := pkgClient.Publish(cmd.Context()); err != nil {
Expand All @@ -255,7 +273,10 @@ var packagePullCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
pkgConfig.PkgOpts.PackageSource = args[0]
pkgClient := packager.NewOrDie(&pkgConfig)
pkgClient, err := packager.New(&pkgConfig)
if err != nil {
return err
}
defer pkgClient.ClearTempPaths()
if err := pkgClient.Pull(cmd.Context()); err != nil {
return fmt.Errorf("failed to pull package: %w", err)
Expand Down
5 changes: 4 additions & 1 deletion src/cmd/tools/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,10 @@ var generatePKICmd = &cobra.Command{
Short: lang.CmdToolsGenPkiShort,
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
pki := pki.GeneratePKI(args[0], subAltNames...)
pki, err := pki.GeneratePKI(args[0], subAltNames...)
if err != nil {
return err
}
if err := os.WriteFile("tls.ca", pki.CA, helpers.ReadAllWriteUser); err != nil {
return err
}
Expand Down
7 changes: 4 additions & 3 deletions src/internal/agent/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ import (
)

// NewAdmissionServer creates a http.Server for the mutating webhook admission handler.
func NewAdmissionServer(ctx context.Context, port string) *http.Server {
func NewAdmissionServer(ctx context.Context, port string) (*http.Server, error) {
message.Debugf("http.NewAdmissionServer(%s)", port)

c, err := cluster.NewCluster()
if err != nil {
message.Fatalf(err, err.Error())
return nil, err
}

// Routers
Expand All @@ -46,11 +46,12 @@ func NewAdmissionServer(ctx context.Context, port string) *http.Server {
mux.Handle("/mutate/argocd-repository", admissionHandler.Serve(argocdRepositoryMutation))
mux.Handle("/metrics", promhttp.Handler())

return &http.Server{
srv := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
ReadHeaderTimeout: 5 * time.Second, // Set ReadHeaderTimeout to avoid Slowloris attacks
}
return srv, nil
}

// NewProxyServer creates and returns an http proxy server.
Expand Down
6 changes: 5 additions & 1 deletion src/internal/agent/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ const (
// StartWebhook launches the Zarf agent mutating webhook in the cluster.
func StartWebhook(ctx context.Context) error {
message.Debug("agent.StartWebhook()")
return startServer(ctx, agentHttp.NewAdmissionServer(ctx, httpPort))
srv, err := agentHttp.NewAdmissionServer(ctx, httpPort)
if err != nil {
return err
}
return startServer(ctx, srv)
}

// StartHTTPProxy launches the zarf agent proxy in the cluster.
Expand Down
8 changes: 4 additions & 4 deletions src/internal/packager/helm/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (h *Helm) PackageChartFromLocalFiles(cosignKeyPath string) error {
var saved string
temp := filepath.Join(h.chartPath, "temp")
if _, ok := cl.(loader.DirLoader); ok {
err = h.buildChartDependencies(spinner)
err = h.buildChartDependencies()
if err != nil {
return fmt.Errorf("unable to build dependencies for the chart: %w", err)
}
Expand Down Expand Up @@ -157,7 +157,7 @@ func (h *Helm) DownloadPublishedChart(cosignKeyPath string) error {
if registry.IsOCI(h.chart.URL) {
regClient, err = registry.NewClient(registry.ClientOptEnableCache(true))
if err != nil {
spinner.Fatalf(err, "Unable to create a new registry client")
return fmt.Errorf("unable to create the new registry client: %w", err)
}
chartURL = h.chart.URL
// Explicitly set the pull version for OCI
Expand Down Expand Up @@ -279,11 +279,11 @@ func (h *Helm) packageValues(cosignKeyPath string) error {
}

// buildChartDependencies builds the helm chart dependencies
func (h *Helm) buildChartDependencies(spinner *message.Spinner) error {
func (h *Helm) buildChartDependencies() error {
// Download and build the specified dependencies
regClient, err := registry.NewClient(registry.ClientOptEnableCache(true))
if err != nil {
spinner.Fatalf(err, "Unable to create a new registry client")
return fmt.Errorf("unable to create a new registry client: %w", err)
}

h.settings = cli.New()
Expand Down
12 changes: 10 additions & 2 deletions src/pkg/cluster/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ func (c *Cluster) InitZarfState(ctx context.Context, initOptions types.ZarfInitO
state.Distro = distro

// Setup zarf agent PKI
state.AgentTLS = pki.GeneratePKI(config.ZarfAgentHost)
agentTLS, err := pki.GeneratePKI(config.ZarfAgentHost)
if err != nil {
return err
}
state.AgentTLS = agentTLS

namespaceList, err := c.Clientset.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
if err != nil {
Expand Down Expand Up @@ -359,7 +363,11 @@ func MergeZarfState(oldState *types.ZarfState, initOptions types.ZarfInitOptions
}
}
if slices.Contains(services, message.AgentKey) {
newState.AgentTLS = pki.GeneratePKI(config.ZarfAgentHost)
agentTLS, err := pki.GeneratePKI(config.ZarfAgentHost)
if err != nil {
return nil, err
}
newState.AgentTLS = agentTLS
}

return &newState, nil
Expand Down
4 changes: 3 additions & 1 deletion src/pkg/cluster/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,10 @@ func TestMergeZarfStateArtifact(t *testing.T) {
func TestMergeZarfStateAgent(t *testing.T) {
t.Parallel()

agentTLS, err := pki.GeneratePKI("example.com")
require.NoError(t, err)
oldState := &types.ZarfState{
AgentTLS: pki.GeneratePKI("example.com"),
AgentTLS: agentTLS,
}
newState, err := MergeZarfState(oldState, types.ZarfInitOptions{}, []string{message.AgentKey})
require.NoError(t, err)
Expand Down
19 changes: 0 additions & 19 deletions src/pkg/message/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"io"
"net/http"
"os"
"runtime/debug"
"strings"
"time"

Expand Down Expand Up @@ -162,20 +161,6 @@ func WarnErrf(err any, format string, a ...any) {
Warnf(format, a...)
}

// Fatal prints a fatal error message and exits with a 1.
func Fatal(err any, message string) {
debugPrinter(2, err)
errorPrinter(2).Println(message)
debugPrinter(2, string(debug.Stack()))
os.Exit(1)
}

// Fatalf prints a fatal error message and exits with a 1 with a given format.
func Fatalf(err any, format string, a ...any) {
message := Paragraph(format, a...)
Fatal(err, message)
}

// Info prints an info message.
func Info(message string) {
Infof("%s", message)
Expand Down Expand Up @@ -351,7 +336,3 @@ func debugPrinter(offset int, a ...any) {
Println(a...)
}
}

func errorPrinter(offset int) *pterm.PrefixPrinter {
return pterm.Error.WithShowLineNumber(logLevel > 2).WithLineNumberOffset(offset)
}
15 changes: 0 additions & 15 deletions src/pkg/message/spinner.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,3 @@ func (p *Spinner) Errorf(err error, format string, a ...any) {
Warnf(format, a...)
debugPrinter(2, err)
}

// Fatal calls message.Fatalf with the given error.
func (p *Spinner) Fatal(err error) {
p.Fatalf(err, p.startText)
}

// Fatalf calls message.Fatalf with the given error and format.
func (p *Spinner) Fatalf(err error, format string, a ...any) {
if p.spinner != nil {
p.spinner.RemoveWhenDone = true
_ = p.spinner.Stop()
activeSpinner = nil
}
Fatalf(err, format, a...)
}
18 changes: 0 additions & 18 deletions src/pkg/packager/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,24 +117,6 @@ func New(cfg *types.PackagerConfig, mods ...Modifier) (*Packager, error) {
return pkgr, nil
}

/*
NewOrDie creates a new package instance with the provided config or throws a fatal error.
Note: This function creates a tmp directory that should be cleaned up with p.ClearTempPaths().
*/
func NewOrDie(config *types.PackagerConfig, mods ...Modifier) *Packager {
var (
err error
pkgr *Packager
)

if pkgr, err = New(config, mods...); err != nil {
message.Fatalf(err, "Unable to setup the package config: %s", err.Error())
}

return pkgr
}

// setTempDirectory sets the temp directory for the packager.
func (p *Packager) setTempDirectory(path string) error {
dir, err := utils.MakeTempDir(path)
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/packager/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ func (p *Packager) setupState(ctx context.Context) (err error) {
return nil
}()
if err != nil {
spinner.Fatalf(err, "Unable to create the zarf namespace")
return fmt.Errorf("unable to create the Zarf namespace: %w", err)
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/pkg/packager/deploy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ func TestGenerateValuesOverrides(t *testing.T) {
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
p := NewOrDie(&types.PackagerConfig{DeployOpts: tt.deployOpts}, WithSource(&sources.TarballSource{}))
p, err := New(&types.PackagerConfig{DeployOpts: tt.deployOpts}, WithSource(&sources.TarballSource{}))
require.NoError(t, err)
for k, v := range tt.setVariables {
p.variableConfig.SetVariable(k, v, false, false, variables.RawVariableType)
}
Expand Down
Loading

0 comments on commit 5a2ada1

Please sign in to comment.