Skip to content

Commit

Permalink
Configure logger and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
hornwind committed Aug 4, 2023
1 parent 558b162 commit 5988128
Show file tree
Hide file tree
Showing 10 changed files with 191 additions and 25 deletions.
6 changes: 6 additions & 0 deletions .changes/unreleased/Other-20230804-174431.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Other
body: Configure logger and refactor logging
time: 2023-08-04T17:44:31.752865458+04:00
custom:
Author: Hornwind
Issue: ""
6 changes: 4 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"os"

"github.com/hornwind/openstack-image-keeper/pkg/action"
log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
)

Expand All @@ -19,6 +19,7 @@ var commands = []*cli.Command{
}

func main() {
log := log.GetLogger()
c := CreateApp()

defer recoverPanic()
Expand All @@ -29,11 +30,12 @@ func main() {
}

func recoverPanic() {
log := log.GetLogger()
if r := recover(); r != nil {
switch r.(type) {
case CommandNotFoundError:
log.Error(r)
log.Exit(127)
log.Logger.Exit(127)
default:
log.Panic(r)
}
Expand Down
52 changes: 34 additions & 18 deletions pkg/action/cleanupByName.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
gh "github.com/hornwind/openstack-image-keeper/pkg/git-history"
log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
"golang.org/x/exp/slices"
)
Expand All @@ -21,6 +21,7 @@ var _ Action = (*CleanupByName)(nil)
type CleanupByName struct {
savedImages map[string]images.Image
imagesForDeletion map[string]images.Image
loglevel string
scanDepth int
dryRun bool
}
Expand All @@ -41,20 +42,13 @@ Images for deletion:

// Run is the main function for 'cleanup' command.
func (c *CleanupByName) Run(ctx context.Context) error {
c.savedImages = make(map[string]images.Image, 0)
c.imagesForDeletion = make(map[string]images.Image, 0)
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return err
}
authOpts := &ao
provider, err := openstack.AuthenticatedClient(*authOpts)
if err != nil {
log := log.GetLogger()
if err := log.SetLogLevel(c.loglevel); err != nil {
return err
}
eo := &gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
}

c.savedImages = make(map[string]images.Image, 0)
c.imagesForDeletion = make(map[string]images.Image, 0)

imageName, ok := ctx.Value("firstArg").(string)
if !ok || imageName == "" {
Expand All @@ -66,26 +60,45 @@ func (c *CleanupByName) Run(ctx context.Context) error {
Owner: os.Getenv("OS_PROJECT_ID"),
Name: imageName,
}
client, err := openstack.NewImageServiceV2(provider, *eo)

client, err := c.getImageServiceClient()
if err != nil {
return err
}

log.Printf("Dry-run %t", c.dryRun)

log.Infof("Dry-run %t", c.dryRun)
if err = c.buildLists(imageName, client, listOpts); err != nil {
return err
}

if !c.dryRun {
log.Printf("Running cleanup for %s", imageName)
log.Infof("Running cleanup for %s", imageName)
return c.cleanupImages(ctx, client)
}

return nil
}

func (c *CleanupByName) getImageServiceClient() (*gophercloud.ServiceClient, error) {
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, err
}
authOpts := &ao
provider, err := openstack.AuthenticatedClient(*authOpts)
if err != nil {
return nil, err
}
eo := &gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
}

return openstack.NewImageServiceV2(provider, *eo)
}

