Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Commit

Permalink
refactor to use slog
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Shen <mshen@redhat.com>
  • Loading branch information
mjlshen committed Aug 30, 2023
1 parent 0112207 commit 6bbc8a2
Show file tree
Hide file tree
Showing 16 changed files with 116 additions and 110 deletions.
3 changes: 0 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ require (
github.com/openshift-online/ocm-cli v0.1.67
github.com/openshift-online/ocm-sdk-go v0.1.364
github.com/openshift/backplane-cli v0.1.10
go.uber.org/zap v1.25.0
)

require (
Expand All @@ -33,7 +32,6 @@ require (
github.com/aws/aws-sdk-go-v2/service/sts v1.21.2 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/benbjohnson/clock v1.3.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
Expand Down Expand Up @@ -114,7 +112,6 @@ require (
github.com/subosito/gotenv v1.4.2 // indirect
github.com/xlab/treeprint v1.1.0 // indirect
go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/oauth2 v0.7.0 // indirect
golang.org/x/sync v0.1.0 // indirect
Expand Down
8 changes: 0 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,6 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
Expand Down Expand Up @@ -608,19 +606,13 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=
go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
Expand Down
62 changes: 29 additions & 33 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ package main
import (
"context"
"flag"
"log"
"fmt"
"log/slog"
"os"
"runtime/debug"

tea "github.com/charmbracelet/bubbletea"
"github.com/mjlshen/mirrosa/pkg/mirrosa"
"github.com/mjlshen/mirrosa/pkg/tui"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

func main() {
Expand All @@ -21,64 +20,61 @@ func main() {
verbose := f.Bool("v", false, "enable verbose logging")
f.Parse(os.Args[1:])

cfg := zap.NewDevelopmentConfig()
if !*verbose {
cfg.Level.SetLevel(zapcore.InfoLevel)
opts := slog.HandlerOptions{}
if *verbose {
opts.AddSource = true
opts.Level = slog.LevelDebug
}

logger, err := cfg.Build()
if err != nil {
log.Fatalf("unable to setup logger: %s", err)
}
defer logger.Sync()
sugared := logger.Sugar()
logger := slog.New(slog.NewTextHandler(os.Stdout, &opts))

if info, ok := debug.ReadBuildInfo(); ok {
sugared.Debugf("Go Version: %s", info.GoVersion)
logger.Debug(fmt.Sprintf("Go Version: %s", info.GoVersion))
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
sugared.Debugf("Git SHA: %s", setting.Value)
logger.Debug(fmt.Sprintf("Git SHA: %s", setting.Value))
}
if setting.Key == "vcs.time" {
sugared.Debugf("From: %s", setting.Value)
logger.Debug(fmt.Sprintf("From: %s", setting.Value))
}
}
}

if *interactive {
p := tea.NewProgram(tui.InitModel())
if _, err := p.Run(); err != nil {
sugared.Fatal(err)
logger.Error(err.Error())
}
os.Exit(0)
}

if *clusterId == "" {
sugared.Fatal("cluster id must not be empty")
logger.Error("cluster id must not be empty")
os.Exit(1)
}

mirrosa, err := mirrosa.NewRosaClient(context.TODO(), sugared, *clusterId)
m, err := mirrosa.NewRosaClient(context.Background(), logger, *clusterId)
if err != nil {
sugared.Fatal(err)
logger.Error(err.Error())
os.Exit(1)
}

sugared.Debugf("cluster info from OCM: %+v", *mirrosa.ClusterInfo)
sugared.Infof("%s: \"Mirror mirror on the wall, who's the fairest of them all?\"", mirrosa.ClusterInfo.Name)
logger.Debug("cluster info from OCM", "cluster info", *m.ClusterInfo)
logger.Info("who's the fairest of them all", "cluster", m.ClusterInfo.Name)

if err := mirrosa.ValidateComponents(context.TODO(),
mirrosa.NewVpc(),
mirrosa.NewDhcpOptions(),
mirrosa.NewSecurityGroup(),
mirrosa.NewVpcEndpointService(),
mirrosa.NewPublicHostedZone(),
mirrosa.NewPrivateHostedZone(),
mirrosa.NewApiLoadBalancer(),
mirrosa.NewInstances(),
if err := m.ValidateComponents(context.TODO(),
m.NewVpc(),
m.NewDhcpOptions(),
m.NewSecurityGroup(),
m.NewVpcEndpointService(),
m.NewPublicHostedZone(),
m.NewPrivateHostedZone(),
m.NewApiLoadBalancer(),
m.NewInstances(),
); err != nil {
sugared.Error(err)
logger.Error(err.Error())
os.Exit(1)
}

sugared.Infof("mirrosa: \"%s is the fairest of them all!\"", mirrosa.ClusterInfo.Name)
logger.Info(fmt.Sprintf("%s is the fairest of them all!", m.ClusterInfo.Name))
os.Exit(0)
}
23 changes: 12 additions & 11 deletions pkg/mirrosa/api_loadbalancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package mirrosa
import (
"context"
"fmt"
"log/slog"

"github.com/aws/aws-sdk-go-v2/aws"
elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
"github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
"go.uber.org/zap"
)

const (
Expand Down Expand Up @@ -45,7 +46,7 @@ type NetworkLoadBalancerAPIClient interface {
}

type NetworkLoadBalancer struct {
log *zap.SugaredLogger
log *slog.Logger
InfraName string
PrivateLink bool
Sts bool
Expand All @@ -67,7 +68,7 @@ func (c *Client) NewApiLoadBalancer() NetworkLoadBalancer {

func (n NetworkLoadBalancer) Validate(ctx context.Context) error {
for name, nlb := range n.getExpectedNLBs() {
n.log.Infof("searching for network load balancer: %s", nlb.name)
n.log.Info("searching for network load balancer", slog.String("name", nlb.name))
resp, err := n.ElbV2Client.DescribeLoadBalancers(ctx, &elbv2.DescribeLoadBalancersInput{
Names: []string{nlb.name},
})
Expand All @@ -91,7 +92,7 @@ func (n NetworkLoadBalancer) Validate(ctx context.Context) error {
case 0:
return fmt.Errorf("NLB %s not found in VPC: %s", nlb.name, n.VpcId)
case 1:
n.log.Infof("found NLB: %s", matches[0])
n.log.Info("found NLB", slog.String("arn", matches[0]))
nlbArn = matches[0]
default:
return fmt.Errorf("multiple matches found for NLB: %s in VPC %s", nlb.name, n.VpcId)
Expand All @@ -109,14 +110,14 @@ func (n NetworkLoadBalancer) Validate(ctx context.Context) error {
break
}

n.log.Debugf("found listener: %s", *l.ListenerArn)
n.log.Debug("found listener", slog.String("arn", *l.ListenerArn))
for k, expectedListener := range nlb.expectedListeners {
if listenersEqual(expectedListener, l) {
if err := n.validateTargetGroups(ctx, *l.DefaultActions[0].TargetGroupArn, expectedListener.healthyTargets); err != nil {
return err
}

n.log.Infof("listener validated for %s: %+v", k, expectedListener)
n.log.Info("listener validated", slog.String("elb", k), slog.String("listenerConfig", fmt.Sprintf("%+v", expectedListener)))
delete(nlb.expectedListeners, k)
}
}
Expand Down Expand Up @@ -190,8 +191,8 @@ func listenersEqual(expected listener, actual types.Listener) bool {

// validateTargetGroups searches for a target group by arn and checks if it has the expected number of healthy targets
func (n NetworkLoadBalancer) validateTargetGroups(ctx context.Context, arn string, expected int) error {
n.log.Infof("validating target group: %s", arn)
n.log.Debugf("searching for target group: %s", arn)
n.log.Info("validating target groups", slog.String("arn", arn))
n.log.Debug("searching for target groups", slog.String("arn", arn))
resp, err := n.ElbV2Client.DescribeTargetGroups(ctx, &elbv2.DescribeTargetGroupsInput{
TargetGroupArns: []string{arn},
})
Expand All @@ -203,12 +204,12 @@ func (n NetworkLoadBalancer) validateTargetGroups(ctx context.Context, arn strin
case 0:
return fmt.Errorf("target group %s not found", arn)
case 1:
n.log.Debugf("found target group: %s", *resp.TargetGroups[0].TargetGroupArn)
n.log.Debug("found target group", slog.String("arn", *resp.TargetGroups[0].TargetGroupArn))
default:
return fmt.Errorf("multiple matches found for target group: %s", arn)
}

n.log.Debugf("validating target group: %s has %d healthy targets", arn, expected)
n.log.Debug("validating target group: %s has %d healthy targets", slog.String("arn", arn), slog.Int("healthyTargets", expected))
healthResp, err := n.ElbV2Client.DescribeTargetHealth(ctx, &elbv2.DescribeTargetHealthInput{
TargetGroupArn: aws.String(arn),
})
Expand All @@ -227,6 +228,6 @@ func (n NetworkLoadBalancer) validateTargetGroups(ctx context.Context, arn strin
return fmt.Errorf("expected %d healthy targets for %s, only found %d", expected, arn, healthyTargets)
}

n.log.Infof("validated target group: %s", arn)
n.log.Info("validated target group", slog.String("arn", arn))
return nil
}
8 changes: 4 additions & 4 deletions pkg/mirrosa/dhcp_option_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package mirrosa
import (
"context"
"fmt"
"log/slog"
"strings"

"github.com/aws/aws-sdk-go-v2/service/ec2"
"go.uber.org/zap"
)

const dhcpOptionsDescription = "DHCP Option Sets configure how devices uses the DHCP protocol within a VPC [1]. " +
Expand All @@ -28,7 +28,7 @@ type MirrosaDhcpOptionsAPIClient interface {
}

type DhcpOptions struct {
log *zap.SugaredLogger
log *slog.Logger
VpcId string

Ec2Client MirrosaDhcpOptionsAPIClient
Expand All @@ -43,7 +43,7 @@ func (c *Client) NewDhcpOptions() DhcpOptions {
}

func (d DhcpOptions) Validate(ctx context.Context) error {
d.log.Debugf("validating that the attached DHCP Options Set has no uppercase characters in its domain name(s)")
d.log.Debug("validating that the attached DHCP Options Set has no uppercase characters in its domain name(s)")
vpcResp, err := d.Ec2Client.DescribeVpcs(ctx, &ec2.DescribeVpcsInput{
VpcIds: []string{d.VpcId},
})
Expand Down Expand Up @@ -71,7 +71,7 @@ func (d DhcpOptions) Validate(ctx context.Context) error {
switch *config.Key {
case "domain-name":
for _, v := range config.Values {
d.log.Debugf("validating DHCP Options Set domain name: %s", *v.Value)
d.log.Debug("validating DHCP Options Set domain name", slog.String("domainName", *v.Value))
if *v.Value != strings.ToLower(*v.Value) {
return fmt.Errorf("DHCP Options set: %s contains uppercase letters in the domain name: %s", dhcpOptionsId, *v.Value)
} else if strings.Contains(*v.Value, " ") {
Expand Down
12 changes: 7 additions & 5 deletions pkg/mirrosa/dhcp_option_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package mirrosa

import (
"context"
"log/slog"
"os"
"testing"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"go.uber.org/zap/zaptest"
"testing"
)

type mockMirrosaDhcpOptionsAPIClient struct {
Expand All @@ -31,7 +33,7 @@ func TestDhcpOptions_Validate(t *testing.T) {
{
name: "all lowercase",
dhcpOptions: &DhcpOptions{
log: zaptest.NewLogger(t).Sugar(),
log: slog.New(slog.NewTextHandler(os.Stdout, nil)),
VpcId: "id",
Ec2Client: &mockMirrosaDhcpOptionsAPIClient{
describeDhcpOptionsResp: &ec2.DescribeDhcpOptionsOutput{
Expand Down Expand Up @@ -66,7 +68,7 @@ func TestDhcpOptions_Validate(t *testing.T) {
{
name: "contains uppercase",
dhcpOptions: &DhcpOptions{
log: zaptest.NewLogger(t).Sugar(),
log: slog.New(slog.NewTextHandler(os.Stdout, nil)),
VpcId: "id",
Ec2Client: &mockMirrosaDhcpOptionsAPIClient{
describeDhcpOptionsResp: &ec2.DescribeDhcpOptionsOutput{
Expand Down Expand Up @@ -101,7 +103,7 @@ func TestDhcpOptions_Validate(t *testing.T) {
{
name: "contains space",
dhcpOptions: &DhcpOptions{
log: zaptest.NewLogger(t).Sugar(),
log: slog.New(slog.NewTextHandler(os.Stdout, nil)),
VpcId: "id",
Ec2Client: &mockMirrosaDhcpOptionsAPIClient{
describeDhcpOptionsResp: &ec2.DescribeDhcpOptionsOutput{
Expand Down
Loading

0 comments on commit 6bbc8a2

Please sign in to comment.