Renamed vars and switched to use zerolog

This commit is contained in:
David Allen 2024-07-30 14:02:12 -06:00
parent 606a7b47cc
commit b27e6b6a73
No known key found for this signature in database
GPG key ID: 717C593FF60A2ACC
7 changed files with 68 additions and 103 deletions

View file

@ -6,10 +6,10 @@ import (
magellan "github.com/OpenCHAMI/magellan/internal" magellan "github.com/OpenCHAMI/magellan/internal"
"github.com/OpenCHAMI/magellan/internal/db/sqlite" "github.com/OpenCHAMI/magellan/internal/db/sqlite"
"github.com/OpenCHAMI/magellan/internal/log" "github.com/OpenCHAMI/magellan/internal/util"
"github.com/OpenCHAMI/magellan/pkg/smd" "github.com/OpenCHAMI/magellan/pkg/client"
"github.com/cznic/mathutil" "github.com/cznic/mathutil"
"github.com/sirupsen/logrus" "github.com/rs/zerolog/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -30,36 +30,32 @@ var collectCmd = &cobra.Command{
" magellan collect --cache ./assets.db --output ./logs --timeout 30 --cacert cecert.pem\n" + " magellan collect --cache ./assets.db --output ./logs --timeout 30 --cacert cecert.pem\n" +
" magellan collect --host smd.example.com --port 27779 --username username --password password", " magellan collect --host smd.example.com --port 27779 --username username --password password",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
// make application logger
l := log.NewLogger(logrus.New(), logrus.DebugLevel)
// get probe states stored in db from scan // get probe states stored in db from scan
probeStates, err := sqlite.GetProbeResults(cachePath) scannedResults, err := sqlite.GetScannedResults(cachePath)
if err != nil { if err != nil {
l.Log.Errorf("failed toget states: %v", err) log.Error().Err(err).Msgf("failed to get scanned results from cache")
} }
// try to load access token either from env var, file, or config if var not set // try to load access token either from env var, file, or config if var not set
if accessToken == "" { if accessToken == "" {
var err error var err error
accessToken, err = LoadAccessToken() accessToken, err = util.LoadAccessToken(tokenPath)
if err != nil { if err != nil {
l.Log.Errorf("failed to load access token: %v", err) log.Error().Err(err).Msgf("failed to load access token")
} }
} }
if verbose { if verbose {
fmt.Printf("access token: %v\n", accessToken) log.Debug().Str("Access Token", accessToken)
} }
// //
if concurrency <= 0 { if concurrency <= 0 {
concurrency = mathutil.Clamp(len(probeStates), 1, 255) concurrency = mathutil.Clamp(len(scannedResults), 1, 255)
} }
q := &magellan.QueryParams{ q := &magellan.QueryParams{
Username: username, Username: username,
Password: password, Password: password,
Protocol: protocol,
Timeout: timeout, Timeout: timeout,
Concurrency: concurrency, Concurrency: concurrency,
Verbose: verbose, Verbose: verbose,
@ -68,23 +64,21 @@ var collectCmd = &cobra.Command{
ForceUpdate: forceUpdate, ForceUpdate: forceUpdate,
AccessToken: accessToken, AccessToken: accessToken,
} }
err = magellan.CollectAll(&probeStates, l, q) err = magellan.CollectInventory(&scannedResults, q)
if err != nil { if err != nil {
l.Log.Errorf("failed to collect data: %v", err) log.Error().Err(err).Msgf("failed to collect data")
} }
// add necessary headers for final request (like token) // add necessary headers for final request (like token)
headers := make(map[string]string) header := util.HTTPHeader{}
if q.AccessToken != "" { header.Authorization(q.AccessToken)
headers["Authorization"] = "Bearer " + q.AccessToken
}
}, },
} }
func init() { func init() {
currentUser, _ = user.Current() currentUser, _ = user.Current()
collectCmd.PersistentFlags().StringVar(&smd.Host, "host", smd.Host, "set the host to the SMD API") collectCmd.PersistentFlags().StringVar(&client.Host, "host", client.Host, "set the host to the SMD API")
collectCmd.PersistentFlags().IntVarP(&smd.Port, "port", "p", smd.Port, "set the port to the SMD API") collectCmd.PersistentFlags().IntVarP(&client.Port, "port", "p", client.Port, "set the port to the SMD API")
collectCmd.PersistentFlags().StringVar(&username, "username", "", "set the BMC user") collectCmd.PersistentFlags().StringVar(&username, "username", "", "set the BMC user")
collectCmd.PersistentFlags().StringVar(&password, "password", "", "set the BMC password") collectCmd.PersistentFlags().StringVar(&password, "password", "", "set the BMC password")
collectCmd.PersistentFlags().StringVar(&protocol, "protocol", "https", "set the protocol used to query") collectCmd.PersistentFlags().StringVar(&protocol, "protocol", "https", "set the protocol used to query")

View file

@ -19,8 +19,9 @@ var crawlCmd = &cobra.Command{
Short: "Crawl a single BMC for inventory information", Short: "Crawl a single BMC for inventory information",
Long: "Crawl a single BMC for inventory information\n" + Long: "Crawl a single BMC for inventory information\n" +
"\n" + "\n" +
"Example:\n" + "Examples:\n" +
" magellan crawl https://bmc.example.com", " magellan crawl https://bmc.example.com\n" +
" magellan crawl https://bmc.example.com -i -u username -p password",
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
// Validate that the only argument is a valid URI // Validate that the only argument is a valid URI
if err := cobra.ExactArgs(1)(cmd, args); err != nil { if err := cobra.ExactArgs(1)(cmd, args); err != nil {

View file

@ -7,6 +7,7 @@ import (
"time" "time"
"github.com/OpenCHAMI/magellan/internal/db/sqlite" "github.com/OpenCHAMI/magellan/internal/db/sqlite"
"github.com/rs/zerolog/log"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -24,16 +25,19 @@ var listCmd = &cobra.Command{
" magellan list\n" + " magellan list\n" +
" magellan list --cache ./assets.db", " magellan list --cache ./assets.db",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
probeResults, err := sqlite.GetProbeResults(cachePath) scannedResults, err := sqlite.GetScannedResults(cachePath)
if err != nil { if err != nil {
logrus.Errorf("failed toget probe results: %v\n", err) logrus.Errorf("failed toget probe results: %v\n", err)
} }
format = strings.ToLower(format) format = strings.ToLower(format)
if format == "json" { if format == "json" {
b, _ := json.Marshal(probeResults) b, err := json.Marshal(scannedResults)
if err != nil {
log.Error().Err(err).Msgf("failed to unmarshal scanned results")
}
fmt.Printf("%s\n", string(b)) fmt.Printf("%s\n", string(b))
} else { } else {
for _, r := range probeResults { for _, r := range scannedResults {
fmt.Printf("%s:%d (%s) @ %s\n", r.Host, r.Port, r.Protocol, r.Timestamp.Format(time.UnixDate)) fmt.Printf("%s:%d (%s) @ %s\n", r.Host, r.Port, r.Protocol, r.Timestamp.Format(time.UnixDate))
} }
} }

View file

@ -7,9 +7,9 @@ import (
"os" "os"
magellan "github.com/OpenCHAMI/magellan/internal" magellan "github.com/OpenCHAMI/magellan/internal"
"github.com/OpenCHAMI/magellan/internal/log" "github.com/OpenCHAMI/magellan/internal/util"
"github.com/lestrrat-go/jwx/jwt" "github.com/lestrrat-go/jwx/jwt"
"github.com/sirupsen/logrus" "github.com/rs/zerolog/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -27,47 +27,50 @@ var loginCmd = &cobra.Command{
Short: "Log in with identity provider for access token", Short: "Log in with identity provider for access token",
Long: "", Long: "",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
// make application logger
l := log.NewLogger(logrus.New(), logrus.DebugLevel)
// check if we have a valid JWT before starting login // check if we have a valid JWT before starting login
if !forceLogin { if !forceLogin {
// try getting the access token from env var // try getting the access token from env var
testToken, err := LoadAccessToken() testToken, err := util.LoadAccessToken(tokenPath)
if err != nil { if err != nil {
l.Log.Errorf("failed to load access token: %v", err) log.Error().Err(err).Msgf("failed to load access token")
} }
// parse into jwt.Token to validate // parse into jwt.Token to validate
token, err := jwt.Parse([]byte(testToken)) token, err := jwt.Parse([]byte(testToken))
if err != nil { if err != nil {
fmt.Printf("failed to parse access token contents: %v\n", err) log.Error().Err(err).Msgf("failed to parse access token contents")
return return
} }
// check if the token is invalid and we need a new one // check if the token is invalid and we need a new one
err = jwt.Validate(token) err = jwt.Validate(token)
if err != nil { if err != nil {
fmt.Printf("failed to validate access token...fetching a new one") log.Error().Err(err).Msgf("failed to validate access token...fetching a new one")
} else { } else {
fmt.Printf("found a valid token...skipping login (use the '-f/--force' flag to login anyway)") log.Printf("found a valid token...skipping login (use the '-f/--force' flag to login anyway)")
return return
} }
} }
if verbose {
log.Printf("Listening for token on %s:%d", targetHost, targetPort)
}
// start the login flow // start the login flow
var err error var err error
accessToken, err = magellan.Login(loginUrl, targetHost, targetPort) accessToken, err = magellan.Login(loginUrl, targetHost, targetPort)
if errors.Is(err, http.ErrServerClosed) { if errors.Is(err, http.ErrServerClosed) {
if verbose {
fmt.Printf("\n=========================================\nServer closed.\n=========================================\n\n") fmt.Printf("\n=========================================\nServer closed.\n=========================================\n\n")
}
} else if err != nil { } else if err != nil {
fmt.Printf("failed to start server: %v\n", err) log.Error().Err(err).Msgf("failed to start server")
} }
// if we got a new token successfully, save it to the token path // if we got a new token successfully, save it to the token path
if accessToken != "" && tokenPath != "" { if accessToken != "" && tokenPath != "" {
err := os.WriteFile(tokenPath, []byte(accessToken), os.ModePerm) err := os.WriteFile(tokenPath, []byte(accessToken), os.ModePerm)
if err != nil { if err != nil {
fmt.Printf("failed to write access token to file: %v\n", err) log.Error().Err(err).Msgf("failed to write access token to file")
} }
} }
}, },

View file

@ -21,7 +21,7 @@ import (
"os/user" "os/user"
magellan "github.com/OpenCHAMI/magellan/internal" magellan "github.com/OpenCHAMI/magellan/internal"
"github.com/OpenCHAMI/magellan/pkg/smd" "github.com/OpenCHAMI/magellan/pkg/client"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -66,35 +66,6 @@ func Execute() {
} }
} }
// LoadAccessToken() tries to load a JWT string from an environment
// variable, file, or config in that order. If loading the token
// fails with one options, it will fallback to the next option until
// all options are exhausted.
//
// Returns a token as a string with no error if successful.
// Alternatively, returns an empty string with an error if a token is
// not able to be loaded.
func LoadAccessToken() (string, error) {
// try to load token from env var
testToken := os.Getenv("ACCESS_TOKEN")
if testToken != "" {
return testToken, nil
}
// try reading access token from a file
b, err := os.ReadFile(tokenPath)
if err == nil {
return string(b), nil
}
// TODO: try to load token from config
testToken = viper.GetString("access_token")
if testToken != "" {
return testToken, nil
}
return "", fmt.Errorf("failed toload token from environment variable, file, or config")
}
func init() { func init() {
currentUser, _ = user.Current() currentUser, _ = user.Current()
cobra.OnInitialize(InitializeConfig) cobra.OnInitialize(InitializeConfig)
@ -140,8 +111,8 @@ func SetDefaults() {
viper.SetDefault("scan.subnet-masks", []net.IP{}) viper.SetDefault("scan.subnet-masks", []net.IP{})
viper.SetDefault("scan.disable-probing", false) viper.SetDefault("scan.disable-probing", false)
viper.SetDefault("collect.driver", []string{"redfish"}) viper.SetDefault("collect.driver", []string{"redfish"})
viper.SetDefault("collect.host", smd.Host) viper.SetDefault("collect.host", client.Host)
viper.SetDefault("collect.port", smd.Port) viper.SetDefault("collect.port", client.Port)
viper.SetDefault("collect.user", "") viper.SetDefault("collect.user", "")
viper.SetDefault("collect.pass", "") viper.SetDefault("collect.pass", "")
viper.SetDefault("collect.protocol", "https") viper.SetDefault("collect.protocol", "https")

View file

@ -18,8 +18,6 @@ import (
) )
var ( var (
begin uint8
end uint8
subnets []string subnets []string
subnetMasks []net.IP subnetMasks []net.IP
disableProbing bool disableProbing bool
@ -38,7 +36,7 @@ var scanCmd = &cobra.Command{
"If the '--disable-probe` flag is used, the tool will not send another request to probe for available " + "If the '--disable-probe` flag is used, the tool will not send another request to probe for available " +
"Redfish services.\n\n" + "Redfish services.\n\n" +
"Example:\n" + "Example:\n" +
" magellan scan --subnet 172.16.0.0/24 --add-host 10.0.0.101\n" + " magellan scan --subnet 172.16.0.0/24 --host 10.0.0.101\n" +
" magellan scan --subnet 172.16.0.0 --subnet-mask 255.255.255.0 --cache ./assets.db", " magellan scan --subnet 172.16.0.0 --subnet-mask 255.255.255.0 --cache ./assets.db",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
var ( var (

View file

@ -2,8 +2,7 @@ package cmd
import ( import (
magellan "github.com/OpenCHAMI/magellan/internal" magellan "github.com/OpenCHAMI/magellan/internal"
"github.com/OpenCHAMI/magellan/internal/log" "github.com/rs/zerolog/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -26,17 +25,16 @@ var updateCmd = &cobra.Command{
Short: "Update BMC node firmware", Short: "Update BMC node firmware",
Long: "Perform an firmware update using Redfish by providing a remote firmware URL and component.\n" + Long: "Perform an firmware update using Redfish by providing a remote firmware URL and component.\n" +
"Examples:\n" + "Examples:\n" +
" magellan update --host 172.16.0.108 --port 443 --username bmc_username --password bmc_password --firmware-url http://172.16.0.200:8005/firmware/bios/image.RBU --component BIOS\n" + " magellan update --bmc.host 172.16.0.108 --bmc.port 443 --username bmc_username --password bmc_password --firmware-url http://172.16.0.200:8005/firmware/bios/image.RBU --component BIOS\n" +
" magellan update --status --host 172.16.0.108 --port 443 --username bmc_username --password bmc_password", " magellan update --status --bmc.host 172.16.0.108 --bmc.port 443 --username bmc_username --password bmc_password",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
l := log.NewLogger(logrus.New(), logrus.DebugLevel) // set up update parameters
q := &magellan.UpdateParams{ q := &magellan.UpdateParams{
FirmwarePath: firmwareUrl, FirmwarePath: firmwareUrl,
FirmwareVersion: firmwareVersion, FirmwareVersion: firmwareVersion,
Component: component, Component: component,
TransferProtocol: transferProtocol, TransferProtocol: transferProtocol,
QueryParams: magellan.QueryParams{ QueryParams: magellan.QueryParams{
Protocol: protocol,
Host: host, Host: host,
Username: username, Username: username,
Password: password, Password: password,
@ -47,53 +45,49 @@ var updateCmd = &cobra.Command{
// check if required params are set // check if required params are set
if host == "" || username == "" || password == "" { if host == "" || username == "" || password == "" {
l.Log.Fatal("requires host, user, and pass to be set") log.Error().Msg("requires host, user, and pass to be set")
} }
// get status if flag is set and exit // get status if flag is set and exit
if status { if status {
err := magellan.GetUpdateStatus(q) err := magellan.GetUpdateStatus(q)
if err != nil { if err != nil {
l.Log.Errorf("failed toget update status: %v", err) log.Error().Err(err).Msgf("failed to get update status")
} }
return return
} }
// client, err := magellan.NewClient(l, &q.QueryParams) // initiate a remote update
// if err != nil {
// l.Log.Errorf("failed tomake client: %v", err)
// }
// err = magellan.UpdateFirmware(client, l, q)
err := magellan.UpdateFirmwareRemote(q) err := magellan.UpdateFirmwareRemote(q)
if err != nil { if err != nil {
l.Log.Errorf("failed toupdate firmware: %v", err) log.Error().Err(err).Msgf("failed to update firmware")
} }
}, },
} }
func init() { func init() {
updateCmd.Flags().StringVar(&host, "bmc-host", "", "set the BMC host") updateCmd.Flags().StringVar(&host, "bmc.host", "", "set the BMC host")
updateCmd.Flags().IntVar(&port, "bmc-port", 443, "set the BMC port") updateCmd.Flags().IntVar(&port, "bmc.port", 443, "set the BMC port")
updateCmd.Flags().StringVar(&username, "username", "", "set the BMC user") updateCmd.Flags().StringVar(&username, "username", "", "set the BMC user")
updateCmd.Flags().StringVar(&password, "password", "", "set the BMC password") updateCmd.Flags().StringVar(&password, "password", "", "set the BMC password")
updateCmd.Flags().StringVar(&transferProtocol, "transfer-protocol", "HTTP", "set the transfer protocol") updateCmd.Flags().StringVar(&transferProtocol, "transfer-protocol", "HTTP", "set the transfer protocol")
updateCmd.Flags().StringVar(&protocol, "protocol", "https", "set the Redfish protocol") updateCmd.Flags().StringVar(&protocol, "protocol", "https", "set the Redfish protocol")
updateCmd.Flags().StringVar(&firmwareUrl, "firmware-url", "", "set the path to the firmware") updateCmd.Flags().StringVar(&firmwareUrl, "firmware.url", "", "set the path to the firmware")
updateCmd.Flags().StringVar(&firmwareVersion, "firmware-version", "", "set the version of firmware to be installed") updateCmd.Flags().StringVar(&firmwareVersion, "firmware.version", "", "set the version of firmware to be installed")
updateCmd.Flags().StringVar(&component, "component", "", "set the component to upgrade") updateCmd.Flags().StringVar(&component, "component", "", "set the component to upgrade")
updateCmd.Flags().BoolVar(&status, "status", false, "get the status of the update") updateCmd.Flags().BoolVar(&status, "status", false, "get the status of the update")
viper.BindPFlag("host", updateCmd.Flags().Lookup("host")) viper.BindPFlag("update.bmc.host", updateCmd.Flags().Lookup("bmc.host"))
viper.BindPFlag("port", updateCmd.Flags().Lookup("port")) viper.BindPFlag("update.bmc.port", updateCmd.Flags().Lookup("bmc.port"))
viper.BindPFlag("username", updateCmd.Flags().Lookup("username")) viper.BindPFlag("update.username", updateCmd.Flags().Lookup("username"))
viper.BindPFlag("password", updateCmd.Flags().Lookup("password")) viper.BindPFlag("update.password", updateCmd.Flags().Lookup("password"))
viper.BindPFlag("transfer-protocol", updateCmd.Flags().Lookup("transfer-protocol")) viper.BindPFlag("update.transfer-protocol", updateCmd.Flags().Lookup("transfer-protocol"))
viper.BindPFlag("protocol", updateCmd.Flags().Lookup("protocol")) viper.BindPFlag("update.protocol", updateCmd.Flags().Lookup("protocol"))
viper.BindPFlag("firmware.url", updateCmd.Flags().Lookup("firmware.url")) viper.BindPFlag("update.firmware.url", updateCmd.Flags().Lookup("firmware.url"))
viper.BindPFlag("firmware.version", updateCmd.Flags().Lookup("firmware.version")) viper.BindPFlag("update.firmware.version", updateCmd.Flags().Lookup("firmware.version"))
viper.BindPFlag("component", updateCmd.Flags().Lookup("component")) viper.BindPFlag("update.component", updateCmd.Flags().Lookup("component"))
viper.BindPFlag("secure-tls", updateCmd.Flags().Lookup("secure-tls")) viper.BindPFlag("update.secure-tls", updateCmd.Flags().Lookup("secure-tls"))
viper.BindPFlag("status", updateCmd.Flags().Lookup("status")) viper.BindPFlag("update.status", updateCmd.Flags().Lookup("status"))
rootCmd.AddCommand(updateCmd) rootCmd.AddCommand(updateCmd)
} }