grafana-backuper/main.go
Tom Neuber 0fb6e0b6e9
All checks were successful
continuous-integration/drone/push Build is passing
Add git functions & improve grafana functions
2024-02-16 21:56:27 +01:00

93 lines
2.7 KiB
Go

package main
import (
"context"
"fmt"
"log"
"slices"
"git.ar21.de/yolokube/grafana-backuper/pkg/git"
"git.ar21.de/yolokube/grafana-backuper/pkg/grafana"
)
const (
grafanaURL = "https://grafana.services.yolokube.de"
grafanaAPIKey = ""
gitBranch = "main"
gitRepoURL = ""
gitUsername = ""
gitEmail = ""
gitPassword = ""
privateGPGKeyFile = ""
)
func main() {
ctx := context.Background()
client, err := grafana.NewClient(grafanaURL, grafanaAPIKey, grafana.DefaultHTTPClient)
if err != nil {
log.Fatalf("Error creating the grafana client: %v", err)
}
gitdata := git.NewPayload(privateGPGKeyFile)
if err = gitdata.GetRepo(gitRepoURL, gitUsername, gitPassword); err != nil {
log.Fatalf("Error cloning git repo: %v", err)
}
gitdata.AddCommitter(gitUsername, gitEmail)
dashboards, err := client.SearchDashboards(ctx, "", false)
if err != nil {
log.Fatalf("Error fetching dashboards: %v", err)
}
for _, dashboard := range dashboards {
gitdata.UpdateDashboard(dashboard)
_, dashboardInfo, err := client.GetRawDashboardByUID(ctx, dashboard.UID)
if err != nil {
log.Fatalf("Error fetching information of dashboard %s: %v", dashboard.Title, err)
}
gitdata.UpdateDashboardInfo(dashboardInfo)
versions, err := client.GetDashboardVersionsByDashboardUID(ctx, dashboard.UID)
if err != nil {
log.Fatalf("Error fetching versions for dashboard %s: %v", dashboard.Title, err)
}
slices.Reverse(versions)
for _, version := range versions {
gitdata.UpdateVersion(version)
if gitdata.IsVersionCommitted(gitBranch) {
fmt.Printf("%s/%s - %s: %s -> already committed\n", dashboardInfo.FolderTitle, dashboard.Title, version.CreatedBy, version.Message)
continue
}
fmt.Printf("%s/%s - %s: %s\n", dashboardInfo.FolderTitle, dashboard.Title, version.CreatedBy, version.Message)
raw, info, err := client.GetRawDashboardByUIDAndVersion(ctx, dashboard.UID, version.Version)
if err != nil {
log.Fatalf("Error fetching dashboard %s version %d: %v", dashboard.Title, version.Version, err)
}
gitdata.AddAuthor(info.CreatedBy, "")
output, err := grafana.ConvertRawToIndent(raw)
if err != nil {
log.Fatalf("Error pritty-printing dashboard %s version %d: %v", dashboard.Title, info.Version, err)
}
gitdata.UpdateContent([]byte(output))
gitdata.UpdateCommitter()
if err = gitdata.CreateCommit(); err != nil {
log.Fatalf("Error creating commit for dashboard %s version %d: %v", dashboard.Title, info.Version, err)
}
if err = gitdata.PushToRemote(gitUsername, gitPassword); err != nil {
log.Fatalf("Error pushing to remote repo %s: %v", gitRepoURL, err)
}
}
}
}