Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
spinillos authored Oct 15, 2024
2 parents 1baff6f + d09e93a commit 7671196
Show file tree
Hide file tree
Showing 15 changed files with 261 additions and 34 deletions.
54 changes: 54 additions & 0 deletions cmd/grr/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package main

import (
"fmt"
"strings"

"github.com/fatih/color"
"github.com/go-clix/cli"
"github.com/grafana/grizzly/pkg/config"
"github.com/grafana/grizzly/pkg/grizzly"
"github.com/spf13/viper"
)

Expand Down Expand Up @@ -193,3 +196,54 @@ func createContextCmd() *cli.Command {
}
return initialiseLogging(cmd, &opts)
}

func checkCmd(registry grizzly.Registry) *cli.Command {
cmd := &cli.Command{
Use: "check",
Short: "Create a configuration context",
}
var opts LoggingOpts

cmd.Run = func(cmd *cli.Command, args []string) error {
red := color.New(color.FgRed).SprintfFunc()
yellow := color.New(color.FgYellow).SprintfFunc()
green := color.New(color.FgGreen).SprintfFunc()

gCtx, err := config.CurrentContext()
if err != nil {
return err
}

fmt.Printf("Configuration file: %s\n", green(viper.ConfigFileUsed()))
fmt.Printf("Current context: %s\n\n", green(gCtx.Name))

for i, provider := range registry.Providers {
fmt.Println(yellow(provider.Name()))
fmt.Println(yellow(strings.Repeat("=", len(provider.Name()))))

status := provider.Status()

activeMsg := green("true")
if !status.Active {
activeMsg = fmt.Sprintf("%s - %s", red("false"), status.ActiveReason)
}
fmt.Printf("Active: %s\n", activeMsg)

onlineMsg := green("true")
if !status.Active || !status.Online {
onlineMsg = red("false")
}
if status.Active && !status.Online {
onlineMsg = fmt.Sprintf("%s - %s", red("false"), status.OnlineReason)
}
fmt.Printf("Online: %s\n", onlineMsg)

if i != len(registry.Providers)-1 {
fmt.Printf("\n")
}
}

return nil
}
return initialiseLogging(cmd, &opts)
}
20 changes: 6 additions & 14 deletions cmd/grr/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@ package main

