Skip to content

Commit

Permalink
Minor refactoring and adding a test
Browse files Browse the repository at this point in the history
  • Loading branch information
safaci2000 committed Oct 17, 2024
1 parent ad433bc commit d88354d
Show file tree
Hide file tree
Showing 34 changed files with 194 additions and 106 deletions.
14 changes: 10 additions & 4 deletions cli/backup/alerting_contacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package backup
import (
"context"
"encoding/json"
"log"
"log/slog"

"github.com/bep/simplecobra"
Expand Down Expand Up @@ -44,10 +45,15 @@ func newListContactPointsCmd() simplecobra.Commander {
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
rootCmd.TableObj.AppendHeader(table.Row{"uid", "name", "slug", "type", "provenance", "settings"})
contactPoints := rootCmd.GrafanaSvc().ListContactPoints()
contactPoints, err := rootCmd.GrafanaSvc().ListContactPoints()
slog.Info("Listing contact points for context",
slog.String("Organization", GetOrganizationName()),
slog.String("context", GetContext()))
slog.Warn("GDG does not manage the 'email receiver' entity. It has a very odd behavior compared to all " +
"other entities. If you need to manage email contacts, please create a new contact. GDG will ignore the default contact.")
if err != nil {
log.Fatal("unable to retrieve Orgs contact points", slog.Any("err", err))
}
if len(contactPoints) == 0 {
slog.Info("No contact points found")
} else {
Expand Down Expand Up @@ -99,7 +105,7 @@ func newUploadContactPointsCmd() simplecobra.Commander {
cmd.Aliases = []string{"u"}
},
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *support.RootCommand, args []string) error {
removedItems, err := rootCmd.GrafanaSvc().UploadContactPoints()
newItems, err := rootCmd.GrafanaSvc().UploadContactPoints()
slog.Info("Upload contact points for context",
slog.String("Organization", GetOrganizationName()),
slog.String("context", GetContext()))
Expand All @@ -108,11 +114,11 @@ func newUploadContactPointsCmd() simplecobra.Commander {
} else {
slog.Info("contact points successfully uploaded")
rootCmd.TableObj.AppendHeader(table.Row{"name"})
for _, item := range removedItems {
for _, item := range newItems {
rootCmd.TableObj.AppendRow(table.Row{item})
}

rootCmd.Render(cd.CobraCommand, removedItems)
rootCmd.Render(cd.CobraCommand, newItems)
}
return nil
},
Expand Down
60 changes: 44 additions & 16 deletions internal/service/alerting.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,31 @@ import (
"log"
"log/slog"

"github.com/samber/lo"

"github.com/esnet/gdg/internal/tools/ptr"

"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/tools"
"github.com/grafana/grafana-openapi-client-go/client/provisioning"
"github.com/grafana/grafana-openapi-client-go/models"
)

func (s *DashNGoImpl) ListContactPoints() []*models.EmbeddedContactPoint {
const (
emailReceiver = "email receiver"
)

func (s *DashNGoImpl) ListContactPoints() ([]*models.EmbeddedContactPoint, error) {
p := provisioning.NewGetContactpointsParams()
result, err := s.GetClient().Provisioning.GetContactpoints(p)
if err != nil {
log.Fatalf("unable to retrieve contact points, err:%s", err.Error())
return nil, err
}
return result.GetPayload()
slog.Warn("removing any contacts with no uid such as 'email receiver' that cannot be managed by GDG")
data := lo.Filter(result.GetPayload(), func(item *models.EmbeddedContactPoint, index int) bool {
return item.UID != ""
})

return data, nil
}

func (s *DashNGoImpl) DownloadContactPoints() (string, error) {
Expand All @@ -27,16 +39,21 @@ func (s *DashNGoImpl) DownloadContactPoints() (string, error) {
err error
)
p := provisioning.NewGetContactpointsExportParams()
p.Download = tools.PtrOf(true)
p.Decrypt = tools.PtrOf(true)
p.Format = tools.PtrOf("json")
p.Download = ptr.Of(true)
p.Decrypt = ptr.Of(true)
p.Format = ptr.Of("json")
data, err := s.GetClient().Provisioning.GetContactpointsExport(p)
if err != nil {
log.Fatalf("unable to retrieve Contact Points, err: %s", err.Error())
}
// filter default contactPoints
payload := data.GetPayload()
payload.ContactPoints = lo.Filter(payload.ContactPoints, func(item *models.ContactPointExport, index int) bool {
return item.Name != emailReceiver
})

dsPath := buildResourcePath("contacts", config.AlertingResource)
if dsPacked, err = json.MarshalIndent(data.GetPayload(), "", " "); err != nil {
if dsPacked, err = json.MarshalIndent(payload.ContactPoints, "", " "); err != nil {
return "", fmt.Errorf("unable to serialize data to JSON. %w", err)
}
if err = s.storage.WriteFile(dsPath, dsPacked); err != nil {
Expand All @@ -52,8 +69,11 @@ func (s *DashNGoImpl) UploadContactPoints() ([]string, error) {
rawDS []byte
result []string
)
data := new(models.AlertingFileExport)
currentContacts := s.ListContactPoints()
var data []models.ContactPointExport
currentContacts, err := s.ListContactPoints()
if err != nil {
return nil, err
}
m := make(map[string]*models.EmbeddedContactPoint)
for ndx, i := range currentContacts {
m[i.UID] = currentContacts[ndx]
Expand All @@ -63,11 +83,15 @@ func (s *DashNGoImpl) UploadContactPoints() ([]string, error) {
if rawDS, err = s.storage.ReadFile(fileLocation); err != nil {
return nil, fmt.Errorf("failed to read file. file: %s, err: %w", fileLocation, err)
}
if err = json.Unmarshal(rawDS, data); err != nil {
if err = json.Unmarshal(rawDS, &data); err != nil {
return nil, fmt.Errorf("failed to unmarshall file, file:%s, err: %w", fileLocation, err)
}
for _, i := range data.ContactPoints {
for _, i := range data {
for _, r := range i.Receivers {
if r.UID == "" {
slog.Info("No valid UID found for record, skipping", slog.Any("type", r.Type))
continue
}
if _, ok := m[r.UID]; ok {
// do update
p := provisioning.NewPutContactpointParams()
Expand All @@ -77,7 +101,7 @@ func (s *DashNGoImpl) UploadContactPoints() ([]string, error) {
Name: i.Name,
Provenance: "",
Settings: r.Settings,
Type: tools.PtrOf(r.Type),
Type: ptr.Of(r.Type),
UID: r.UID,
}
_, err := s.GetClient().Provisioning.PutContactpoint(p)
Expand All @@ -95,9 +119,9 @@ func (s *DashNGoImpl) UploadContactPoints() ([]string, error) {
UID: r.UID,
Provenance: "",
Settings: r.Settings,
Type: tools.PtrOf(r.Type),
Type: ptr.Of(r.Type),
}
_, err := s.GetClient().Provisioning.PostContactpoints(p)
_, err = s.GetClient().Provisioning.PostContactpoints(p)
if err != nil {
slog.Error("failed to create contact point", slog.Any("uid", r.UID))
continue
Expand All @@ -116,7 +140,11 @@ func (s *DashNGoImpl) ClearContactPoints() ([]string, error) {
err error
results []string
)
contacts := s.ListContactPoints()
contacts, err := s.ListContactPoints()
if err != nil {
return nil, err
}

for _, contact := range contacts {
_, err = s.GetClient().Provisioning.DeleteContactpoints(contact.UID)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/service/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ type DashboardsApi interface {
}

type AlertingApi interface {
ListContactPoints() []*models.EmbeddedContactPoint
ListContactPoints() ([]*models.EmbeddedContactPoint, error)
DownloadContactPoints() (string, error)
ClearContactPoints() ([]string, error)
UploadContactPoints() ([]string, error)
Expand Down
8 changes: 5 additions & 3 deletions internal/service/dashboards.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"sort"
"strings"

"github.com/esnet/gdg/internal/tools/ptr"

"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/service/filters"
"github.com/esnet/gdg/internal/service/types"
Expand Down Expand Up @@ -279,9 +281,9 @@ func (s *DashNGoImpl) ListDashboards(filterReq filters.Filter) []*models.Hit {
if tag != "" {
searchParams.Tag = []string{tag}
}
searchParams.Limit = tools.PtrOf(limit)
searchParams.Page = tools.PtrOf(page)
searchParams.Type = tools.PtrOf(searchTypeDashboard)
searchParams.Limit = ptr.Of(limit)
searchParams.Page = ptr.Of(page)
searchParams.Type = ptr.Of(searchTypeDashboard)

pageBoardLinks, err := s.GetClient().Search.Search(searchParams)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions internal/service/libraryelements.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import (
"log/slog"
"strings"

"github.com/esnet/gdg/internal/tools/ptr"

"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/service/filters"
"github.com/esnet/gdg/internal/tools"
"github.com/gosimple/slug"
"github.com/grafana/grafana-openapi-client-go/client/library_elements"
"github.com/grafana/grafana-openapi-client-go/models"
Expand Down Expand Up @@ -66,7 +67,7 @@ func (s *DashNGoImpl) ListLibraryElements(filter filters.Filter) []*models.Libra

params := library_elements.NewGetLibraryElementsParams()
params.FolderFilter = &folderList
params.Kind = tools.PtrOf(listLibraryPanels)
params.Kind = ptr.Of(listLibraryPanels)
libraryElements, err := s.GetClient().LibraryElements.GetLibraryElements(params)
if err != nil {
log.Fatalf("Unable to list Library Elements %v", err)
Expand Down
22 changes: 16 additions & 6 deletions internal/service/mocks/AlertingApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/AuthenticationApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/ConnectionPermissions.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/ConnectionsApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/DashboardPermissionsApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/DashboardsApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/FoldersApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 16 additions & 6 deletions internal/service/mocks/GrafanaService.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/LibraryElementsApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/LicenseApi.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/service/mocks/NewClientOpts.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit d88354d

Please sign in to comment.