func (c *CleanupByName) buildLists(name string, client *gophercloud.ServiceClient, listOpts *images.ListOpts) error {
log := log.GetLogger()

allPages, err := images.List(client, *listOpts).AllPages()
if err != nil {
log.Error(err)
Expand All @@ -106,6 +119,7 @@ func (c *CleanupByName) buildLists(name string, client *gophercloud.ServiceClien
}

func (c *CleanupByName) filterImagesByCommitAndTime(imgs []images.Image, commits []string) error {
log := log.GetLogger()
latestImg := images.Image{}
currentCommitImg := images.Image{}

Expand Down Expand Up @@ -213,9 +227,10 @@ func (c *CleanupByName) filterImagesByCommitAndTime(imgs []images.Image, commits
}

func (c *CleanupByName) cleanupImages(ctx context.Context, client *gophercloud.ServiceClient) error {
log := log.GetLogger()
for _, img := range c.imagesForDeletion {
result := images.Delete(client, img.ID)
log.Printf("Delete image %s", img.ID)
log.Infof("Delete image %s", img.ID)
if result.Err != nil {
return result.Err
}
Expand All @@ -239,6 +254,7 @@ func (c *CleanupByName) flags() []cli.Flag {
self := []cli.Flag{
flagScanDepth(&c.scanDepth),
flagDryRun(&c.dryRun),
flagLogLevel(&c.loglevel),
}

return self
Expand Down
19 changes: 18 additions & 1 deletion pkg/action/deleteByID.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
)

Expand All @@ -19,10 +19,16 @@ type DeleteByID struct {
authOpts *gophercloud.AuthOptions
provider *gophercloud.ProviderClient
eo *gophercloud.EndpointOpts
loglevel string
}

// Run is the main function for 'delete' command.
func (d *DeleteByID) Run(ctx context.Context) error {
log := log.GetLogger()
if err := log.SetLogLevel(d.loglevel); err != nil {
return err
}

ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return err
Expand All @@ -48,6 +54,7 @@ func (d *DeleteByID) Run(ctx context.Context) error {
}

func (d *DeleteByID) deleteImages(ctx context.Context, idList []string) error {
log := log.GetLogger()
client, _ := openstack.NewImageServiceV2(d.provider, *d.eo)

for _, id := range idList {
Expand All @@ -66,6 +73,16 @@ func (d *DeleteByID) Cmd() *cli.Command {
Name: "delete",
Aliases: []string{"del"},
Usage: "Delete image by id",
Flags: d.flags(),
Action: toCtx(d.Run),
}
}

// flags return flag set of CLI urfave.
func (d *DeleteByID) flags() []cli.Flag {
self := []cli.Flag{
flagLogLevel(&d.loglevel),
}

return self
}
13 changes: 13 additions & 0 deletions pkg/action/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import (
"github.com/urfave/cli/v2"
)

// flagScanDepth pass val to urfave flag.
func flagLogLevel(v *string) *cli.StringFlag {
return &cli.StringFlag{
Name: "loglevel",
Usage: "configure log level",
Value: "info",
EnvVars: []string{"HOUSEKEEPER_LOG_LEVEL"},
Destination: v,
}
}

// flagScanDepth pass val to urfave flag.
func flagScanDepth(v *int) *cli.IntFlag {
return &cli.IntFlag{
Expand All @@ -26,6 +37,7 @@ func flagDryRun(v *bool) *cli.BoolFlag {
}
}

// flagDryRun pass val to urfave flag.
func flagProtected(v *bool) *cli.BoolFlag {
return &cli.BoolFlag{
Name: "protected",
Expand All @@ -36,6 +48,7 @@ func flagProtected(v *bool) *cli.BoolFlag {
}
}

// flagDryRun pass val to urfave flag.
func flagHidden(v *bool) *cli.BoolFlag {
return &cli.BoolFlag{
Name: "hidden",
Expand Down
4 changes: 3 additions & 1 deletion pkg/action/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package action
import (
"context"

log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
)

Expand All @@ -23,10 +23,12 @@ func toCtx(a func(context.Context) error) func(c *cli.Context) error {
}

func getContextWithFlags(c *cli.Context) context.Context {
log := log.GetLogger()
ctx := c.Context
for _, flagName := range c.FlagNames() {
g := c.Value(flagName)
log.WithField("name", flagName).WithField("value", g).Trace("adding flag to action context.Context")
// log.GetLogger().GetLoggerWithField("name", flagName).WithField("value", g).Trace("adding flag to action context.Context")
ctx = context.WithValue(ctx, flagName, g) //nolint:staticcheck // weird issue, we won't have any collisions with strings
}

Expand Down
20 changes: 18 additions & 2 deletions pkg/action/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
)

var _ Action = (*List)(nil)

// List is a struct for running 'list' command.
type List struct{}
type List struct {
loglevel string
}

var listOutputTpl string = `Name: {{ .Name }}
ID: {{ $.ID }}
Expand All @@ -38,6 +40,10 @@ Properties:

// Run is the main function for 'list' command.
func (l *List) Run(ctx context.Context) error {
log := log.GetLogger()
if err := log.SetLogLevel(l.loglevel); err != nil {
return err
}
ao, err := openstack.AuthOptionsFromEnv()
if err != nil {
return err
Expand Down Expand Up @@ -92,6 +98,16 @@ func (l *List) Cmd() *cli.Command {
Name: "list",
Aliases: []string{"ls"},
Usage: "List of available images",
Flags: l.flags(),
Action: toCtx(l.Run),
}
}

// flags return flag set of CLI urfave.
func (l *List) flags() []cli.Flag {
self := []cli.Flag{
flagLogLevel(&l.loglevel),
}

return self
}
7 changes: 7 additions & 0 deletions pkg/action/publishByID.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
"github.com/urfave/cli/v2"
)

Expand All @@ -17,6 +18,7 @@ type Publication struct {
provider *gophercloud.ProviderClient
client *gophercloud.ServiceClient
eo *gophercloud.EndpointOpts
loglevel string
dryRun bool
protected bool
hidden bool
Expand All @@ -37,6 +39,10 @@ These images will be private:
)

func (p *Publication) Run(ctx context.Context) error {
log := log.GetLogger()
if err := log.SetLogLevel(p.loglevel); err != nil {
return err
}
if err := p.configureClient(); err != nil {
return err
}
Expand Down Expand Up @@ -212,6 +218,7 @@ func (p *Publication) flags() []cli.Flag {
flagDryRun(&p.dryRun),
flagProtected(&p.protected),
flagHidden(&p.hidden),
flagLogLevel(&p.loglevel),
}

return self
Expand Down
5 changes: 4 additions & 1 deletion pkg/git-history/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"os"

"github.com/go-git/go-git/v5"
log "github.com/sirupsen/logrus"
log "github.com/hornwind/openstack-image-keeper/pkg/logging"
)

func GetNCommitsFromHead(scanDepth int) ([]string, error) {
log := log.GetLogger()
var output []string

pwd, err := os.Getwd()
Expand Down Expand Up @@ -40,6 +41,7 @@ func GetNCommitsFromHead(scanDepth int) ([]string, error) {
}

func GetCurrentBranch() (string, error) {
log := log.GetLogger()
pwd, err := os.Getwd()
if err != nil {
log.Debug(err)
Expand All @@ -62,6 +64,7 @@ func GetCurrentBranch() (string, error) {
}

func GetTags(scanDepth int) ([]string, error) {
log := log.GetLogger()
var output []string

pwd, err := os.Getwd()
Expand Down
Loading

0 comments on commit 5988128

Please sign in to comment.