Skip to content

Commit

Permalink
logging - migrate the whole code to LogI, LogD, LogE functions
Browse files Browse the repository at this point in the history
Change-Id: Iec310acdd50f805e03b6291ea1c2bc3771563a9f
  • Loading branch information
morucci committed Jun 11, 2024
1 parent 3840f7d commit fce0e5b
Show file tree
Hide file tree
Showing 13 changed files with 123 additions and 121 deletions.
76 changes: 31 additions & 45 deletions cli/cmd/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import (
opv1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
sfv1 "github.com/softwarefactory-project/sf-operator/api/v1"
controllers "github.com/softwarefactory-project/sf-operator/controllers"
ctrlutils "github.com/softwarefactory-project/sf-operator/controllers/libs/utils"

"k8s.io/client-go/kubernetes"
)
Expand Down Expand Up @@ -137,21 +138,6 @@ func SetLogger(command *cobra.Command) {
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
}

// logI logs a message with the INFO log Level
func logI(msg string) {
ctrl.Log.Info(msg)
}

// logI logs a message with the DEBUG log Level
func logD(msg string) {
ctrl.Log.V(1).Info(msg)
}

// logI logs a message with the Error log Level
func logE(err error, msg string) {
ctrl.Log.Error(err, msg)
}

func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error) {

// This is usually called for every CLI command so here let's set the Logger settings
Expand All @@ -164,10 +150,10 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
if configPath != "" {
ctxName, cliContext, err = getContextFromFile(command)
if err != nil {
logE(err, "Could not load config file")
ctrlutils.LogE(err, "Could not load config file")
os.Exit(1)
} else {
logD("Using configuration context " + ctxName)
ctrlutils.LogD("Using configuration context " + ctxName)
}
}
// Override with defaults
Expand All @@ -190,12 +176,12 @@ func GetCLIContext(command *cobra.Command) (SoftwareFactoryConfigContext, error)
if cliContext.Dev.SFOperatorRepositoryPath == "" {
defaultSFOperatorRepositoryPath, getwdErr := os.Getwd()
if getwdErr != nil {
logE(getwdErr,
ctrlutils.LogE(getwdErr,
"sf-operator-repository-path is not set in `dev` section of the configuration file and unable to determine the current working directory")
os.Exit(1)
}
cliContext.Dev.SFOperatorRepositoryPath = defaultSFOperatorRepositoryPath
logD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
ctrlutils.LogD("Using current working directory for sf-operator-repository-path: " + cliContext.Dev.SFOperatorRepositoryPath)
}
return cliContext, nil
}
Expand Down Expand Up @@ -239,7 +225,7 @@ func CreateKubernetesClient(contextName string) (client.Client, error) {
func CreateKubernetesClientOrDie(contextName string) client.Client {
cli, err := CreateKubernetesClient(contextName)
if err != nil {
ctrl.Log.Error(err, "Error creating Kubernetes client")
ctrlutils.LogE(err, "Error creating Kubernetes client")
os.Exit(1)
}
return cli
Expand All @@ -249,7 +235,7 @@ func GetCLIENV(kmd *cobra.Command) (string, ENV) {

cliCtx, err := GetCLIContext(kmd)
if err != nil {
ctrl.Log.Error(err, "Error initializing CLI:")
ctrlutils.LogE(err, "Error initializing CLI:")
os.Exit(1)
}

Expand Down Expand Up @@ -283,7 +269,7 @@ func DeleteOrDie(env *ENV, obj client.Object, opts ...client.DeleteOption) bool
return false
} else if err != nil {
msg := fmt.Sprintf("Error while deleting %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
ctrl.Log.Error(err, msg)
ctrlutils.LogE(err, msg)
os.Exit(1)
}
return true
Expand All @@ -295,49 +281,49 @@ func GetMOrDie(env *ENV, name string, obj client.Object) bool {
return false
} else if err != nil {
msg := fmt.Sprintf("Error while fetching %s \"%s\"", reflect.TypeOf(obj).Name(), name)
ctrl.Log.Error(err, msg)
ctrlutils.LogE(err, msg)
os.Exit(1)
}
return true
}

func UpdateROrDie(env *ENV, obj client.Object) {
var msg = fmt.Sprintf("Updating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
ctrl.Log.Info(msg)
ctrlutils.LogI(msg)
if err := env.Cli.Update(env.Ctx, obj); err != nil {
msg = fmt.Sprintf("Error while updating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
ctrl.Log.Error(err, msg)
ctrlutils.LogE(err, msg)
os.Exit(1)
}
msg = fmt.Sprintf("%s \"%s\" updated", reflect.TypeOf(obj).Name(), obj.GetName())
ctrl.Log.Info(msg)
ctrlutils.LogI(msg)
}

func CreateROrDie(env *ENV, obj client.Object) {
var msg = fmt.Sprintf("Creating %s \"%s\" in %s", reflect.TypeOf(obj).Name(), obj.GetName(), env.Ns)
ctrl.Log.Info(msg)
ctrlutils.LogI(msg)
obj.SetNamespace(env.Ns)
if err := env.Cli.Create(env.Ctx, obj); err != nil {
msg = fmt.Sprintf("Error while creating %s \"%s\"", reflect.TypeOf(obj).Name(), obj.GetName())
ctrl.Log.Error(err, msg)
ctrlutils.LogE(err, msg)
os.Exit(1)
}
msg = fmt.Sprintf("%s \"%s\" created", reflect.TypeOf(obj).Name(), obj.GetName())
ctrl.Log.Info(msg)
ctrlutils.LogI(msg)
}

func DeleteAllOfOrDie(env *ENV, obj client.Object, opts ...client.DeleteAllOfOption) {
if err := env.Cli.DeleteAllOf(env.Ctx, obj, opts...); err != nil {
var msg = "Error while deleting"
ctrl.Log.Error(err, msg)
ctrlutils.LogE(err, msg)
os.Exit(1)
}
}

func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) SoftwareFactoryConfigContext {
cliCtx, err := GetCLIContext(kmd)
if err != nil {
ctrl.Log.Error(err, "Error initializing:")
ctrlutils.LogE(err, "Error initializing:")
os.Exit(1)
}
if len(allowedArgs) == 0 {
Expand All @@ -346,15 +332,15 @@ func GetCLIctxOrDie(kmd *cobra.Command, args []string, allowedArgs []string) Sof
} else {
argumentError := errors.New("argument must be in: " + strings.Join(allowedArgs, ", "))
if len(args) != 1 {
ctrl.Log.Error(argumentError, "Need one argument")
ctrlutils.LogE(argumentError, "Need one argument")
os.Exit(1)
}
for _, a := range allowedArgs {
if args[0] == a {
return cliCtx
}
}
ctrl.Log.Error(argumentError, "Unknown argument "+args[0])
ctrlutils.LogE(argumentError, "Unknown argument "+args[0])
os.Exit(1)
}
return SoftwareFactoryConfigContext{}
Expand All @@ -380,8 +366,8 @@ func RunCmdWithEnvOrDie(environ []string, cmd string, args ...string) string {
kmd.Env = append(os.Environ(), environ...)
out, err := kmd.CombinedOutput()
if err != nil {
logE(err, "Could not run command '"+cmd+"'")
logI("Captured output:\n" + string(out))
ctrlutils.LogE(err, "Could not run command '"+cmd+"'")
ctrlutils.LogI("Captured output:\n" + string(out))
os.Exit(1)
}
return string(out)
Expand All @@ -397,7 +383,7 @@ func EnsureNamespaceOrDie(env *ENV, name string) {
ns.Name = name
CreateROrDie(env, &ns)
} else if err != nil {
ctrl.Log.Error(err, "Error checking namespace "+name)
ctrlutils.LogE(err, "Error checking namespace "+name)
os.Exit(1)
}
}
Expand All @@ -412,7 +398,7 @@ func EnsureServiceAccountOrDie(env *ENV, name string) {
func WriteContentToFile(filePath string, content []byte, mode fs.FileMode) {
err := os.WriteFile(filePath, content, mode)
if err != nil {
ctrl.Log.Error(err, "Can not write a file "+filePath)
ctrlutils.LogE(err, "Can not write a file "+filePath)
os.Exit(1)
}
}
Expand All @@ -425,7 +411,7 @@ func VarListToMap(varsList []string) map[string]string {
tokens := strings.Split(v, "=")

if len(tokens) != 2 {
ctrl.Log.Error(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
ctrlutils.LogE(errors.New("parse error"), "parsed value `"+v+"` needs to be defined as 'foo=bar'")
os.Exit(1)
}
vars[tokens[0]] = tokens[1]
Expand All @@ -436,7 +422,7 @@ func VarListToMap(varsList []string) map[string]string {
func CreateDirectory(dirPath string, mode fs.FileMode) {
err := os.MkdirAll(dirPath, mode)
if err != nil {
ctrl.Log.Error(err, "Can not create directory "+dirPath)
ctrlutils.LogE(err, "Can not create directory "+dirPath)
os.Exit(1)
}
}
Expand All @@ -454,7 +440,7 @@ func GetClientset(kubeContext string) (*rest.Config, *kubernetes.Clientset) {
restConfig := controllers.GetConfigContextOrDie(kubeContext)
kubeClientset, err := kubernetes.NewForConfig(restConfig)
if err != nil {
ctrl.Log.Error(err, "Could not instantiate Clientset")
ctrlutils.LogE(err, "Could not instantiate Clientset")
os.Exit(1)
}
return restConfig, kubeClientset
Expand Down Expand Up @@ -482,7 +468,7 @@ func RunRemoteCmd(kubeContext string, namespace string, podName string, containe
if err != nil {
errMsg := fmt.Sprintf("Command \"%s\" [Pod: %s - Container: %s] failed with the following stderr: %s",
strings.Join(cmdArgs, " "), podName, containerName, errorBuffer.String())
ctrl.Log.Error(err, errMsg)
ctrlutils.LogE(err, errMsg)
os.Exit(1)
}
return buffer
Expand All @@ -493,10 +479,10 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
secretContent := make(map[string]interface{})
err := yaml.Unmarshal(readFile, &secretContent)
if err != nil {
ctrl.Log.Error(err, "Problem on reading the file content")
ctrlutils.LogE(err, "Problem on reading the file content")
}
if len(secretContent) == 0 {
ctrl.Log.Error(errors.New("file is empty"), "The file is empty or it does not exist!")
ctrlutils.LogE(errors.New("file is empty"), "The file is empty or it does not exist!")
os.Exit(1)
}
return secretContent
Expand All @@ -505,7 +491,7 @@ func ReadYAMLToMapOrDie(filePath string) map[string]interface{} {
func GetKubectlPath() string {
kubectlPath, err := exec.LookPath("kubectl")
if err != nil {
ctrl.Log.Error(errors.New("no kubectl binary"),
ctrlutils.LogE(errors.New("no kubectl binary"),
"No 'kubectl' binary found. Please install the 'kubectl' binary before attempting a restore")
os.Exit(1)
}
Expand All @@ -519,7 +505,7 @@ func ExecuteKubectlClient(ns string, podName string, containerName string, execu

err := cmd.Run()
if err != nil {
ctrl.Log.Error(err, "There is an issue on executing command: "+executeCommand)
ctrlutils.LogE(err, "There is an issue on executing command: "+executeCommand)
os.Exit(1)
}

Expand Down
8 changes: 4 additions & 4 deletions controllers/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
var secret apiv1.Secret
secretName := "config-update-secrets"
if !r.GetM(secretName, &secret) {
r.log.V(1).Info("Creating the config-update service account secret")
utils.LogI("Creating the config-update service account secret")
secret = apiv1.Secret{
Type: "kubernetes.io/service-account-token",
ObjectMeta: metav1.ObjectMeta{
Expand Down Expand Up @@ -129,13 +129,13 @@ func (r *SFController) SetupBaseSecrets(internalTenantSecretsVersion string) boo
}

if !found {
r.log.V(1).Info("Creating base secret job")
utils.LogI("Creating base secret job")
r.CreateR(r.RunCommand(jobName, []string{"config-create-zuul-secrets"}, extraCmdVars))
return false
} else if job.Status.Succeeded >= 1 {
return true
} else {
r.log.V(1).Info("Waiting for base secret job result")
utils.LogI("Waiting for base secret job result")
return false
}
}
Expand Down Expand Up @@ -213,7 +213,7 @@ func (r *SFController) SetupConfigJob() bool {
// This ensures that the zuul-scheduler loaded the provisionned Zuul config
// for the 'internal' tenant
if needReconfigureTenant {
r.log.Info("Running tenant-reconfigure for the 'internal' tenant")
utils.LogI("Running tenant-reconfigure for the 'internal' tenant")
if r.runZuulInternalTenantReconfigure() {
// Create an empty ConfigMap to keep note the reconfigure has been already done
zsInternalTenantReconfigure.ObjectMeta = metav1.ObjectMeta{
Expand Down
2 changes: 1 addition & 1 deletion controllers/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (r *SFController) DeployHTTPDGateway() bool {
current := appsv1.Deployment{}
if r.GetM(ident, &current) {
if !utils.MapEquals(&current.Spec.Template.ObjectMeta.Annotations, &annotations) {
r.log.V(1).Info("gateway configuration changed, rollout gateway pods ...")
utils.LogI("gateway configuration changed, rollout gateway pods ...")
current.Spec = dep.DeepCopy().Spec
r.UpdateR(&current)
return false
Expand Down
16 changes: 16 additions & 0 deletions controllers/libs/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"golang.org/x/crypto/ssh"
"gopkg.in/ini.v1"
"k8s.io/apimachinery/pkg/api/resource"
ctrl "sigs.k8s.io/controller-runtime"
)

// GetEnvVarValue returns the value of the named env var. Return an empty string when not found.
Expand All @@ -38,6 +39,21 @@ func BoolPtr(b bool) *bool { return &b }

var Execmod int32 = 493 // decimal for 0755 octal

// LogI logs a message with the INFO log Level
func LogI(msg string) {
ctrl.Log.Info(msg)
}

// LogD logs a message with the DEBUG log Level
func LogD(msg string) {
ctrl.Log.V(1).Info(msg)
}

// LogE logs a message with the Error log Level
func LogE(err error, msg string) {
ctrl.Log.Error(err, msg)
}

// NewUUIDString produce a UUID
func NewUUIDString() string {
return uuid.New().String()
Expand Down
4 changes: 2 additions & 2 deletions controllers/logserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (r *SFController) ensureLogserverPodMonitor() bool {
return false
} else {
if !utils.MapEquals(&currentLspm.ObjectMeta.Annotations, &annotations) {
r.log.V(1).Info("Logserver PodMonitor configuration changed, updating...")
utils.LogI("Logserver PodMonitor configuration changed, updating...")
currentLspm.Spec = desiredLsPodmonitor.Spec
currentLspm.ObjectMeta.Annotations = annotations
r.UpdateR(&currentLspm)
Expand Down Expand Up @@ -106,7 +106,7 @@ func (r *SFController) ensureLogserverPromRule() bool {
return false
} else {
if !utils.MapEquals(&currentPromRule.ObjectMeta.Annotations, &annotations) {
r.log.V(1).Info("Logserver default Prometheus rules changed, updating...")
utils.LogI("Logserver default Prometheus rules changed, updating...")
currentPromRule.Spec = desiredLsPromRule.Spec
currentPromRule.ObjectMeta.Annotations = annotations
r.UpdateR(&currentPromRule)
Expand Down
2 changes: 1 addition & 1 deletion controllers/mariadb.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ GRANT ALL ON *.* TO root@'%%' WITH GRANT OPTION;`,
Data: nil,
}
if !r.GetM(zuulDBConfigSecret, &zuulDBSecret) {
r.log.V(1).Info("Starting DB Post Init")
utils.LogI("Starting DB Post Init")
zuulDBSecret = r.DBPostInit(zuulDBSecret)
}
}
Expand Down
4 changes: 2 additions & 2 deletions controllers/nodepool.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ func (r *SFController) ensureNodepoolPromRule(cloudsYaml map[string]interface{})
return false
} else {
if !utils.MapEquals(&currentPromRule.ObjectMeta.Annotations, &annotations) {
r.log.V(1).Info("Nodepool default Prometheus rules changed, updating...")
utils.LogI("Nodepool default Prometheus rules changed, updating...")
currentPromRule.Spec = desiredNodepoolPromRule.Spec
currentPromRule.ObjectMeta.Annotations = annotations
r.UpdateR(&currentPromRule)
Expand Down Expand Up @@ -790,7 +790,7 @@ func (r *SFController) DeployNodepoolLauncher(statsdExporterVolume apiv1.Volume,
current := appsv1.Deployment{}
if r.GetM(LauncherIdent, &current) {
if !utils.MapEquals(&current.Spec.Template.ObjectMeta.Annotations, &annotations) {
r.log.V(1).Info("Nodepool-launcher configuration changed, rollout pods ...")
utils.LogI("Nodepool-launcher configuration changed, rollout pods ...")
current.Spec = nl.DeepCopy().Spec
r.UpdateR(&current)
return false
Expand Down
Loading

0 comments on commit fce0e5b

Please sign in to comment.