refactor(cmd): add backup command to cli

This commit is contained in:
Tom Neuber 2024-07-27 18:56:09 +02:00
parent 577f821b9d
commit 62b316b5ef
Signed by: tom
GPG key ID: F17EFE4272D89FF6
8 changed files with 357 additions and 193 deletions

148
internal/cmd/backup.go Normal file
View file

@ -0,0 +1,148 @@
package cmd
import (
"context"
"encoding/json"
"fmt"
"slices"
"git.ar21.de/yolokube/grafana-backuper/internal/config"
"git.ar21.de/yolokube/grafana-backuper/pkg/git"
"git.ar21.de/yolokube/grafana-backuper/pkg/grafana"
"github.com/spf13/cobra"
)
func NewBackupCommand(c *config.Config) *cobra.Command {
backupCmd := &cobra.Command{
Use: "backup",
Short: "Back up the dashboards from grafana to a git repository.",
Long: "Back up the dashboards from grafana to a git repository.",
RunE: func(cmd *cobra.Command, _ []string) error {
return backup(cmd.Context(), c)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return c.Validate()
},
}
backupCmd.PersistentFlags().BoolVar(&c.ForceCommits, "force", false, "Force git commits / ignore existence check")
backupCmd.PersistentFlags().StringVar(&c.GitEmail, "git-email", "", "Git email address")
backupCmd.PersistentFlags().StringVar(&c.GPGKey, "signing-key", "", "Path to the GPG signing key")
return backupCmd
}
func backup(ctx context.Context, c *config.Config) error {
client := grafana.NewClient(
c.GrafanaURL,
grafana.WithToken(c.GrafanaToken),
)
project := git.NewProject(
c.GitRepo,
git.WithBasicAuth(c.GitUser, c.GitPass),
git.WithBranch(c.GitBranch),
)
if err := project.Clone(ctx); err != nil {
return err
}
if err := project.Checkout(); err != nil {
return err
}
if err := project.Pull(ctx); err != nil {
return err
}
var signer git.SignKey
if c.GPGKey != "" {
signer = git.SignKey{KeyFile: c.GPGKey}
if err := signer.ReadKeyFile(); err != nil {
return err
}
}
dashboards, _, err := client.File.Search(ctx, grafana.WithType(grafana.SearchTypeDashboard))
if err != nil {
return err
}
for _, dashboardInfo := range dashboards {
var dashboard *grafana.Dashboard
dashboard, _, err = client.Dashboard.Get(ctx, dashboardInfo.UID)
if err != nil {
return err
}
var versions []*grafana.DashboardVersion
versions, _, err = client.DashboardVersion.List(ctx, dashboardInfo.UID)
if err != nil {
return err
}
slices.Reverse(versions)
var uncommitedVersion bool
for _, version := range versions {
var dashboardVersion *grafana.DashboardVersion
dashboardVersion, _, err = client.DashboardVersion.Get(ctx, dashboardInfo.UID, version.Version)
if err != nil {
return err
}
dashboard.Dashboard = dashboardVersion.Data
dashboard.UpdatedBy = dashboardVersion.CreatedBy
dashboard.Updated = dashboardVersion.Created
dashboard.Version = dashboardVersion.Version
var data []byte
data, err = json.MarshalIndent(grafana.SchemaFromDashboardMeta(dashboard), "", " ")
if err != nil {
return err
}
commitMsg := fmt.Sprintf(
"%s: Update %s to version %d",
dashboardInfo.Title,
dashboardInfo.UID,
dashboardVersion.ID,
)
if dashboardVersion.Message != "" {
commitMsg += fmt.Sprintf(" => %s", dashboardVersion.Message)
}
commitOpts := []git.CommitOption{
git.WithAuthor(dashboardVersion.CreatedBy, ""),
git.WithFileContent(data, dashboardInfo.Title, dashboard.FolderTitle),
git.WithSigner(signer),
}
if c.GitUser != "" {
commitOpts = append(commitOpts, git.WithCommitter(c.GitUser, c.GitEmail))
}
commit := project.NewCommit(commitOpts...)
if commit.Exists(dashboardVersion.DashboardUID, dashboardVersion.ID) && !c.ForceCommits && !uncommitedVersion {
fmt.Fprintf(c.Output, "%s -> already committed\n", commitMsg)
continue
}
uncommitedVersion = true
if err = commit.Create(commitMsg); err != nil {
return err
}
fmt.Fprintln(c.Output, commitMsg)
}
}
if project.HasChanges() {
if err = project.Push(ctx); err != nil {
return err
}
}
return nil
}

76
internal/cmd/root.go Normal file
View file