import (
"errors"
"fmt"
"os"
"strings"

"github.com/go-clix/cli"
"github.com/grafana/grizzly/pkg/config"
"github.com/grafana/grizzly/pkg/grafana"
"github.com/grafana/grizzly/pkg/grizzly"
"github.com/grafana/grizzly/pkg/grizzly/notifier"
"github.com/grafana/grizzly/pkg/mimir"
"github.com/grafana/grizzly/pkg/syntheticmonitoring"
log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -40,6 +37,11 @@ func main() {
Version: Version,
}

log.SetFormatter(&log.TextFormatter{
DisableTimestamp: true,
DisableLevelTruncation: true,
})

config.Initialise()
err := config.Read()
if err != nil {
Expand All @@ -64,7 +66,7 @@ func main() {
exportCmd(registry),
snapshotCmd(registry),
providersCmd(registry),
configCmd(),
configCmd(registry),
serveCmd(registry),
selfUpdateCmd(),
)
Expand All @@ -87,15 +89,5 @@ func createRegistry(context *config.Context) grizzly.Registry {
syntheticmonitoring.NewProvider(&context.SyntheticMonitoring),
}

var providerList []string
for _, provider := range providers {
err := provider.Validate()
if err != nil {
providerList = append(providerList, fmt.Sprintf("%s - inactive (%s)", provider.Name(), err.Error()))
} else {
providerList = append(providerList, provider.Name()+" - active")
}
}
notifier.InfoStderr(nil, "Providers: "+strings.Join(providerList, ", "))
return grizzly.NewRegistry(providers)
}
9 changes: 7 additions & 2 deletions cmd/grr/workflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,13 @@ func serveCmd(registry grizzly.Registry) *cli.Command {
return err
}

resourcesPath := args[0]
resourcesPath := ""
watchPaths := args

if len(args) > 0 {
resourcesPath = args[0]
}

if opts.WatchScript != "" {
resourcesPath = ""
}
Expand Down Expand Up @@ -489,7 +493,7 @@ func providersCmd(registry grizzly.Registry) *cli.Command {
return initialiseLogging(cmd, &opts)
}

func configCmd() *cli.Command {
func configCmd(registry grizzly.Registry) *cli.Command {
cmd := &cli.Command{
Use: "config <sub-command>",
Short: "Show, select or configure configuration",
Expand All @@ -504,6 +508,7 @@ func configCmd() *cli.Command {
cmd.AddCommand(setCmd())
cmd.AddCommand(unsetCmd())
cmd.AddCommand(createContextCmd())
cmd.AddCommand(checkCmd(registry))
return cmd
}

Expand Down
25 changes: 25 additions & 0 deletions internal/logger/decorator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package logger

import (
"github.com/sirupsen/logrus"
)

type MinimalLogger interface {
Print(v ...interface{})
}

type decoratedLogger struct {
logger *logrus.Logger
level logrus.Level
}

func (d *decoratedLogger) Print(v ...interface{}) {
d.logger.Log(d.level, v...)
}

func DecorateAtLevel(l *logrus.Logger, level logrus.Level) MinimalLogger {
return &decoratedLogger{
logger: l,
level: level,
}
}
31 changes: 28 additions & 3 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,36 @@ var acceptableKeys = map[string]string{

func Get(path, outputFormat string) (string, error) {
ctx := viper.GetString(CurrentContextSetting)
fullPath := fmt.Sprintf("contexts.%s", ctx)

vCtx := viper.Sub(fmt.Sprintf("contexts.%s", ctx))
if vCtx == nil {
vCtx = viper.New()
}
override(vCtx)

var val any
val = vCtx.AllSettings()

if path != "" {
fullPath = fmt.Sprintf("%s.%s", fullPath, path)
for _, part := range strings.Split(path, ".") {
if val == nil {
break
}

values, ok := val.(map[string]interface{})
if !ok {
val = nil
break
}

val, ok = values[part]
if !ok {
val = nil
break
}
}
}
val := viper.Get(fullPath)

if val == nil {
return "", fmt.Errorf("key not found: %s", path)
}
Expand Down
26 changes: 26 additions & 0 deletions pkg/grafana/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,32 @@ func (p *Provider) Validate() error {
return nil
}

func (p *Provider) Status() grizzly.ProviderStatus {
status := grizzly.ProviderStatus{}

if err := p.Validate(); err != nil {
status.ActiveReason = err.Error()
return status
}

status.Active = true

client, err := p.Client()
if err != nil {
status.OnlineReason = err.Error()
return status
}

if _, err = client.Dashboards.GetHomeDashboard(); err != nil {
status.OnlineReason = err.Error()
return status
}

status.Online = true

return status
}

func (p *Provider) Name() string {
return "Grafana"
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/grizzly/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@ import (
"encoding/json"
"os"
"path/filepath"

log "github.com/sirupsen/logrus"
)

type JSONParser struct {
registry Registry
logger *log.Entry
}

func NewJSONParser(registry Registry) *JSONParser {
return &JSONParser{
registry: registry,
logger: log.WithField("parser", "json"),
}
}

Expand All @@ -22,6 +26,8 @@ func (parser *JSONParser) Accept(file string) bool {

// Parse evaluates a JSON file and parses it into resources
func (parser *JSONParser) Parse(file string, options ParserOptions) (Resources, error) {
parser.logger.WithField("file", file).Debug("Parsing file")

f, err := os.Open(file)
if err != nil {
return Resources{}, err
Expand Down
5 changes: 5 additions & 0 deletions pkg/grizzly/jsonnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,20 @@ import (

"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
log "github.com/sirupsen/logrus"
)

type JsonnetParser struct {
registry Registry
jsonnetPaths []string
logger *log.Entry
}

func NewJsonnetParser(registry Registry, jsonnetPaths []string) *JsonnetParser {
return &JsonnetParser{
registry: registry,
jsonnetPaths: jsonnetPaths,
logger: log.WithField("parser", "json"),
}
}

Expand All @@ -32,6 +35,8 @@ func (parser *JsonnetParser) Accept(file string) bool {

// Parse evaluates a jsonnet file and parses it into an object tree
func (parser *JsonnetParser) Parse(file string, options ParserOptions) (Resources, error) {
parser.logger.WithField("file", file).Debug("Parsing file")

if _, err := os.Stat(file); os.IsNotExist(err) {
return Resources{}, fmt.Errorf("file does not exist: %s", file)
}
Expand Down
11 changes: 10 additions & 1 deletion pkg/grizzly/parsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,15 @@ type FilteredParser struct {
registry Registry
decorated Parser
targets []string
logger *log.Entry
}

func NewFilteredParser(registry Registry, decorated Parser, targets []string) *FilteredParser {
return &FilteredParser{
registry: registry,
decorated: decorated,
targets: targets,
logger: log.WithField("parser", "filtered"),
}
}

Expand All @@ -87,13 +89,20 @@ func (parser *FilteredParser) Accept(file string) bool {
}

func (parser *FilteredParser) Parse(resourcePath string, options ParserOptions) (Resources, error) {
parser.logger.WithField("resourcePath", resourcePath).Debug("Parsing resource")

resources, err := parser.decorated.Parse(resourcePath, options)
if err != nil {
return resources, err
}

resources = resources.Filter(func(resource Resource) bool {
return parser.registry.ResourceMatchesTarget(resource.Kind(), resource.Name(), parser.targets)
result := parser.registry.ResourceMatchesTarget(resource.Kind(), resource.Name(), parser.targets)
if !result {
parser.logger.WithField("resource", resource.Ref().String()).Debug("Omitting resource")
}

return result
})

return parser.registry.Sort(resources), nil
Expand Down
13 changes: 13 additions & 0 deletions pkg/grizzly/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import (
"github.com/gobwas/glob"
)

type ProviderStatus struct {
// Active indicates that the provider is properly configured.
Active bool
ActiveReason string
// Online indicates that the configuration could be used successfully to perform requests.
Online bool
OnlineReason string
}

// Provider describes a single Endpoint Provider
type Provider interface {
Name() string
Expand All @@ -16,6 +25,10 @@ type Provider interface {
APIVersion() string
GetHandlers() []Handler
Validate() error

// Status performs checks to determine if the provider is active (ie: properly configured)
// and "online" (able to perform requests).
Status() ProviderStatus
}

type ProxyProvider interface {
Expand Down
Loading

0 comments on commit 7671196

Please sign in to comment.