diff --git a/certification/pyxis/builder.go b/certification/pyxis/builder.go index a20b8fef..0dbda4e8 100644 --- a/certification/pyxis/builder.go +++ b/certification/pyxis/builder.go @@ -7,7 +7,7 @@ import ( "io" "net/http" - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) // certificationInputBuilder facilitates the building of CertificationInput for @@ -68,7 +68,7 @@ func (b *certificationInputBuilder) Finalize() (*CertificationInput, error) { // Errors are logged, but will not halt execution. func (b *certificationInputBuilder) WithCertImage(r io.Reader) *certificationInputBuilder { if err := b.storeCertImage(r); err != nil { - log.Error(fmt.Errorf("cert image could not be stored: %v", err)) + log.L().Error(fmt.Errorf("cert image could not be stored: %v", err)) } return b @@ -78,7 +78,7 @@ func (b *certificationInputBuilder) WithCertImage(r io.Reader) *certificationInp // Errors are logged, but will not halt execution. func (b *certificationInputBuilder) WithPreflightResults(r io.Reader) *certificationInputBuilder { if err := b.storePreflightResults(r); err != nil { - log.Error(fmt.Errorf("preflight results could not be stored: %v", err)) + log.L().Error(fmt.Errorf("preflight results could not be stored: %v", err)) } return b @@ -88,7 +88,7 @@ func (b *certificationInputBuilder) WithPreflightResults(r io.Reader) *certifica // Errors are logged, but will not halt execution. func (b *certificationInputBuilder) WithRPMManifest(r io.Reader) *certificationInputBuilder { if err := b.storeRPMManifest(r); err != nil { - log.Error(fmt.Errorf("rpm manifest could not be stored: %v", err)) + log.L().Error(fmt.Errorf("rpm manifest could not be stored: %v", err)) } return b @@ -102,7 +102,7 @@ func (b *certificationInputBuilder) WithRPMManifest(r io.Reader) *certificationI func (b *certificationInputBuilder) WithArtifact(r io.Reader, filename string) *certificationInputBuilder { bts, err := io.ReadAll(r) if err != nil { - log.Error(fmt.Errorf("artifact could not be stored: %s: %v", filename, err)) + log.L().Error(fmt.Errorf("artifact could not be stored: %s: %v", filename, err)) return b } diff --git a/certification/pyxis/pyxis.go b/certification/pyxis/pyxis.go index e47815e6..aedca53a 100644 --- a/certification/pyxis/pyxis.go +++ b/certification/pyxis/pyxis.go @@ -9,7 +9,8 @@ import ( "net/http" "github.com/shurcooL/graphql" - log "github.com/sirupsen/logrus" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) const ( @@ -54,7 +55,7 @@ func (p *pyxisClient) createImage(ctx context.Context, certImage *CertImage) (*C return nil, err } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -94,7 +95,7 @@ func (p *pyxisClient) getImage(ctx context.Context, dockerImageDigest string) (* return nil, fmt.Errorf("could not create new request: %w", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -241,7 +242,7 @@ func (p *pyxisClient) createRPMManifest(ctx context.Context, rpmManifest *RPMMan return nil, fmt.Errorf("could not create new request: %w", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -280,7 +281,7 @@ func (p *pyxisClient) getRPMManifest(ctx context.Context, imageID string) (*RPMM return nil, fmt.Errorf("could not create new request: %w", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -314,7 +315,7 @@ func (p *pyxisClient) GetProject(ctx context.Context) (*CertProject, error) { if err != nil { return nil, fmt.Errorf("could not create new request: %v", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -366,7 +367,7 @@ func (p *pyxisClient) updateProject(ctx context.Context, certProject *CertProjec return nil, fmt.Errorf("could not create new request: %w", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { @@ -442,7 +443,7 @@ func (p *pyxisClient) createArtifact(ctx context.Context, artifact *Artifact) (* return nil, fmt.Errorf("could not create new request: %w", err) } - log.Debugf("URL is: %s", req.URL) + log.L().Debugf("URL is: %s", req.URL) resp, err := p.Client.Do(req) if err != nil { diff --git a/certification/pyxis/pyxis_suite_test.go b/certification/pyxis/pyxis_suite_test.go index e431cdd1..281132e4 100644 --- a/certification/pyxis/pyxis_suite_test.go +++ b/certification/pyxis/pyxis_suite_test.go @@ -11,7 +11,9 @@ import ( . "github.com/onsi/ginkgo/v2/dsl/core" . "github.com/onsi/gomega" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) func TestPyxis(t *testing.T) { @@ -20,8 +22,8 @@ func TestPyxis(t *testing.T) { } func init() { - log.SetFormatter(&log.TextFormatter{}) - log.SetLevel(log.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) } type localRoundTripper struct { @@ -57,7 +59,7 @@ type ( // to dedupe. Acknowledged that it is a bit fragile. -bpc func (p *pyxisProjectHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the Project ServeHTTP") + log.L().Trace("In the Project ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() @@ -83,13 +85,13 @@ func (p *pyxisProjectHandler) ServeHTTP(response http.ResponseWriter, request *h } func (p *pyxisImageHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the Image ServeHTTP") + log.L().Trace("In the Image ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() } responseString := `{"_id":"blah","certified":false,"deleted":false,"image_id":"123456789abc"}` - log.Tracef("Method: %s", request.Method) + log.L().Tracef("Method: %s", request.Method) switch { case request.Method == http.MethodPost && strings.Contains(request.Header["X-Api-Key"][0], "my-update-image"): response.WriteHeader(http.StatusConflict) @@ -106,7 +108,7 @@ func (p *pyxisImageHandler) ServeHTTP(response http.ResponseWriter, request *htt case request.Method == http.MethodPost && request.Header["X-Api-Key"][0] == "my-bad-image-api-token": response.WriteHeader(http.StatusConflict) case request.Method == http.MethodGet && request.Header["X-Api-Key"][0] == "my-bad-401-image-api-token": - log.Trace("get with 401") + log.L().Trace("get with 401") response.WriteHeader(http.StatusUnauthorized) case request.Header["X-Api-Key"][0] == "my-bad-image-api-token": response.WriteHeader(http.StatusUnauthorized) @@ -122,7 +124,7 @@ func (p *pyxisImageHandler) ServeHTTP(response http.ResponseWriter, request *htt } func (p *pyxisRPMManifestHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the RPM Manifest ServeHTTP") + log.L().Trace("In the RPM Manifest ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() @@ -145,7 +147,7 @@ func (p *pyxisRPMManifestHandler) ServeHTTP(response http.ResponseWriter, reques } func (p *pyxisTestResultsHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the Results ServeHTTP") + log.L().Trace("In the Results ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() @@ -159,7 +161,7 @@ func (p *pyxisTestResultsHandler) ServeHTTP(response http.ResponseWriter, reques } func (p *pyxisGraphqlLayerHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the graphql Layers ServeHTTP") + log.L().Trace("In the graphql Layers ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() @@ -189,7 +191,7 @@ func (p *pyxisGraphqlLayerHandler) ServeHTTP(response http.ResponseWriter, reque } func (p *pyxisGraphqlFindImagesHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { - log.Trace("In the graphql FindImages ServeHTTP") + log.L().Trace("In the graphql FindImages ServeHTTP") response.Header().Set("Content-Type", "application/json") if request.Body != nil { defer request.Body.Close() diff --git a/certification/runtime/assets.go b/certification/runtime/assets.go index 9b13807e..d6ec5561 100644 --- a/certification/runtime/assets.go +++ b/certification/runtime/assets.go @@ -7,10 +7,10 @@ import ( "strings" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/authn" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/google/go-containerregistry/pkg/crane" cranev1 "github.com/google/go-containerregistry/pkg/v1" - log "github.com/sirupsen/logrus" ) // images maps the images use by preflight with their purpose. @@ -41,7 +41,7 @@ func imageList(ctx context.Context) []string { base := strings.Split(image, ":")[0] digest, err := crane.Digest(image, options...) if err != nil { - log.Error(fmt.Errorf("could not retrieve image digest: %w", err)) + log.L().Error(fmt.Errorf("could not retrieve image digest: %w", err)) // Skip this entry continue } @@ -63,7 +63,7 @@ func Assets(ctx context.Context) AssetData { // returned, otherwise, the default is returned. func ScorecardImage(userProvidedScorecardImage string) string { if userProvidedScorecardImage != "" { - log.Debugf("Using %s as the scorecard test image", userProvidedScorecardImage) + log.L().Debugf("Using %s as the scorecard test image", userProvidedScorecardImage) return userProvidedScorecardImage } return images["scorecard"] diff --git a/cmd/preflight/cmd/check_container.go b/cmd/preflight/cmd/check_container.go index c0ff4e0c..c6e6b9d9 100644 --- a/cmd/preflight/cmd/check_container.go +++ b/cmd/preflight/cmd/check_container.go @@ -12,9 +12,9 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/container" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/cli" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/lib" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/version" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -67,7 +67,7 @@ func checkContainerCmd() *cobra.Command { // checkContainerRunE executes checkContainer using the user args to inform the execution. func checkContainerRunE(cmd *cobra.Command, args []string) error { - log.Info("certification library version ", version.Version.String()) + log.L().Info("certification library version ", version.Version.String()) ctx := cmd.Context() containerImage := args[0] diff --git a/cmd/preflight/cmd/check_operator.go b/cmd/preflight/cmd/check_operator.go index 391a4677..07098def 100644 --- a/cmd/preflight/cmd/check_operator.go +++ b/cmd/preflight/cmd/check_operator.go @@ -11,10 +11,10 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/runtime" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/cli" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/lib" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/operator" "github.com/redhat-openshift-ecosystem/openshift-preflight/version" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -72,7 +72,7 @@ func ensureIndexImageConfigIsSet() error { // checkOperatorRunE executes checkOperator using the user args to inform the execution. func checkOperatorRunE(cmd *cobra.Command, args []string) error { - log.Info("certification library version ", version.Version.String()) + log.L().Info("certification library version ", version.Version.String()) ctx := cmd.Context() operatorImage := args[0] diff --git a/cmd/preflight/cmd/root.go b/cmd/preflight/cmd/root.go index f51e0781..3fbe064a 100644 --- a/cmd/preflight/cmd/root.go +++ b/cmd/preflight/cmd/root.go @@ -6,12 +6,15 @@ import ( "io" "os" + "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/version" - log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var configFileUsed bool @@ -80,21 +83,22 @@ func initConfig() { // preRunConfig is used by cobra.PreRun in all non-root commands to load all necessary configurations func preRunConfig(cmd *cobra.Command, args []string) { + l := log.L() // set up logging logname := viper.GetString("logfile") logFile, err := os.OpenFile(logname, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err == nil { mw := io.MultiWriter(os.Stderr, logFile) - log.SetOutput(mw) + l.SetOutput(mw) } else { - log.Debug("Failed to log to file, using default stderr") + l.Debug("Failed to log to file, using default stderr") } - if ll, err := log.ParseLevel(viper.GetString("loglevel")); err == nil { - log.SetLevel(ll) + if ll, err := logrus.ParseLevel(viper.GetString("loglevel")); err == nil { + l.SetLevel(ll) } - log.SetFormatter(&log.TextFormatter{}) + l.SetFormatter(&logrus.TextFormatter{}) if !configFileUsed { - log.Debug("config file not found, proceeding without it") + l.Debug("config file not found, proceeding without it") } } diff --git a/internal/authn/keychain.go b/internal/authn/keychain.go index a8a2799c..0b33bc77 100644 --- a/internal/authn/keychain.go +++ b/internal/authn/keychain.go @@ -9,7 +9,8 @@ import ( "github.com/docker/cli/cli/config/types" craneauthn "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" - log "github.com/sirupsen/logrus" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) type preflightKeychain struct { @@ -49,7 +50,7 @@ func PreflightKeychain(opts ...PreflightKeychainOption) craneauthn.Keychain { // If the file cannot be found or read, that constitutes an error. // Can return os.IsNotExist. func (k *preflightKeychain) Resolve(target craneauthn.Resource) (craneauthn.Authenticator, error) { - log.Trace("entering preflight keychain Resolve") + log.L().Trace("entering preflight keychain Resolve") if k.dockercfg == "" { // No file specified. No auth expected diff --git a/internal/authn/keychain_test.go b/internal/authn/keychain_test.go index b7257889..e075ac58 100644 --- a/internal/authn/keychain_test.go +++ b/internal/authn/keychain_test.go @@ -24,7 +24,9 @@ import ( craneauthn "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var ( @@ -201,6 +203,6 @@ func TestVariousPaths(t *testing.T) { } func init() { - log.SetFormatter(&log.TextFormatter{}) - log.SetLevel(log.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) } diff --git a/internal/bundle/bundle.go b/internal/bundle/bundle.go index 47c09295..a17c36ff 100644 --- a/internal/bundle/bundle.go +++ b/internal/bundle/bundle.go @@ -12,9 +12,11 @@ import ( "github.com/operator-framework/api/pkg/manifests" "github.com/operator-framework/api/pkg/validation" olmvalidation "github.com/redhat-openshift-ecosystem/ocp-olm-catalog-validator/pkg/validation" - log "github.com/sirupsen/logrus" + rbacv1 "k8s.io/api/rbac/v1" "sigs.k8s.io/yaml" + + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) // This table signifies what the NEXT release of OpenShift will @@ -30,8 +32,8 @@ var ocpToKubeVersion = map[string]string{ const latestReleasedVersion = "4.11" func Validate(ctx context.Context, imagePath string) (*Report, error) { - log.Trace("reading annotations file from the bundle") - log.Debug("image extraction directory is ", imagePath) + log.L().Trace("reading annotations file from the bundle") + log.L().Debug("image extraction directory is ", imagePath) bundle, err := manifests.GetBundleFromDir(imagePath) if err != nil { @@ -65,7 +67,7 @@ func Validate(ctx context.Context, imagePath string) (*Report, error) { return nil, fmt.Errorf("%v", err) } if k8sVer, found := ocpToKubeVersion[targetVersion]; found { - log.Debugf("OpenShift %s detected in annotations. Running with additional checks enabled.", targetVersion) + log.L().Debugf("OpenShift %s detected in annotations. Running with additional checks enabled.", targetVersion) optionalValues = make(map[string]string) optionalValues["k8s-version"] = k8sVer } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 7a1a4c99..3d942b44 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -9,12 +9,11 @@ import ( "os" "strings" - log "github.com/sirupsen/logrus" - "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/formatters" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/runtime" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/lib" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) type CheckConfig struct { @@ -79,7 +78,7 @@ func RunPreflight( } } - log.Infof("Preflight result: %s", convertPassedOverall(results.PassedOverall)) + log.L().Infof("Preflight result: %s", convertPassedOverall(results.PassedOverall)) return nil } @@ -102,7 +101,7 @@ func writeJUnit(ctx context.Context, results runtime.Results) error { if err != nil { return err } - log.Tracef("JUnitXML written to %s", junitFilename) + log.L().Tracef("JUnitXML written to %s", junitFilename) } return nil diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index a0b3c0d5..38ced58b 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -11,6 +11,9 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + // This file imports logrus instead of internal/log because a standalone logger is used + // for test specs defined here. log "github.com/sirupsen/logrus" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" diff --git a/internal/engine/engine.go b/internal/engine/engine.go index d5b33362..000d0051 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -18,11 +18,14 @@ import ( "sync" "time" + "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/pyxis" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/runtime" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/authn" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/openshift" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/rpm" @@ -31,8 +34,6 @@ import ( cranev1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/cache" "github.com/google/go-containerregistry/pkg/v1/remote" - - log "github.com/sirupsen/logrus" ) // CraneEngine implements a certification.CheckEngine, and leverage crane to interact with @@ -67,7 +68,7 @@ type CraneEngine struct { } func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { - log.Debug("target image: ", c.Image) + log.L().Debug("target image: ", c.Image) // prepare crane runtime options, if necessary options := []crane.Option{ @@ -95,7 +96,7 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { } // pull the image and save to fs - log.Debug("pulling image from target registry") + log.L().Debug("pulling image from target registry") img, err := crane.Pull(c.Image, options...) if err != nil { return fmt.Errorf("failed to pull remote container: %v", err) @@ -106,10 +107,10 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { if err != nil { return fmt.Errorf("failed to create temporary directory: %v", err) } - log.Debug("temporary directory is ", tmpdir) + log.L().Debug("temporary directory is ", tmpdir) defer func() { if err := os.RemoveAll(tmpdir); err != nil { - log.Errorf("unable to clean up tmpdir %s: %v", tmpdir, err) + log.L().Errorf("unable to clean up tmpdir %s: %v", tmpdir, err) } }() @@ -126,25 +127,25 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { } // export/flatten, and extract - log.Debug("exporting and flattening image") + log.L().Debug("exporting and flattening image") wg := sync.WaitGroup{} wg.Add(1) r, w := io.Pipe() go func() { defer w.Close() - log.Debugf("writing container filesystem to output dir: %s", containerFSPath) + log.L().Debugf("writing container filesystem to output dir: %s", containerFSPath) err = crane.Export(img, w) if err != nil { // TODO: Handle this error more effectively. Right now we rely on // error handling in the logic to extract this export in a lower // line, but we should probably exit early if the export encounters // an error, which requires watching multiple error streams. - log.Error("unable to export and flatten container filesystem:", err) + log.L().Error("unable to export and flatten container filesystem:", err) } wg.Done() }() - log.Debug("extracting container filesystem to ", containerFSPath) + log.L().Debug("extracting container filesystem to ", containerFSPath) if err := untar(containerFSPath, r); err != nil { return fmt.Errorf("failed to extract tarball: %v", err) } @@ -179,21 +180,21 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { // Record test cluster version c.results.TestedOn, err = openshift.GetOpenshiftClusterVersion(c.Kubeconfig) if err != nil { - log.Errorf("could not determine test cluster version: %v", err) + log.L().Errorf("could not determine test cluster version: %v", err) } } else { - log.Debug("Container checks do not require a cluster. skipping cluster version check.") + log.L().Debug("Container checks do not require a cluster. skipping cluster version check.") c.results.TestedOn = runtime.UnknownOpenshiftClusterVersion() } // execute checks - log.Debug("executing checks") + log.L().Debug("executing checks") for _, check := range c.Checks { c.results.TestedImage = c.Image - log.Debug("running check: ", check.Name()) + log.L().Debug("running check: ", check.Name()) if check.Metadata().Level == "optional" { - log.Infof("Check %s is not currently being enforced.", check.Name()) + log.L().Infof("Check %s is not currently being enforced.", check.Name()) } // run the validation @@ -202,18 +203,18 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { checkElapsedTime := time.Since(checkStartTime) if err != nil { - log.WithFields(log.Fields{"result": "ERROR", "err": err}).Info("check completed: ", check.Name()) + log.L().WithFields(logrus.Fields{"result": "ERROR", "err": err}).Info("check completed: ", check.Name()) c.results.Errors = appendUnlessOptional(c.results.Errors, runtime.Result{Check: check, ElapsedTime: checkElapsedTime}) continue } if !checkPassed { - log.WithFields(log.Fields{"result": "FAILED"}).Info("check completed: ", check.Name()) + log.L().WithFields(logrus.Fields{"result": "FAILED"}).Info("check completed: ", check.Name()) c.results.Failed = appendUnlessOptional(c.results.Failed, runtime.Result{Check: check, ElapsedTime: checkElapsedTime}) continue } - log.WithFields(log.Fields{"result": "PASSED"}).Info("check completed: ", check.Name()) + log.L().WithFields(logrus.Fields{"result": "PASSED"}).Info("check completed: ", check.Name()) c.results.Passed = appendUnlessOptional(c.results.Passed, runtime.Result{Check: check, ElapsedTime: checkElapsedTime}) } @@ -227,7 +228,7 @@ func (c *CraneEngine) ExecuteChecks(ctx context.Context) error { // hash the contents of the bundle. md5sum, err := generateBundleHash(ctx, c.imageRef.ImageFSPath) if err != nil { - log.Errorf("could not generate bundle hash: %v", err) + log.L().Errorf("could not generate bundle hash: %v", err) } c.results.CertificationHash = md5sum } else { // for containers: @@ -262,7 +263,7 @@ func tagDigestBindingInfo(providedIdentifier string, resolvedDigest string) (msg "no tag will be associated with this image. " + "If you would like to associate a tag with this image, " + "please rerun this tool replacing your image reference with a tag.", - log.Warn + log.L().Warn } return fmt.Sprintf( @@ -272,7 +273,7 @@ func tagDigestBindingInfo(providedIdentifier string, resolvedDigest string) (msg `You may then add or remove any supplemental tags `+ `through your Red Hat Connect portal as you see fit.`, providedIdentifier, resolvedDigest, - ), log.Info + ), log.L().Info } func generateBundleHash(ctx context.Context, bundlePath string) (string, error) { @@ -320,7 +321,7 @@ func generateBundleHash(ctx context.Context, bundlePath string) (string, error) sum := fmt.Sprintf("%x", md5.Sum(hashBuffer.Bytes())) - log.Debugf("md5 sum: %s", sum) + log.L().Debugf("md5 sum: %s", sum) return sum, nil } @@ -389,7 +390,7 @@ func untar(dst string, r io.Reader) error { case tar.TypeSymlink: err := os.Symlink(header.Linkname, filepath.Join(dst, header.Name)) if err != nil { - log.Println(fmt.Sprintf("Error creating link: %s. Ignoring.", header.Name)) + log.L().Println(fmt.Sprintf("Error creating link: %s. Ignoring.", header.Name)) continue } } @@ -511,7 +512,7 @@ func writeCertImage(ctx context.Context, imageRef certification.ImageReference) return fmt.Errorf("failed to save file to artifacts directory: %w", err) } - log.Tracef("image config written to disk: %s", fileName) + log.L().Tracef("image config written to disk: %s", fileName) } return nil @@ -525,7 +526,7 @@ func getBgName(srcrpm string) string { func writeRPMManifest(ctx context.Context, containerFSPath string) error { pkgList, err := rpm.GetPackageList(ctx, containerFSPath) if err != nil { - log.Errorf("could not get rpm list, continuing without it: %v", err) + log.L().Errorf("could not get rpm list, continuing without it: %v", err) } // covert rpm struct to pxyis struct @@ -546,7 +547,7 @@ func writeRPMManifest(ctx context.Context, containerFSPath string) error { if matches != nil { pgpKeyID = matches[1] } else { - log.Debugf("string did not match the format required: %s", packageInfo.PGP) + log.L().Debugf("string did not match the format required: %s", packageInfo.PGP) pgpKeyID = "" } } @@ -582,7 +583,7 @@ func writeRPMManifest(ctx context.Context, containerFSPath string) error { return fmt.Errorf("failed to save file to artifacts directory: %w", err) } - log.Tracef("rpm manifest written to disk: %s", fileName) + log.L().Tracef("rpm manifest written to disk: %s", fileName) } return nil diff --git a/internal/lib/lib.go b/internal/lib/lib.go index 45724da6..6285852e 100644 --- a/internal/lib/lib.go +++ b/internal/lib/lib.go @@ -33,7 +33,7 @@ func GetContainerPolicyExceptions(ctx context.Context, pc PyxisClient) (policy.P if err != nil { return "", fmt.Errorf("could not retrieve project: %w", err) } - // log.Debugf("Certification project name is: %s", certProject.Name) + // log.L().Debugf("Certification project name is: %s", certProject.Name) if certProject.Container.Type == "scratch" { return policy.PolicyScratch, nil } diff --git a/internal/lib/logging.go b/internal/lib/logging.go index 9913f846..db79f4d4 100644 --- a/internal/lib/logging.go +++ b/internal/lib/logging.go @@ -5,28 +5,27 @@ import ( "context" "io" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) // LogThroughArtifactWriterIfSet reconfigures the logger used by Preflight to write to // the artifact writer if one is configured. If this is called and no Artifact Writer -// is configured, this forces calls to logrus.StandardLogger to be discarded. -// This is a workaround for the library implementation because existing checks -// make calls directly to logrus. +// is configured, this will set writes to the application's logger to be discarded. func LogThroughArtifactWriterIfSet(ctx context.Context) { if w := artifacts.WriterFromContext(ctx); w != nil { - log.SetLevel(log.TraceLevel) - log.SetFormatter(&log.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) b := bytes.NewBufferString("") - log.SetOutput(b) + log.L().SetOutput(b) w.WriteFile("preflight.log", b) //nolint:errcheck return } - log.SetOutput(io.Discard) + log.L().SetOutput(io.Discard) } type contextKey string diff --git a/internal/lib/logging_test.go b/internal/lib/logging_test.go index 6363010e..ba2a3bd1 100644 --- a/internal/lib/logging_test.go +++ b/internal/lib/logging_test.go @@ -6,9 +6,9 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - log "github.com/sirupsen/logrus" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var _ = Describe("Lib Logging Functions", func() { @@ -30,7 +30,7 @@ var _ = Describe("Lib Logging Functions", func() { LogThroughArtifactWriterIfSet(ctx) msg := "testing logs emitted through artifact writer" - log.Info(msg) + log.L().Info(msg) data, ok := w.Files()["preflight.log"] Expect(ok).To(BeTrue()) Expect(data).To(ContainSubstring(msg)) @@ -39,7 +39,7 @@ var _ = Describe("Lib Logging Functions", func() { It("Should be configured to discard logs if no artifact writer is configured", func() { ctx := context.Background() LogThroughArtifactWriterIfSet(ctx) - Expect(log.StandardLogger().Out).To(Equal(io.Discard)) + Expect(log.L().Out).To(Equal(io.Discard)) }) }) }) diff --git a/internal/lib/types.go b/internal/lib/types.go index 7b3c5d96..736389ed 100644 --- a/internal/lib/types.go +++ b/internal/lib/types.go @@ -11,13 +11,13 @@ import ( "path/filepath" "time" + "github.com/sirupsen/logrus" "github.com/spf13/viper" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/pyxis" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) // ResultWriter defines methods associated with writing check results. @@ -64,7 +64,7 @@ type ContainerCertificationSubmitter struct { } func (s *ContainerCertificationSubmitter) Submit(ctx context.Context) error { - log.Info("preparing results that will be submitted to Red Hat") + log.L().Info("preparing results that will be submitted to Red Hat") // get the project info from pyxis certProject, err := s.Pyxis.GetProject(ctx) @@ -80,7 +80,7 @@ func (s *ContainerCertificationSubmitter) Submit(ctx context.Context) error { return fmt.Errorf("no certification project was returned from pyxis") } - log.Tracef("CertProject: %+v", certProject) + log.L().Tracef("CertProject: %+v", certProject) // only read the dockerfile if the user provides a location for the file // at this point in the flow, if `cfg.DockerConfig` is empty we know the repo is public and can continue the submission flow @@ -184,11 +184,11 @@ func (s *ContainerCertificationSubmitter) Submit(ctx context.Context) error { return fmt.Errorf("could not submit to pyxis: %w", err) } - log.Info("Test results have been submitted to Red Hat.") - log.Info("These results will be reviewed by Red Hat for final certification.") - log.Infof("The container's image id is: %s.", certResults.CertImage.ID) - log.Infof("Please check %s to view scan results.", BuildScanResultsURL(s.CertificationProjectID, certResults.CertImage.ID)) - log.Infof("Please check %s to monitor the progress.", BuildOverviewURL(s.CertificationProjectID)) + log.L().Info("Test results have been submitted to Red Hat.") + log.L().Info("These results will be reviewed by Red Hat for final certification.") + log.L().Infof("The container's image id is: %s.", certResults.CertImage.ID) + log.L().Infof("Please check %s to view scan results.", BuildScanResultsURL(s.CertificationProjectID, certResults.CertImage.ID)) + log.L().Infof("Please check %s to monitor the progress.", BuildOverviewURL(s.CertificationProjectID)) return nil } @@ -198,10 +198,10 @@ func (s *ContainerCertificationSubmitter) Submit(ctx context.Context) error { type NoopSubmitter struct { emitLog bool reason string - log *log.Logger + log *logrus.Logger } -func NewNoopSubmitter(emitLog bool, log *log.Logger) *NoopSubmitter { +func NewNoopSubmitter(emitLog bool, log *logrus.Logger) *NoopSubmitter { return &NoopSubmitter{ emitLog: emitLog, log: log, diff --git a/internal/log/log.go b/internal/log/log.go new file mode 100644 index 00000000..453c63f0 --- /dev/null +++ b/internal/log/log.go @@ -0,0 +1,22 @@ +// Package log is a preflight-local logrus bridge, removing the +// dependency on logrus' global logger instance. +package log + +import ( + "github.com/sirupsen/logrus" +) + +var l *logrus.Logger + +// Logger returns the configured logger, or a new unconfigured logger +// if one has not already been configured. +func Logger() *logrus.Logger { + if l == nil { + l = logrus.New() + } + + return l +} + +// L is a convenience alias to Logger. +var L = Logger diff --git a/internal/log/log_test.go b/internal/log/log_test.go new file mode 100644 index 00000000..a94dcbae --- /dev/null +++ b/internal/log/log_test.go @@ -0,0 +1,16 @@ +package log + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/sirupsen/logrus" +) + +var _ = Describe("Internal Logrus Instance", func() { + When("Changing the configuration of the instance", func() { + L().SetFormatter(&logrus.JSONFormatter{}) + It("Should persist when called again", func() { + Expect(l.Formatter).To(BeEquivalentTo(&logrus.JSONFormatter{})) + }) + }) +}) diff --git a/internal/log/suite_test.go b/internal/log/suite_test.go new file mode 100644 index 00000000..c2a87cc4 --- /dev/null +++ b/internal/log/suite_test.go @@ -0,0 +1,13 @@ +package log + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestLib(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "log Suite") +} diff --git a/internal/openshift/openshift.go b/internal/openshift/openshift.go index 081f5f3f..6378d0ea 100644 --- a/internal/openshift/openshift.go +++ b/internal/openshift/openshift.go @@ -4,10 +4,11 @@ import ( "context" "fmt" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" + imagestreamv1 "github.com/openshift/api/image/v1" operatorsv1 "github.com/operator-framework/api/pkg/operators/v1" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" - log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -48,7 +49,7 @@ func AddSchemes(scheme *apiruntime.Scheme) error { // CreateNamespace can return an ErrAlreadyExists func (oe *openshiftClient) CreateNamespace(ctx context.Context, name string) (*corev1.Namespace, error) { - log.Tracef("Creating namespace: %q", name) + log.L().Tracef("Creating namespace: %q", name) nsSpec := corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -65,7 +66,7 @@ func (oe *openshiftClient) CreateNamespace(ctx context.Context, name string) (*c } func (oe *openshiftClient) DeleteNamespace(ctx context.Context, name string) error { - log.Tracef("Deleting namespace: %q", name) + log.L().Tracef("Deleting namespace: %q", name) nsSpec := corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -81,7 +82,7 @@ func (oe *openshiftClient) DeleteNamespace(ctx context.Context, name string) err // GetNamespace can return am ErrNotFound func (oe *openshiftClient) GetNamespace(ctx context.Context, name string) (*corev1.Namespace, error) { - log.Tracef("fetching namespace %q", name) + log.L().Tracef("fetching namespace %q", name) nsSpec := corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -102,7 +103,7 @@ func (oe *openshiftClient) GetNamespace(ctx context.Context, name string) (*core // CreateOperatorGroup can return an ErrAlreadyExists func (oe *openshiftClient) CreateOperatorGroup(ctx context.Context, data OperatorGroupData, namespace string) (*operatorsv1.OperatorGroup, error) { - log.Tracef("Creating OperatorGroup %q in namespace %q", data.Name, namespace) + log.L().Tracef("Creating OperatorGroup %q in namespace %q", data.Name, namespace) operatorGroup := &operatorsv1.OperatorGroup{ ObjectMeta: metav1.ObjectMeta{ Name: data.Name, @@ -124,7 +125,7 @@ func (oe *openshiftClient) CreateOperatorGroup(ctx context.Context, data Operato } func (oe *openshiftClient) DeleteOperatorGroup(ctx context.Context, name string, namespace string) error { - log.Tracef("Deleting OperatorGroup %q in namespace %q", name, namespace) + log.L().Tracef("Deleting OperatorGroup %q in namespace %q", name, namespace) operatorGroup := operatorsv1.OperatorGroup{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -141,7 +142,7 @@ func (oe *openshiftClient) DeleteOperatorGroup(ctx context.Context, name string, // GetOperatorGroup can return an ErrNotFound func (oe *openshiftClient) GetOperatorGroup(ctx context.Context, name string, namespace string) (*operatorsv1.OperatorGroup, error) { - log.Tracef("fetching operatorgroup %q from namespace %q", name, namespace) + log.L().Tracef("fetching operatorgroup %q from namespace %q", name, namespace) operatorGroup := operatorsv1.OperatorGroup{} err := oe.Client.Get(ctx, crclient.ObjectKey{ Name: name, @@ -158,7 +159,7 @@ func (oe *openshiftClient) GetOperatorGroup(ctx context.Context, name string, na // CreateSecret can return an ErrAlreadyExists func (oe openshiftClient) CreateSecret(ctx context.Context, name string, content map[string]string, secretType corev1.SecretType, namespace string) (*corev1.Secret, error) { - log.Tracef("Creating secret %q in namespace %q", name, namespace) + log.L().Tracef("Creating secret %q in namespace %q", name, namespace) secret := corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", @@ -183,7 +184,7 @@ func (oe openshiftClient) CreateSecret(ctx context.Context, name string, content } func (oe openshiftClient) DeleteSecret(ctx context.Context, name string, namespace string) error { - log.Tracef("Deleting secret %q from namespace %q", name, namespace) + log.L().Tracef("Deleting secret %q from namespace %q", name, namespace) secret := corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -200,7 +201,7 @@ func (oe openshiftClient) DeleteSecret(ctx context.Context, name string, namespa // GetSecret can return an ErrNotFound func (oe openshiftClient) GetSecret(ctx context.Context, name string, namespace string) (*corev1.Secret, error) { - log.Tracef("fetching secret %q from namespace %q", name, namespace) + log.L().Tracef("fetching secret %q from namespace %q", name, namespace) secret := corev1.Secret{} err := oe.Client.Get(ctx, crclient.ObjectKey{ Name: name, @@ -217,7 +218,7 @@ func (oe openshiftClient) GetSecret(ctx context.Context, name string, namespace // CreateCatalogSource can return an ErrAlreadyExists func (oe openshiftClient) CreateCatalogSource(ctx context.Context, data CatalogSourceData, namespace string) (*operatorsv1alpha1.CatalogSource, error) { - log.Tracef("Creating CatalogSource %q in namespace %q", data.Name, namespace) + log.L().Tracef("Creating CatalogSource %q in namespace %q", data.Name, namespace) catalogSource := &operatorsv1alpha1.CatalogSource{ ObjectMeta: metav1.ObjectMeta{ Name: data.Name, @@ -241,7 +242,7 @@ func (oe openshiftClient) CreateCatalogSource(ctx context.Context, data CatalogS } func (oe *openshiftClient) DeleteCatalogSource(ctx context.Context, name string, namespace string) error { - log.Tracef("Deleting CatalogSource %q in namespace %q", name, namespace) + log.L().Tracef("Deleting CatalogSource %q in namespace %q", name, namespace) catalogSource := operatorsv1alpha1.CatalogSource{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -257,7 +258,7 @@ func (oe *openshiftClient) DeleteCatalogSource(ctx context.Context, name string, // GetCatalogSource cat return an ErrNotFound func (oe *openshiftClient) GetCatalogSource(ctx context.Context, name string, namespace string) (*operatorsv1alpha1.CatalogSource, error) { - log.Tracef("fetching catalogsource: %q", name) + log.L().Tracef("fetching catalogsource: %q", name) catalogSource := &operatorsv1alpha1.CatalogSource{} err := oe.Client.Get(ctx, crclient.ObjectKey{ Name: name, @@ -274,7 +275,7 @@ func (oe *openshiftClient) GetCatalogSource(ctx context.Context, name string, na // CreateSubscription can return an ErrAlreadyExists func (oe openshiftClient) CreateSubscription(ctx context.Context, data SubscriptionData, namespace string) (*operatorsv1alpha1.Subscription, error) { - log.Tracef("Creating Subscription %q in namespace %q", data.Name, namespace) + log.L().Tracef("Creating Subscription %q in namespace %q", data.Name, namespace) subscription := &operatorsv1alpha1.Subscription{ ObjectMeta: metav1.ObjectMeta{ Name: data.Name, @@ -299,7 +300,7 @@ func (oe openshiftClient) CreateSubscription(ctx context.Context, data Subscript // GetSubscription can return an ErrNotFound func (oe *openshiftClient) GetSubscription(ctx context.Context, name string, namespace string) (*operatorsv1alpha1.Subscription, error) { - log.Tracef("fetching subscription %q from namespace %q", name, namespace) + log.L().Tracef("fetching subscription %q from namespace %q", name, namespace) subscription := &operatorsv1alpha1.Subscription{} err := oe.Client.Get(ctx, crclient.ObjectKey{ Name: name, @@ -315,7 +316,7 @@ func (oe *openshiftClient) GetSubscription(ctx context.Context, name string, nam } func (oe openshiftClient) DeleteSubscription(ctx context.Context, name string, namespace string) error { - log.Tracef("Deleting Subscription %q in namespace %q", name, namespace) + log.L().Tracef("Deleting Subscription %q in namespace %q", name, namespace) subscription := &operatorsv1alpha1.Subscription{ ObjectMeta: metav1.ObjectMeta{ @@ -332,7 +333,7 @@ func (oe openshiftClient) DeleteSubscription(ctx context.Context, name string, n // GetCSV can return an ErrNotFound func (oe *openshiftClient) GetCSV(ctx context.Context, name string, namespace string) (*operatorsv1alpha1.ClusterServiceVersion, error) { - log.Debugf("fetching csv %q from namespace %q", name, namespace) + log.L().Debugf("fetching csv %q from namespace %q", name, namespace) csv := &operatorsv1alpha1.ClusterServiceVersion{} err := oe.Client.Get(ctx, crclient.ObjectKey{ Name: name, @@ -378,7 +379,7 @@ func (oe *openshiftClient) GetImages(ctx context.Context) (map[string]struct{}, // CreateRoleBinding can return an ErrAlreadyExists func (oe *openshiftClient) CreateRoleBinding(ctx context.Context, data RoleBindingData, namespace string) (*rbacv1.RoleBinding, error) { - log.Tracef("Creating RoleBinding %q in namespace %q", data.Name, namespace) + log.L().Tracef("Creating RoleBinding %q in namespace %q", data.Name, namespace) subjectsObj := make([]rbacv1.Subject, 0, len(data.Subjects)) for _, subject := range data.Subjects { subjectsObj = append(subjectsObj, rbacv1.Subject{ @@ -412,13 +413,13 @@ func (oe *openshiftClient) CreateRoleBinding(ctx context.Context, data RoleBindi return nil, fmt.Errorf("could not create rolebinding: %s/%s: %v", namespace, data.Name, err) } - log.Debugf("RoleBinding %s created in namespace %s", data.Name, namespace) + log.L().Debugf("RoleBinding %s created in namespace %s", data.Name, namespace) return &roleBindingObj, nil } // GetRoleBinding can return an ErrNotFound func (oe *openshiftClient) GetRoleBinding(ctx context.Context, name string, namespace string) (*rbacv1.RoleBinding, error) { - log.Tracef("fetching RoleBinding %q from namespace %q", name, namespace) + log.L().Tracef("fetching RoleBinding %q from namespace %q", name, namespace) roleBinding := rbacv1.RoleBinding{ TypeMeta: metav1.TypeMeta{ Kind: "RoleBinding", @@ -443,7 +444,7 @@ func (oe *openshiftClient) GetRoleBinding(ctx context.Context, name string, name } func (oe *openshiftClient) DeleteRoleBinding(ctx context.Context, name string, namespace string) error { - log.Tracef("Deleting RoleBinding %q in namespace %q", name, namespace) + log.L().Tracef("Deleting RoleBinding %q in namespace %q", name, namespace) roleBinding := rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{ diff --git a/internal/openshift/openshift_version.go b/internal/openshift/openshift_version.go index c1ed993f..3c3caafb 100644 --- a/internal/openshift/openshift_version.go +++ b/internal/openshift/openshift_version.go @@ -5,9 +5,9 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/runtime" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" configv1Client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1" - log "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/clientcmd" ) @@ -31,7 +31,7 @@ func GetOpenshiftClusterVersion(kubeconfig []byte) (runtime.OpenshiftClusterVers return runtime.UnknownOpenshiftClusterVersion(), fmt.Errorf("unable to get openshift-apiserver cluster operator: %v", err) } - log.Debug(fmt.Sprintf("fetching operator version and openshift-apiserver version %s from %s", openshiftAPIServer.Status.Versions, restconfig.Host)) + log.L().Debug(fmt.Sprintf("fetching operator version and openshift-apiserver version %s from %s", openshiftAPIServer.Status.Versions, restconfig.Host)) return runtime.OpenshiftClusterVersion{ Name: "OpenShift", Version: openshiftAPIServer.Status.Versions[1].Version, diff --git a/internal/operatorsdk/operatorsdk.go b/internal/operatorsdk/operatorsdk.go index 493868cf..70ba1ddd 100644 --- a/internal/operatorsdk/operatorsdk.go +++ b/internal/operatorsdk/operatorsdk.go @@ -11,8 +11,7 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/runtime" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) func New(userProvidedScorecardImage string, cmdContext execContext) *operatorSdk { @@ -47,7 +46,7 @@ func (o operatorSdk) Scorecard(ctx context.Context, image string, opts OperatorS if err != nil { return nil, fmt.Errorf("unable to create a temporary kubeconfig file for use with scorecard: %s", err) } - log.Trace("created temporary kubeconfig for use with scorecard at path: ", kcf.Name()) + log.L().Trace("created temporary kubeconfig for use with scorecard at path: ", kcf.Name()) defer os.Remove(kcf.Name()) _, err = kcf.Write(opts.Kubeconfig) if err != nil { @@ -79,7 +78,7 @@ func (o operatorSdk) Scorecard(ctx context.Context, image string, opts OperatorS cmdArgs = append(cmdArgs, image) cmd := o.cmdContext("operator-sdk", cmdArgs...) - log.Trace("running scorecard with the following invocation", cmd.Args) + log.L().Trace("running scorecard with the following invocation", cmd.Args) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -93,8 +92,8 @@ func (o operatorSdk) Scorecard(ctx context.Context, image string, opts OperatorS // We also conclude/assume that "FATA" being in stderr would indicate an error in the // check execution itself. if stderr.Len() != 0 && strings.Contains(strings.ToUpper(stderr.String()), "FATA") { - log.Debug("operator-sdk scorecard failed to run properly.") - log.Debugf("stderr: %s", stderr.String()) + log.L().Debug("operator-sdk scorecard failed to run properly.") + log.L().Debugf("stderr: %s", stderr.String()) return nil, fmt.Errorf("failed to run operator-sdk scorecard: %v", err) } @@ -139,7 +138,7 @@ func (o operatorSdk) BundleValidate(ctx context.Context, image string, opts Oper cmdArgs = append(cmdArgs, image) cmd := o.cmdContext("operator-sdk", cmdArgs...) - log.Debugf("Command being run: %s", cmd.Args) + log.L().Debugf("Command being run: %s", cmd.Args) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -153,8 +152,8 @@ func (o operatorSdk) BundleValidate(ctx context.Context, image string, opts Oper // We also conclude/assume that "FATA" being in stderr would indicate an error in the // check execution itself. if stderr.Len() != 0 && strings.Contains(stderr.String(), "FATA") { - log.Debugf("stdout: %s", stdout.String()) - log.Debugf("stderr: %s", stderr.String()) + log.L().Debugf("stdout: %s", stdout.String()) + log.L().Debugf("stderr: %s", stderr.String()) return nil, fmt.Errorf("failed to run operator-sdk bundle validate: %v", err) } } diff --git a/internal/operatorsdk/operatorsdk_suite_test.go b/internal/operatorsdk/operatorsdk_suite_test.go index 1f8d7d5b..827fd510 100644 --- a/internal/operatorsdk/operatorsdk_suite_test.go +++ b/internal/operatorsdk/operatorsdk_suite_test.go @@ -6,7 +6,9 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" + + "github.com/sirupsen/logrus" ) func TestOperatorSdk(t *testing.T) { @@ -15,6 +17,6 @@ func TestOperatorSdk(t *testing.T) { } func init() { - log.SetFormatter(&log.TextFormatter{}) - log.SetLevel(log.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) } diff --git a/internal/policy/container/container_suite_test.go b/internal/policy/container/container_suite_test.go index 0a3772dd..6a12d2e4 100644 --- a/internal/policy/container/container_suite_test.go +++ b/internal/policy/container/container_suite_test.go @@ -5,12 +5,13 @@ import ( "testing" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - log "github.com/sirupsen/logrus" + logrus "github.com/sirupsen/logrus" ) func TestContainer(t *testing.T) { @@ -19,8 +20,8 @@ func TestContainer(t *testing.T) { } func init() { - log.SetFormatter(&log.TextFormatter{}) - log.SetLevel(log.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) } type FakeLayer struct{} diff --git a/internal/policy/container/has_license.go b/internal/policy/container/has_license.go index 3ecdb65c..af6f3614 100644 --- a/internal/policy/container/has_license.go +++ b/internal/policy/container/has_license.go @@ -9,8 +9,7 @@ import ( "path/filepath" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) const ( @@ -68,7 +67,7 @@ func (p *HasLicenseCheck) validate(ctx context.Context, licenseFileList []fs.Dir break } } - log.Debugf("%d Licenses found", len(licenseFileList)) + log.L().Debugf("%d Licenses found", len(licenseFileList)) return len(licenseFileList) >= minLicenseFileCount && nonZeroLength, nil } diff --git a/internal/policy/container/has_modified_files.go b/internal/policy/container/has_modified_files.go index af806527..d5195e78 100644 --- a/internal/policy/container/has_modified_files.go +++ b/internal/policy/container/has_modified_files.go @@ -9,10 +9,10 @@ import ( "sync" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/rpm" rpmdb "github.com/knqyf263/go-rpmdb/pkg" - log "github.com/sirupsen/logrus" ) var _ certification.Check = &HasModifiedFilesCheck{} @@ -98,7 +98,7 @@ func (p *HasModifiedFilesCheck) getDataToValidate(ctx context.Context, imgRef ce // tell the user the first layer was dropped diff0, _ := layers[0].DiffID() diff1, _ := layers[1].DiffID() - log.Debugf( + log.L().Debugf( "The first layer (%s) contained no files, so the next layer (%s) is being used as the base layer.", diff0.String(), diff1.String(), @@ -146,7 +146,7 @@ func (p *HasModifiedFilesCheck) validate(packageFilesRef *packageFilesRef) (bool for _, file := range layer { if _, ok := baseLayer[file]; ok { // This means the files exists in the base layer. This is a fail. - log.Debugf("modified file detected: %s", file) + log.L().Debugf("modified file detected: %s", file) modifiedFilesDetected = true } } diff --git a/internal/policy/container/has_prohibited_packages.go b/internal/policy/container/has_prohibited_packages.go index b6e44e02..c64743f9 100644 --- a/internal/policy/container/has_prohibited_packages.go +++ b/internal/policy/container/has_prohibited_packages.go @@ -6,9 +6,8 @@ import ( "strings" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/rpm" - - log "github.com/sirupsen/logrus" ) var _ certification.Check = &HasNoProhibitedPackagesCheck{} @@ -56,8 +55,8 @@ func (p *HasNoProhibitedPackagesCheck) validate(ctx context.Context, pkgList []s } if len(prohibitedPackages) > 0 { - log.Debugf("The number of prohibited package found in the container image: %d", len(prohibitedPackages)) - log.Debugf("found the following prohibited packages: %+v", prohibitedPackages) + log.L().Debugf("The number of prohibited package found in the container image: %d", len(prohibitedPackages)) + log.L().Debugf("found the following prohibited packages: %+v", prohibitedPackages) } return len(prohibitedPackages) == 0, nil diff --git a/internal/policy/container/has_required_labels.go b/internal/policy/container/has_required_labels.go index 9a7de16c..a7c3c3d8 100644 --- a/internal/policy/container/has_required_labels.go +++ b/internal/policy/container/has_required_labels.go @@ -5,9 +5,9 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" cranev1 "github.com/google/go-containerregistry/pkg/v1" - log "github.com/sirupsen/logrus" ) var requiredLabels = []string{"name", "vendor", "version", "release", "summary", "description"} @@ -42,7 +42,7 @@ func (p *HasRequiredLabelsCheck) validate(labels map[string]string) (bool, error // TODO: We should be reporting this in the results, not in a log message if len(missingLabels) > 0 { - log.Debugf("expected labels are missing: %+v", missingLabels) + log.L().Debugf("expected labels are missing: %+v", missingLabels) } return len(missingLabels) == 0, nil diff --git a/internal/policy/container/max_layers.go b/internal/policy/container/max_layers.go index f0ed2468..bd19aedc 100644 --- a/internal/policy/container/max_layers.go +++ b/internal/policy/container/max_layers.go @@ -5,9 +5,9 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" cranev1 "github.com/google/go-containerregistry/pkg/v1" - log "github.com/sirupsen/logrus" ) const ( @@ -33,7 +33,7 @@ func (p *MaxLayersCheck) getDataToValidate(image cranev1.Image) ([]cranev1.Layer } func (p *MaxLayersCheck) validate(layers []cranev1.Layer) (bool, error) { - log.Debugf("detected %d layers in image", len(layers)) + log.L().Debugf("detected %d layers in image", len(layers)) return len(layers) <= acceptableLayerMax, nil } diff --git a/internal/policy/container/runs_as_nonroot.go b/internal/policy/container/runs_as_nonroot.go index f61c7e51..1d590e94 100644 --- a/internal/policy/container/runs_as_nonroot.go +++ b/internal/policy/container/runs_as_nonroot.go @@ -5,9 +5,9 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" cranev1 "github.com/google/go-containerregistry/pkg/v1" - log "github.com/sirupsen/logrus" ) var _ certification.Check = &RunAsNonRootCheck{} @@ -35,18 +35,18 @@ func (p *RunAsNonRootCheck) getDataToValidate(image cranev1.Image) (string, erro func (p *RunAsNonRootCheck) validate(user string) (bool, error) { if user == "" { - log.Info("detected empty USER. Presumed to be running as root") - log.Info("USER value must be provided and be a non-root value for this check to pass") + log.L().Info("detected empty USER. Presumed to be running as root") + log.L().Info("USER value must be provided and be a non-root value for this check to pass") return false, nil } if user == "0" || user == "root" { - log.Infof("detected USER specified as root: %s", user) - log.Info("USER other than root is required for this check to pass") + log.L().Infof("detected USER specified as root: %s", user) + log.L().Info("USER other than root is required for this check to pass") return false, nil } - log.Infof("USER %s specified that is non-root", user) + log.L().Infof("USER %s specified that is non-root", user) return true, nil } diff --git a/internal/policy/operator/certified_images.go b/internal/policy/operator/certified_images.go index dbf8cfaf..9c9da22c 100644 --- a/internal/policy/operator/certified_images.go +++ b/internal/policy/operator/certified_images.go @@ -7,11 +7,11 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/pyxis" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/google/go-containerregistry/pkg/name" "github.com/operator-framework/operator-manifest-tools/pkg/image" "github.com/operator-framework/operator-manifest-tools/pkg/pullspec" - log "github.com/sirupsen/logrus" ) var _ certification.Check = &certifiedImagesCheck{} @@ -60,7 +60,7 @@ func (p *certifiedImagesCheck) dataToValidate(ctx context.Context, imagePath str for _, img := range imageNames { digest, err := name.NewDigest(img) if err != nil { - log.Warningf("Image does not appear to be pinned: %s: %v", img, err) + log.L().Warningf("Image does not appear to be pinned: %s: %v", img, err) p.nonCertifiedImages = append(p.nonCertifiedImages, img) continue } @@ -84,13 +84,13 @@ func (p *certifiedImagesCheck) validate(ctx context.Context, imageDigests []stri for _, digest := range imageDigests { img, ok := foundMap[digest] if !ok { - log.Warningf("Image not found in Pyxis, therefore it is not certified: %s", digest) + log.L().Warningf("Image not found in Pyxis, therefore it is not certified: %s", digest) p.nonCertifiedImages = append(p.nonCertifiedImages, digest) continue } if !img.Certified { fullImg := fmt.Sprintf("%s/%s@%s", img.Repositories[0].Registry, img.Repositories[0].Repository, img.DockerImageDigest) - log.Warningf("Image is not certified: %s", fullImg) + log.L().Warningf("Image is not certified: %s", fullImg) p.nonCertifiedImages = append(p.nonCertifiedImages, fullImg) } } diff --git a/internal/policy/operator/deployable_by_olm.go b/internal/policy/operator/deployable_by_olm.go index f911d50f..e9089eda 100644 --- a/internal/policy/operator/deployable_by_olm.go +++ b/internal/policy/operator/deployable_by_olm.go @@ -15,12 +15,12 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification/artifacts" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/bundle" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/openshift" "github.com/operator-framework/api/pkg/manifests" operatorsv1 "github.com/operator-framework/api/pkg/operators/v1" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" - log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" apiruntime "k8s.io/apimachinery/pkg/runtime" @@ -128,7 +128,7 @@ func (p *DeployableByOlmCheck) Validate(ctx context.Context, bundleRef certifica return false, fmt.Errorf("%v", err) } - log.Debugf("The operator Metadata is %+v", *operatorData) + log.L().Debugf("The operator Metadata is %+v", *operatorData) // create k8s custom resources for the operator deployment err = p.setUp(ctx, operatorData) @@ -143,7 +143,7 @@ func (p *DeployableByOlmCheck) Validate(ctx context.Context, bundleRef certifica return false, fmt.Errorf("%v", err) } operatorData.InstalledCsv = installedCSV - log.Trace("the installed CSV is ", operatorData.InstalledCsv) + log.L().Trace("the installed CSV is ", operatorData.InstalledCsv) p.csvReady, err = p.isCSVReady(ctx, *operatorData) if err != nil { @@ -172,24 +172,24 @@ func diffImageList(before, after map[string]struct{}) []string { } func checkImageSource(operatorImages []string) bool { - log.Debug("Checking that images are from approved sources...") + log.L().Debug("Checking that images are from approved sources...") registries := make([]string, 0, len(approvedRegistries)) for registry := range approvedRegistries { registries = append(registries, registry) } - log.Debug("List of approved registries are: ", registries) + log.L().Debug("List of approved registries are: ", registries) allApproved := true for _, image := range operatorImages { userRegistry := strings.Split(image, "/")[0] if _, ok := approvedRegistries[userRegistry]; !ok { - log.Warnf("Unapproved registry found for image %s", image) + log.L().Warnf("Unapproved registry found for image %s", image) allApproved = false } } if allApproved { - log.Debug("All images are from approved sources...") + log.L().Debug("All images are from approved sources...") } return allApproved } @@ -267,7 +267,7 @@ func (p *DeployableByOlmCheck) setUp(ctx context.Context, operatorData *operator return err } } else { - log.Debug("No docker config file is found to access the index image in private registries. Proceeding...") + log.L().Debug("No docker config file is found to access the index image in private registries. Proceeding...") } if strings.Contains(operatorData.CatalogImage, imageRegistryService) { @@ -349,7 +349,7 @@ func (p *DeployableByOlmCheck) generateOperatorGroupData(operatorData *operatorD installMode = operatorData.InstallModes[v].Type } } - log.Debugf("The operator install mode is %s", installMode) + log.L().Debugf("The operator install mode is %s", installMode) targetNamespaces := make([]string, 2) switch installMode { @@ -362,7 +362,7 @@ func (p *DeployableByOlmCheck) generateOperatorGroupData(operatorData *operatorD case operatorsv1alpha1.InstallModeTypeAllNamespaces: targetNamespaces = []string{} } - log.Debugf("The OperatorGroup's TargetNamespaces is %s", targetNamespaces) + log.L().Debugf("The OperatorGroup's TargetNamespaces is %s", targetNamespaces) operatorData.CsvNamespaces = targetNamespaces return openshift.OperatorGroupData{Name: operatorData.App, TargetNamespaces: targetNamespaces} } @@ -395,7 +395,7 @@ func watch(ctx context.Context, client openshift.Client, wg *sync.WaitGroup, nam defer cancel() for { - log.Debugf("watch: Waiting for object %s/%s to become ready...", namespace, name) + log.L().Debugf("watch: Waiting for object %s/%s to become ready...", namespace, name) obj, done, err := fn(ctx, client, name, namespace) if err != nil { // Something bad happened. Get out of town @@ -404,11 +404,11 @@ func watch(ctx context.Context, client openshift.Client, wg *sync.WaitGroup, nam return } if done { - log.Debugf("watch: Successfully retrieved object %s/%s", namespace, obj) + log.L().Debugf("watch: Successfully retrieved object %s/%s", namespace, obj) channel <- obj return } - log.Debugf("watch: Object %s/%s is not set yet, retrying...", namespace, name) + log.L().Debugf("watch: Object %s/%s is not set yet, retrying...", namespace, name) select { case <-ctx.Done(): @@ -428,7 +428,7 @@ func csvStatusSucceeded(ctx context.Context, client openshift.Client, name, name } // if the CSV phase is succeeded, stop the querying if csv != nil && csv.Status.Phase == operatorsv1alpha1.CSVPhaseSucceeded { - log.Debugf("CSV %s is created successfully in namespace %s", name, namespace) + log.L().Debugf("CSV %s is created successfully in namespace %s", name, namespace) return name, true, nil } return "", false, nil @@ -441,7 +441,7 @@ func (p *DeployableByOlmCheck) isCSVReady(ctx context.Context, operatorData oper } else { CsvNamespaces = []string{operatorData.CsvNamespaces[0]} } - log.Tracef("Looking for csv %s in namespace(s) %s", operatorData.InstalledCsv, CsvNamespaces) + log.L().Tracef("Looking for csv %s in namespace(s) %s", operatorData.InstalledCsv, CsvNamespaces) csvChannel := make(chan string) @@ -473,7 +473,7 @@ func subscriptionCsvIsInstalled(ctx context.Context, client openshift.Client, na if err != nil && !errors.Is(err, openshift.ErrNotFound) { return "", false, fmt.Errorf("failed to fetch the subscription %s from namespace %s: %w", name, namespace, err) } - log.Tracef("current subscription status is %+v", sub.Status) + log.L().Tracef("current subscription status is %+v", sub.Status) installedCSV := sub.Status.InstalledCSV // if the installedCSV field is present, stop the querying if len(installedCSV) > 0 { @@ -507,55 +507,55 @@ func (p *DeployableByOlmCheck) installedCSV(ctx context.Context, operatorData op } func (p *DeployableByOlmCheck) cleanUp(ctx context.Context, operatorData operatorData) { - log.Debug("Dumping data in artifacts/ directory") + log.L().Debug("Dumping data in artifacts/ directory") subs, err := p.openshiftClient.GetSubscription(ctx, operatorData.App, operatorData.InstallNamespace) if err != nil { - log.Warn("unable to retrieve the subscription") + log.L().Warn("unable to retrieve the subscription") } else { err := p.writeToFile(ctx, subs) if err != nil { - log.Errorf("could not write subscription to storage") + log.L().Errorf("could not write subscription to storage") } } cs, err := p.openshiftClient.GetCatalogSource(ctx, operatorData.App, operatorData.InstallNamespace) if err != nil { - log.Warn("unable to retrieve the catalogsource") + log.L().Warn("unable to retrieve the catalogsource") } else { if err := p.writeToFile(ctx, cs); err != nil { - log.Errorf("could not write catalogsource to storage") + log.L().Errorf("could not write catalogsource to storage") } } og, err := p.openshiftClient.GetOperatorGroup(ctx, operatorData.App, operatorData.InstallNamespace) if err != nil { - log.Warn("unable to retrieve the operatorgroup") + log.L().Warn("unable to retrieve the operatorgroup") } else { if err := p.writeToFile(ctx, og); err != nil { - log.Errorf("could not write operatorgroup to storage") + log.L().Errorf("could not write operatorgroup to storage") } } installNamespace, err := p.openshiftClient.GetNamespace(ctx, operatorData.InstallNamespace) if err != nil { - log.Warn("unable to retrieve the install namespace") + log.L().Warn("unable to retrieve the install namespace") } else { if err := p.writeToFile(ctx, installNamespace); err != nil { - log.Errorf("could not write install namespace to storage") + log.L().Errorf("could not write install namespace to storage") } } targetNamespace, err := p.openshiftClient.GetNamespace(ctx, operatorData.TargetNamespace) if err != nil { - log.Warn("unable to retrieve the target namespace") + log.L().Warn("unable to retrieve the target namespace") } else { if err := p.writeToFile(ctx, targetNamespace); err != nil { - log.Errorf("could not write target namespace to storage") + log.L().Errorf("could not write target namespace to storage") } } - log.Trace("Deleting the resources created by DeployableByOLM Check") + log.L().Trace("Deleting the resources created by DeployableByOLM Check") _ = p.openshiftClient.DeleteSubscription(ctx, operatorData.App, operatorData.InstallNamespace) _ = p.openshiftClient.DeleteCatalogSource(ctx, operatorData.App, operatorData.InstallNamespace) _ = p.openshiftClient.DeleteOperatorGroup(ctx, operatorData.App, operatorData.InstallNamespace) diff --git a/internal/policy/operator/operator_suite_test.go b/internal/policy/operator/operator_suite_test.go index 03a0e037..8d8dab29 100644 --- a/internal/policy/operator/operator_suite_test.go +++ b/internal/policy/operator/operator_suite_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/operatorsdk" . "github.com/onsi/ginkgo/v2" @@ -13,7 +14,8 @@ import ( imagestreamv1 "github.com/openshift/api/image/v1" operatorsv1 "github.com/operator-framework/api/pkg/operators/v1" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -24,8 +26,8 @@ func TestOperator(t *testing.T) { } func init() { - log.SetFormatter(&log.TextFormatter{}) - log.SetLevel(log.TraceLevel) + log.L().SetFormatter(&logrus.TextFormatter{}) + log.L().SetLevel(logrus.TraceLevel) } type FakeOperatorSdk struct { diff --git a/internal/policy/operator/related_images.go b/internal/policy/operator/related_images.go index 2f78e9c0..6d3347ac 100644 --- a/internal/policy/operator/related_images.go +++ b/internal/policy/operator/related_images.go @@ -6,11 +6,11 @@ import ( "path/filepath" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" "github.com/operator-framework/operator-manifest-tools/pkg/image" "github.com/operator-framework/operator-manifest-tools/pkg/pullspec" - log "github.com/sirupsen/logrus" "sigs.k8s.io/yaml" ) @@ -66,7 +66,7 @@ func (p *RelatedImagesCheck) dataToValidate(ctx context.Context, imagePath strin func (p *RelatedImagesCheck) validate(ctx context.Context, images []string, relatedImages map[string]struct{}) (bool, error) { for _, image := range images { if _, ok := relatedImages[image]; !ok { - log.Warningf("Image %s is not in relatedImages. This will eventually cause this check to fail", image) + log.L().Warningf("Image %s is not in relatedImages. This will eventually cause this check to fail", image) } } return true, nil diff --git a/internal/policy/operator/scc_info.go b/internal/policy/operator/scc_info.go index ef6a47f7..e77efe94 100644 --- a/internal/policy/operator/scc_info.go +++ b/internal/policy/operator/scc_info.go @@ -6,8 +6,7 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/bundle" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var _ certification.Check = &securityContextConstraintsInCSV{} @@ -45,7 +44,7 @@ func (p *securityContextConstraintsInCSV) dataToValidate(ctx context.Context, im //nolint:unparam // ctx is unused. Keep for future use. func (p *securityContextConstraintsInCSV) validate(ctx context.Context, requestedSccList []string) (bool, error) { if len(requestedSccList) == 0 { - log.Infof("No custom security context constraint was detected in the CSV. The default restricted SCC will be used.") + log.L().Infof("No custom security context constraint was detected in the CSV. The default restricted SCC will be used.") return true, nil } @@ -53,7 +52,7 @@ func (p *securityContextConstraintsInCSV) validate(ctx context.Context, requeste return false, fmt.Errorf("only one scc should be requested at a time") } - log.Infof("A custom scc was specified: %s , action may be needed by a cluster admin, please check the "+ + log.L().Infof("A custom scc was specified: %s , action may be needed by a cluster admin, please check the "+ "operator documentation for more information", requestedSccList[0]) // set bool to change help text p.customSCCSpecified = true diff --git a/internal/policy/operator/scorecard_basic_check_spec.go b/internal/policy/operator/scorecard_basic_check_spec.go index 501b14fa..9b5221aa 100644 --- a/internal/policy/operator/scorecard_basic_check_spec.go +++ b/internal/policy/operator/scorecard_basic_check_spec.go @@ -5,8 +5,7 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var _ certification.Check = &ScorecardBasicSpecCheck{} @@ -34,9 +33,9 @@ func NewScorecardBasicSpecCheck(operatorSdk operatorSdk, ns, sa string, kubeconf } func (p *ScorecardBasicSpecCheck) Validate(ctx context.Context, bundleRef certification.ImageReference) (bool, error) { - log.Trace("Running operator-sdk scorecard check for ", bundleRef.ImageURI) + log.L().Trace("Running operator-sdk scorecard check for ", bundleRef.ImageURI) selector := []string{"test=basic-check-spec-test"} - log.Tracef("--selector=%s", selector) + log.L().Tracef("--selector=%s", selector) scorecardReport, err := p.getDataToValidate(ctx, bundleRef.ImageFSPath, selector, scorecardBasicCheckResult) if err != nil { p.fatalError = true diff --git a/internal/policy/operator/scorecard_check.go b/internal/policy/operator/scorecard_check.go index 428bb91a..9726ab69 100644 --- a/internal/policy/operator/scorecard_check.go +++ b/internal/policy/operator/scorecard_check.go @@ -5,9 +5,8 @@ import ( "fmt" "strings" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/operatorsdk" - - log "github.com/sirupsen/logrus" ) type scorecardCheck struct { @@ -25,7 +24,7 @@ func (p *scorecardCheck) validate(ctx context.Context, items []operatorsdk.Opera var err error if len(items) == 0 { - log.Warn("Did not receive any test result information from scorecard output") + log.L().Warn("Did not receive any test result information from scorecard output") } for _, item := range items { for _, result := range item.Status.Results { diff --git a/internal/policy/operator/scorecard_olm_suite.go b/internal/policy/operator/scorecard_olm_suite.go index 997f85e4..36bce402 100644 --- a/internal/policy/operator/scorecard_olm_suite.go +++ b/internal/policy/operator/scorecard_olm_suite.go @@ -5,8 +5,7 @@ import ( "fmt" "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" - - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var _ certification.Check = &ScorecardOlmSuiteCheck{} @@ -34,9 +33,9 @@ func NewScorecardOlmSuiteCheck(operatorSdk operatorSdk, ns, sa string, kubeconfi } func (p *ScorecardOlmSuiteCheck) Validate(ctx context.Context, bundleRef certification.ImageReference) (bool, error) { - log.Trace("Running operator-sdk scorecard Check for ", bundleRef.ImageURI) + log.L().Trace("Running operator-sdk scorecard Check for ", bundleRef.ImageURI) selector := []string{"suite=olm"} - log.Tracef("--selector=%s", selector) + log.L().Tracef("--selector=%s", selector) scorecardReport, err := p.getDataToValidate(ctx, bundleRef.ImageFSPath, selector, scorecardOlmSuiteResult) if err != nil { p.fatalError = true diff --git a/internal/policy/operator/validate_operator_bundle.go b/internal/policy/operator/validate_operator_bundle.go index f905398e..a748faea 100644 --- a/internal/policy/operator/validate_operator_bundle.go +++ b/internal/policy/operator/validate_operator_bundle.go @@ -7,7 +7,7 @@ import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/certification" "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/bundle" - log "github.com/sirupsen/logrus" + "github.com/redhat-openshift-ecosystem/openshift-preflight/internal/log" ) var _ certification.Check = &ValidateOperatorBundleCheck{} @@ -37,10 +37,10 @@ func (p *ValidateOperatorBundleCheck) validate(ctx context.Context, report *bund if !report.Passed || len(report.Results) > 0 { for _, output := range report.Results { for _, result := range output.Errors { - log.Error(result.Error()) + log.L().Error(result.Error()) } for _, result := range output.Warnings { - log.Warn(result.Error()) + log.L().Warn(result.Error()) } } }