@ -0,0 +1,76 @@
package cmd
import (
"fmt"
"os"
"strings"
"git.ar21.de/yolokube/grafana-backuper/internal/config"
"git.ar21.de/yolokube/grafana-backuper/internal/version"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
const envVarPrefix = "GB"
func NewRootCommand(c *config.Config) *cobra.Command {
rootCmd := &cobra.Command{
Use: "grafana-backuper",
Short: "Grafana Backuper CLI",
Long: "A command-line tool to back up and restore Grafana dashboards",
Version: version.Version(),
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
initializeConfig(cmd)
c.Output = os.Stdout
if c.Quiet {
var err error
c.Output, err = os.Open(os.DevNull)
if err != nil {
return err
}
}
cmd.SetOut(c.Output)
return nil
},
SilenceUsage: true,
}
rootCmd.SetErrPrefix("Error:")
rootCmd.PersistentFlags().BoolVarP(&c.Debug, "debug", "d", false, "Debug output")
rootCmd.PersistentFlags().StringVar(&c.GrafanaURL, "grafana-url", "", "Grafana URL to access the API")
rootCmd.PersistentFlags().StringVar(&c.GrafanaToken, "grafana-token", "", "Grafana auth token to access the API")
rootCmd.PersistentFlags().StringVar(&c.GitBranch, "git-branch", "main", "Git branch name")
rootCmd.PersistentFlags().StringVar(&c.GitRepo, "git-repo", "", "Complete Git repository URL")
rootCmd.PersistentFlags().StringVar(&c.GitUser, "git-user", "", "Git user name")
rootCmd.PersistentFlags().StringVar(&c.GitPass, "git-pass", "", "Git user password")
rootCmd.PersistentFlags().BoolVarP(&c.Quiet, "quiet", "q", false, "Mute console output")
return rootCmd
}
func initializeConfig(cmd *cobra.Command) {
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.SetEnvPrefix(envVarPrefix)
v.AutomaticEnv()
bindFlags(cmd, v)
}
func bindFlags(cmd *cobra.Command, v *viper.Viper) {
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
// Apply the viper config value to the flag when the flag is not set and viper has a value
if !flag.Changed && v.IsSet(flag.Name) {
err := cmd.Flags().Set(
flag.Name,
fmt.Sprintf("%v", v.Get(flag.Name)),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
}
})
}

View file

@ -1,36 +1,52 @@
package config
import (
"flag"
"os"
"github.com/peterbourgon/ff"
"errors"
"io"
)
const envVarPrefix = "GB"
type Config struct {
Debug bool
ForceCommits bool
GrafanaURL string
GrafanaToken string
GitBranch string
GitEmail string
GitRepo string
GitUser string
GitEmail string
GitPass string
GPGKey string
Quiet bool
Output io.Writer
}
func (c *Config) RegisterFlags(fs *flag.FlagSet) error {
fs.BoolVar(&c.ForceCommits, "force-commits", false, "Force git commits / ignore existence check")
fs.StringVar(&c.GrafanaURL, "grafana-url", "", "Grafana URL to access the API")
fs.StringVar(&c.GrafanaToken, "grafana-token", "", "Grafana auth token to access the API")
fs.StringVar(&c.GitBranch, "git-branch", "main", "Git branch name")
fs.StringVar(&c.GitRepo, "git-repo", "", "Complete Git repository URL")
fs.StringVar(&c.GitUser, "git-user", "", "Git username")
fs.StringVar(&c.GitEmail, "git-email", "", "Git email address")
fs.StringVar(&c.GitPass, "git-pass", "", "Git user password")
fs.StringVar(&c.GPGKey, "signing-key", "", "Path to the GPG signing key")
func (c *Config) Validate() error {
var err error
return ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix(envVarPrefix))
if c.GrafanaURL == "" {
err = errors.Join(err, errors.New("invalid grafana URL, must not be blank"))
}
if c.GrafanaToken == "" {
err = errors.Join(err, errors.New("invalid auth token for grafana, must not be blank"))
}
if c.GitRepo == "" {
err = errors.Join(err, errors.New("invalid repo url for git, must not be blank"))
}
if c.GitUser == "" {
err = errors.Join(err, errors.New("invalid username for git, must not be blank"))
}
if c.GitPass == "" {
err = errors.Join(err, errors.New("invalid password for git, must not be blank"))
}
if c.GitBranch == "" {
err = errors.Join(err, errors.New("invalid branch name for git, must not be blank"))
}
return err
}

View file

@ -0,0 +1,17 @@
package version
import (
"fmt"
)
var (
version = "undefined"
versionPrerelease = "dev" //nolint:gochecknoglobals // this has to be a variable to set the version during release.
)
func Version() string {
if versionPrerelease != "" {
return fmt.Sprintf("%s-%s", version, versionPrerelease)
}
return version
}