Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
tukaelu committed Nov 11, 2023
1 parent 52145d4 commit 6d09c21
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 100 deletions.
104 changes: 4 additions & 100 deletions cmd/ikesu/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,11 @@ import (
"os"
"os/signal"
"slices"
"strings"
"syscall"

"github.com/aws/aws-lambda-go/lambda"
"github.com/mackerelio/mackerel-client-go"
"github.com/urfave/cli/v2"

"github.com/tukaelu/ikesu/cmd/ikesu/subcommand"
"github.com/tukaelu/ikesu/internal/config"
"github.com/tukaelu/ikesu/internal/constants"
"github.com/tukaelu/ikesu/internal/logger"
)

var version string
Expand All @@ -28,10 +22,9 @@ func main() {
Usage: "Manage the health condition of the fish in the \"Ikesu\".",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "apikey",
DefaultText: "**********",
EnvVars: []string{"MACKEREL_APIKEY", "IKESU_MACKEREL_APIKEY"},
Required: true,
Name: "apikey",
EnvVars: []string{"MACKEREL_APIKEY", "IKESU_MACKEREL_APIKEY"},
Required: true,
},
&cli.StringFlag{
Name: "apibase",
Expand All @@ -56,76 +49,7 @@ func main() {
},
},
Commands: []*cli.Command{
{
Name: "check",
Usage: "Detects disruptions in posted metrics and notifies the host as a CRITICAL alert.",
UsageText: "ikesu check -config <config file> [-dry-run]",
Action: func(ctx *cli.Context) error {

// Show the provider name and metric name, then terminate.
if ctx.Bool("show-providers") {
showProvidersInspectionMetricMap()
return nil
}

var l *logger.Logger
var err error
if l, err = logger.NewLogger(ctx.String("log"), ctx.String("log-level"), ctx.Bool("dry-run")); err != nil {
return err
}

config, err := config.NewCheckConfig(ctx.Context, ctx.String("config"))
if err != nil {
return err
}
if err := config.Validate(); err != nil {
return err
}
client, err := mackerel.NewClientWithOptions(
ctx.String("apikey"),
ctx.String("apibase"),
false,
)
if err != nil {
return err
}
check := &subcommand.Check{
Config: config,
Client: client,
DryRun: ctx.Bool("dry-run"),
Logger: l,
}

// wrap function
handler := func(ctx context.Context) error {
return check.Run(ctx)
}
l.Log.Info("Run command", "version", ctx.App.Version)
l.Log.Debug("Config", "dump", fmt.Sprintf("%+v", config))

if isLambda() {
lambda.StartWithOptions(handler, lambda.WithContext(ctx.Context))
return nil
}
return handler(ctx.Context)
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Specify the path to the configuration file.",
Aliases: []string{"c"},
EnvVars: []string{"IKESU_CHECK_CONFIG"},
},
&cli.BoolFlag{
Name: "show-providers",
Usage: "List the inspection metric names corresponding to the provider for each integration.",
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "Only a simplified display of the check results is performed, and no alerts are issued.",
},
},
},
subcommand.NewCheckCommand(),
},
}

Expand All @@ -139,23 +63,3 @@ func main() {
os.Exit(1)
}
}

func isLambda() bool {
return os.Getenv("AWS_EXECUTION_ENV") != "" || os.Getenv("AWS_LAMBDA_RUNTIME_API") != ""
}

func showProvidersInspectionMetricMap() {
integrations := constants.GetIntegrations()
providers := constants.GetProviders()
immap := constants.GetProvidersInspectionMetricMap()
for i := 0; i < len(integrations); i++ {
fmt.Printf("Integration: %s\n", integrations[i])
fmt.Println(strings.Repeat("-", 30))
for _, key := range providers {
if metric, ok := immap[integrations[i]][key]; ok {
fmt.Printf("provider: %-20s, metric: %s\n", key, metric)
}
}
fmt.Println("")
}
}
99 changes: 99 additions & 0 deletions cmd/ikesu/subcommand/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,94 @@ package subcommand
import (
"context"
"fmt"
"os"
"slices"
"strings"
"time"

"github.com/aws/aws-lambda-go/lambda"
"github.com/mackerelio/mackerel-client-go"
"github.com/urfave/cli/v2"

"github.com/tukaelu/ikesu/internal/config"
"github.com/tukaelu/ikesu/internal/constants"
"github.com/tukaelu/ikesu/internal/logger"
)

// NewCheckCommand returns a command that detects disruptions in posted metrics and notifies the host as a CRITICAL alert.
func NewCheckCommand() *cli.Command {
return &cli.Command{
Name: "check",
Usage: "Detects disruptions in posted metrics and notifies the host as a CRITICAL alert.",
UsageText: "ikesu check -config <config file> [-dry-run]",
Action: func(ctx *cli.Context) error {

// Show the provider name and metric name, then terminate.
if ctx.Bool("show-providers") {
showProvidersInspectionMetricMap()
return nil
}

var l *logger.Logger
var err error
if l, err = logger.NewLogger(ctx.String("log"), ctx.String("log-level"), ctx.Bool("dry-run")); err != nil {
return err
}

config, err := config.NewCheckConfig(ctx.Context, ctx.String("config"))
if err != nil {
return err
}
if err := config.Validate(); err != nil {
return err
}
client, err := mackerel.NewClientWithOptions(
ctx.String("apikey"),
ctx.String("apibase"),
false,
)
if err != nil {
return err
}
check := &Check{
Config: config,
Client: client,
DryRun: ctx.Bool("dry-run"),
Logger: l,
}

// wrap function
handler := func(ctx context.Context) error {
return check.Run(ctx)
}
l.Log.Info("Run command", "version", ctx.App.Version)
l.Log.Debug("Config", "dump", fmt.Sprintf("%+v", config))

if isLambda() {
lambda.StartWithOptions(handler, lambda.WithContext(ctx.Context))
return nil
}
return handler(ctx.Context)
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Specify the path to the configuration file.",
Aliases: []string{"c"},
EnvVars: []string{"IKESU_CHECK_CONFIG"},
},
&cli.BoolFlag{
Name: "show-providers",
Usage: "List the inspection metric names corresponding to the provider for each integration.",
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "Only a simplified display of the check results is performed, and no alerts are issued.",
},
},
}
}

type Check struct {
Config *config.CheckConfig
Client *mackerel.Client
Expand Down Expand Up @@ -128,6 +205,28 @@ func (c *Check) Run(ctx context.Context) error {
return nil
}

// judge whether it is running on AWS Lambda.
func isLambda() bool {
return os.Getenv("AWS_EXECUTION_ENV") != "" || os.Getenv("AWS_LAMBDA_RUNTIME_API") != ""
}

// Show the provider name and metric name, then terminate.
func showProvidersInspectionMetricMap() {
integrations := constants.GetIntegrations()
providers := constants.GetProviders()
immap := constants.GetProvidersInspectionMetricMap()
for i := 0; i < len(integrations); i++ {
fmt.Printf("Integration: %s\n", integrations[i])
fmt.Println(strings.Repeat("-", 35))
for _, key := range providers {
if metric, ok := immap[integrations[i]][key]; ok {
fmt.Printf("provider: %-25s, metric: %s\n", key, metric)
}
}
fmt.Println("")
}
}

// see constants.providersInspectionMetricMap
func getHostProviderType(h *mackerel.Host) string {
pType := make([]string, 0)
Expand Down

0 comments on commit 6d09c21

Please sign in to comment.