Skip to content
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
44 changes: 8 additions & 36 deletions cmd/container-suseconnect/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,9 @@ import (
"github.com/urfave/cli/v2"
)

func actionWrapper(action func(*cli.Context) error) func(*cli.Context) error {
return func(ctx *cli.Context) error {
if err := action(ctx); err != nil {
switch err.(type) {
case *cs.SuseConnectError:
if err.(*cs.SuseConnectError).ErrorCode == cs.GetCredentialsError {
if ctx.Bool("log-credentials-errors") {
return err
}
return nil
}
}
return err
}
return nil
}
}

func main() {
cs.SetLoggerOutput()

// Set the basic CLI metadata
app := cli.NewApp()
app.Copyright = fmt.Sprintf("© %d SUSE LCC", time.Now().Year())
Expand All @@ -73,13 +57,13 @@ func main() {
defaultUsageAdditionListProducts := ""
switch filepath.Base(os.Args[0]) {
case "container-suseconnect-zypp":
app.Action = actionWrapper(runZypperPlugin)
app.Action = runZypperPlugin
defaultUsageAdditionZypp = " (default)"
case "susecloud":
app.Action = actionWrapper(runZypperURLResolver)
app.Action = runZypperURLResolver
defaultUsageAdditionZypp = " (default)"
default:
app.Action = actionWrapper(runListProducts)
app.Action = runListProducts
defaultUsageAdditionListProducts = " (default)"
}

Expand All @@ -90,28 +74,20 @@ func main() {
Aliases: []string{"lp"},
Usage: fmt.Sprintf("List available products%v",
defaultUsageAdditionListProducts),
Action: actionWrapper(runListProducts),
Action: runListProducts,
},
{
Name: "list-modules",
Aliases: []string{"lm"},
Usage: "List available modules",
Action: actionWrapper(runListModules),
Action: runListModules,
},
{
Name: "zypper",
Aliases: []string{"z", "zypp"},
Usage: fmt.Sprintf("Run the zypper service plugin%v",
defaultUsageAdditionZypp),
Action: actionWrapper(runZypperPlugin),
},
}

app.Flags = []cli.Flag{
&cli.BoolFlag{
Name: "log-credentials-errors",
Usage: "Print errors with your credentials",
EnvVars: []string{"CONTAINER_SUSECONNECT_LOG_CREDENTIALS_ERR"},
Action: runZypperPlugin,
},
}

Expand Down Expand Up @@ -173,8 +149,6 @@ func requestProducts() ([]cs.Product, error) {
// Read the arguments as given by zypper on the stdin and print into stdout the
// response to be used.
func runZypperURLResolver(_ *cli.Context) error {
log.SetOutput(cs.GetLoggerFile())

if err := regionsrv.ServerReachable(); err != nil {
return fmt.Errorf("could not reach build server from the host: %v", err)
}
Expand All @@ -192,8 +166,6 @@ func runZypperURLResolver(_ *cli.Context) error {
// can be specified via the `ADDITIONAL_MODULES` environment variable, which
// reflect the module `identifier`.
func runZypperPlugin(_ *cli.Context) error {
log.SetOutput(cs.GetLoggerFile())

products, err := requestProducts()
if err != nil {
return err
Expand Down
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ go 1.21

require (
github.com/mssola/capture v1.1.0
github.com/stretchr/testify v1.9.0
github.com/urfave/cli/v2 v2.27.4
)

require (
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mssola/capture v1.1.0 h1:6eQlJabrKukAgp4+ytyEB+AACciMqA30H2WRhhHC0xk=
github.com/mssola/capture v1.1.0/go.mod h1:pHi3j6hBxMY+w6folEomycA/3aUz/4VtXRlKJaBcY7E=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/urfave/cli/v2 v2.27.4 h1:o1owoI+02Eb+K107p27wEX9Bb8eqIoZCfLXloLUSWJ8=
github.com/urfave/cli/v2 v2.27.4/go.mod h1:m4QzxcD2qpra4z7WhzEGn74WZLViBnMpb1ToCAKdGRQ=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
93 changes: 71 additions & 22 deletions internal/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,85 @@ package containersuseconnect

import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
)

// The default path for the logger if nothing has been specified.
var defaultLogPath = "/var/log/suseconnect.log"

// The environment variable used to specify a custom path for the logger
// path.
const logEnv = "SUSECONNECT_LOG_FILE"

// GetLoggerFile returns the output file for the logger. If the `logEnv` environment
// variable has been set, it will try to output there. Otherwise, it
// will try to output to the file as given in `defaultLogPath`. If
// everything fails, it will just output to the standard error channel.
func GetLoggerFile() *os.File {
// Determine the path to be used.
var path string
if env := os.Getenv(logEnv); env != "" {
path = env
} else {
path = defaultLogPath
// Default path for the log file.
const DefaultLogPath = "/var/log/suseconnect.log"

// Environment variable used to specify a custom path for the log file.
const LogEnv = "SUSECONNECT_LOG_FILE"

// getLogEnv returns the value set to the [LogEnv] environment variable.
func getLogEnv() string {
return strings.TrimSpace(os.Getenv(LogEnv))
}

// getLogWritter checks if the path can be open and written to
// and returns an [io.WriteCloser] if there are no errors.
func getLogWritter(path string) (io.WriteCloser, error) {
path = strings.TrimSpace(path)

if len(path) == 0 {
return nil, fmt.Errorf("path is empty")
}

if !filepath.IsAbs(path) {
return nil, fmt.Errorf("log path is not absulute: %s", path)
}

lf, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)

if err != nil {
return nil, err
}

if fi, err := lf.Stat(); err == nil {
if !fi.Mode().IsRegular() {
lf.Close()
return nil, fmt.Errorf("path is not a regular file: %s", path)
}
}

// If it's writable, use the given file, otherwise use os.Stderr.
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
_, err = lf.WriteString(fmt.Sprintf("container-suseconnect %s\n", Version))

if err != nil {
lf.Close()
return nil, err
}

return lf, nil
}

// SetLoggerOutput configures the logger to write to /dev/stderr
// and to a file.
//
// If [LogEnv] is set and writable it writes to the file defined,
// otherwise it writes to [DefaultLogPath].
func SetLoggerOutput() {
// ensure we are logging to stderr and nowhere else
log.SetOutput(os.Stderr)

path := getLogEnv()

if len(path) == 0 {
path = DefaultLogPath
}

w, err := getLogWritter(path)

if err == nil {
return f
writter := io.MultiWriter(os.Stderr, w)
log.SetOutput(writter)
log.Printf("Log file location: %s\n", path)
} else {
log.Printf("Failed to set up log file '%s'\n", path)
log.Println(err)
}
return os.Stderr
}

// Log the given formatted string with its parameters, and return it
Expand Down
Loading