Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

cli: add slog to commands #22

Merged
merged 3 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions cli/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -42,12 +42,17 @@ func runGenerate(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to parse flags: %w", err)
}

paths, err := findGenerateTargets(args)
logger, err := newCLILogger(cmd)
if err != nil {
return err
}

if err := generatePolicies(cmd.Context(), flags.policyPath, flags.settingsPath, paths); err != nil {
paths, err := findGenerateTargets(args, logger)
if err != nil {
return err
}

if err := generatePolicies(cmd.Context(), flags.policyPath, flags.settingsPath, paths, logger); err != nil {
return fmt.Errorf("failed to generate policies: %w", err)
}

Expand Down Expand Up @@ -80,7 +85,7 @@ func runGenerate(cmd *cobra.Command, args []string) error {
return nil
}

func findGenerateTargets(args []string) ([]string, error) {
func findGenerateTargets(args []string, logger *slog.Logger) ([]string, error) {
var paths []string
for _, path := range args {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
Expand All @@ -103,34 +108,34 @@ func findGenerateTargets(args []string) ([]string, error) {
}
}

paths = filterNonCoCoRuntime("kata-cc-isolation", paths)
paths = filterNonCoCoRuntime("kata-cc-isolation", paths, logger)

if len(paths) == 0 {
return nil, fmt.Errorf("no .yml/.yaml files found")
}
return paths, nil
}

func filterNonCoCoRuntime(runtimeClassName string, paths []string) []string {
func filterNonCoCoRuntime(runtimeClassName string, paths []string, logger *slog.Logger) []string {
var filtered []string
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
log.Printf("failed to read %s: %v", path, err)
logger.Warn("Failed to read file", "path", path, "err", err)
continue
}
if !bytes.Contains(data, []byte(runtimeClassName)) {
log.Printf("%s is not a CoCo runtime, ignoring", path)
logger.Info("Ignoring non-CoCo runtime", "className", runtimeClassName, "path", path)
continue
}
filtered = append(filtered, path)
}
return filtered
}

func generatePolicies(ctx context.Context, regoPath, policyPath string, yamlPaths []string) error {
func generatePolicies(ctx context.Context, regoPath, policyPath string, yamlPaths []string, logger *slog.Logger) error {
for _, yamlPath := range yamlPaths {
policyHash, err := generatePolicyForFile(ctx, regoPath, policyPath, yamlPath)
policyHash, err := generatePolicyForFile(ctx, regoPath, policyPath, yamlPath, logger)
if err != nil {
return fmt.Errorf("failed to generate policy for %s: %w", yamlPath, err)
}
Expand All @@ -142,7 +147,7 @@ func generatePolicies(ctx context.Context, regoPath, policyPath string, yamlPath
return nil
}

func generatePolicyForFile(ctx context.Context, regoPath, policyPath, yamlPath string) ([32]byte, error) {
func generatePolicyForFile(ctx context.Context, regoPath, policyPath, yamlPath string, logger *slog.Logger) ([32]byte, error) {
args := []string{
"--raw-out",
"--use-cached-files",
Expand All @@ -163,7 +168,7 @@ func generatePolicyForFile(ctx context.Context, regoPath, policyPath, yamlPath s
return [32]byte{}, fmt.Errorf("genpolicy failed: %w", err)
}
if stdout.Len() == 0 {
log.Printf("policy output for %s is empty, ignoring the file", yamlPath)
logger.Info("Policy output is empty, ignoring the file", "yamlPath", yamlPath)
return [32]byte{}, nil
}
policyHash := sha256.Sum256(stdout.Bytes())
Expand Down
40 changes: 40 additions & 0 deletions cli/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"fmt"
"log/slog"
"strconv"
"strings"

"github.com/spf13/cobra"
)

func newCLILogger(cmd *cobra.Command) (*slog.Logger, error) {
rawLogLevel, err := cmd.Flags().GetString("log-level")
if err != nil {
rawLogLevel = "info"
}
var level slog.Level
switch strings.ToLower(rawLogLevel) {
case "debug":
level = slog.LevelDebug
case "":
fallthrough
case "info":
level = slog.LevelInfo
case "warn":
level = slog.LevelWarn
case "error":
level = slog.LevelError
default:
numericLevel, err := strconv.Atoi(rawLogLevel)
if err != nil {
return nil, fmt.Errorf("invalid log level: %q", rawLogLevel)
}
level = slog.Level(numericLevel)
}
opts := &slog.HandlerOptions{
Level: level,
}
return slog.New(slog.NewTextHandler(cmd.ErrOrStderr(), opts)), nil
}
3 changes: 3 additions & 0 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ func newRootCmd() *cobra.Command {
Version: version,
}
cmd.SetOut(os.Stdout)

cmd.PersistentFlags().String("log-level", "info", "set logging level (debug, info, warn, error, or a number)")

cmd.InitDefaultVersionFlag()
cmd.AddCommand(
newGenerateCmd(),
Expand Down
10 changes: 7 additions & 3 deletions cli/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"os"

Expand Down Expand Up @@ -41,6 +40,11 @@ func runSet(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to parse flags: %w", err)
}

logger, err := newCLILogger(cmd)
if err != nil {
return err
}

manifestStr, err := os.ReadFile(flags.manifestPath)
if err != nil {
return fmt.Errorf("failed to read manifest file: %w", err)
Expand All @@ -51,7 +55,7 @@ func runSet(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to unmarshal manifest: %w", err)
}

paths, err := findGenerateTargets(args)
paths, err := findGenerateTargets(args, logger)
if err != nil {
return fmt.Errorf("finding yaml files: %w", err)
}
Expand Down Expand Up @@ -110,7 +114,7 @@ func runSet(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to set manifest: %w", err)
}

log.Println("Manifest set successfully")
logger.Info("Manifest set successfully")

if err := os.WriteFile("coordinator-root.pem", resp.CACert, 0o644); err != nil {
return fmt.Errorf("failed to write root certificate: %w", err)
Expand Down