Skip to content

Commit

Permalink
resolved all lint errors and fixed the manual lint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
sio4 committed Apr 23, 2022
1 parent 520a801 commit 38d0ef5
Show file tree
Hide file tree
Showing 33 changed files with 371 additions and 144 deletions.
14 changes: 10 additions & 4 deletions checks/checks.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package checks contains all checkers to provide status checking service
package checks

import (
Expand All @@ -19,16 +20,18 @@ type Checker struct {

var _ common.Plugin = &Checker{}

// Name implements common.Plugin
// Name implements common.Plugin.
func (p *Checker) Name() string {
return p.name
}

// Run implements common.Plugin
// Run implements common.Plugin.
func (p *Checker) Run(c common.Context, opts common.PluginOptions, ch chan interface{}) error {
return p.runFunc(c, opts, ch)
}

// StartAll executes runners for all checkers and returns number of successful
// executions.
func StartAll(c common.Context, opts *common.Options, ch chan interface{}) int {
logger := c.Logger().WithField("module", "checker")
n := 0
Expand All @@ -37,17 +40,20 @@ func StartAll(c common.Context, opts *common.Options, ch chan interface{}) int {
x, _ := x.(common.Plugin)
if len(opts.Checkers) > 0 && !common.Contains(opts.Checkers, x.Name()) {
logger.Debugf("%v is not on the checker list. skipping...", x.Name())
continue
continue //nolint
}

copts := opts.CheckerOptions[x.Name()]
logger.Debugf("--- checker: %s %v with %v", x.Name(), x, copts)
logger.Infof("starting checker %v...", x.Name())

if err := x.Run(c, copts, ch); err != nil {
logger.Errorf("%s checker was aborted: %v", x.Name(), err)
// TODO: should returns error?
logger.Errorf("%s checker was aborted: %v", x.Name(), err)
} else {
n++
}
}

return n
}
8 changes: 7 additions & 1 deletion checks/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ const (
heartbeatCheckerIntervalSec = 60
)

// RegisterHeartbeat returns a new Checker instance and it is used by StartAll().
func (*Checker) RegisterHeartbeat() *Checker {
return &Checker{
name: heartbeatChecker,
runFunc: heartbeatRunner,
}
}

// heartbeatRunner is a Runner function for the HeartbeatChecker, the sample
// checker implementation.
// It starts goroutine that report periodic heartbeat and returns the error
// status.
func heartbeatRunner(c common.Context, opts common.PluginOptions, out chan interface{}) error {
logger := c.Logger().WithField("checker", heartbeatChecker)

Expand All @@ -28,7 +33,7 @@ func heartbeatRunner(c common.Context, opts common.PluginOptions, out chan inter
}

c.WG().Add(1)
go func() {
go func() { // nolint
defer c.WG().Done()

ticker := time.NewTicker(time.Duration(interval) * time.Second)
Expand All @@ -47,5 +52,6 @@ func heartbeatRunner(c common.Context, opts common.PluginOptions, out chan inter
}
logger.Infof("%s checker exited", heartbeatChecker)
}()

return nil
}
11 changes: 10 additions & 1 deletion checks/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@ var (
errTargetStringShouldNotBeEmpty = errors.New("target string should not be empty")
)

// RegisterPing returns a new Checker instance and it is used by StartAll().
func (*Checker) RegisterPing() *Checker {
return &Checker{
name: pingChecker,
runFunc: pingRunner,
}
}

// pingRunner is a Runner function for the PingChecker.
// It starts goroutines for each target and returns the error status.
func pingRunner(c common.Context, opts common.PluginOptions, out chan interface{}) error {
logger := c.Logger().WithField("checker", pingChecker)
logger.Debug("ping opts: ", opts)
Expand All @@ -52,7 +55,7 @@ func pingRunner(c common.Context, opts common.PluginOptions, out chan interface{
// spawn ping workers for each target
for _, h := range targets {
c.WG().Add(1)
go func(host string) {
go func(host string) { // nolint
defer c.WG().Done()

ticker := time.NewTicker(time.Duration(checkInterval) * time.Second)
Expand All @@ -68,6 +71,7 @@ func pingRunner(c common.Context, opts common.PluginOptions, out chan interface{
m, err := doPing(host, pingInterval)
if err != nil {
logger.Error(err)

break infinite
}
out <- m
Expand All @@ -77,9 +81,13 @@ func pingRunner(c common.Context, opts common.PluginOptions, out chan interface{
logger.Infof("%s checker for %s exited", pingChecker, host)
}(h)
}

return nil
}

// getTarget returns the list of target hosts to ping as an array of strings.
// When it runs on a supported cloud platform, it could uses the metadata of
// the platform (which is stored as "targets").
func getTarget(c common.Context, opts *common.PluginOptions) ([]string, error) {
targets := opts.GetValuesOr("targets", []string{})

Expand Down Expand Up @@ -115,6 +123,7 @@ func doPing(target string, interval int) (bogo.PingMessage, error) {
if err := pinger.Run(); err != nil {
return bogo.PingMessage{}, err
}

stats := pinger.Statistics()

return bogo.PingMessage{
Expand Down
2 changes: 1 addition & 1 deletion checks/ping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestPingRunner(t *testing.T) {
r.NoError(pingRunner(c, o, c.Channel()))
get := <-c.Channel()
r.NotNil(get)
m := get.(bogo.PingMessage)
m, _ := get.(bogo.PingMessage)
r.IsType(bogo.PingMessage{}, m)

c.Cancel()
Expand Down
23 changes: 16 additions & 7 deletions cmd/bogo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import (
func main() {
showVersion := false
showHelp := false
var copts string
var eopts string

var copts, eopts string

opts := common.DefaultOptions()

Expand All @@ -39,27 +39,32 @@ func main() {
getopt.FlagLong(&showHelp, "help", 'h', "show help message")

getopt.Parse()

if opts.IsDebug {
opts.LogLevel = "debug"
}

if showVersion {
fmt.Println("bogo", bogo.Version)
return
os.Exit(1)
}

if showHelp {
fmt.Println("bogo", bogo.Version)
getopt.Usage()
return
os.Exit(1)
}

c, _ := common.NewDefaultContext(&opts)
logger := c.Logger()

var err error

opts.CheckerOptions, err = common.BuildPluginOptions(copts)
if err != nil {
logger.Fatal("could not build checker options:", err)
}

opts.ExporterOptions, err = common.BuildPluginOptions(eopts)
if err != nil {
logger.Fatal("could not build exporter options:", err)
Expand All @@ -69,7 +74,8 @@ func main() {
run(c, &opts)
}

// run is the main thread
// run executes all necessary subroutines and servers, waits until signal, then
// closes all servers and subroutines.
func run(c common.Context, opts *common.Options) {
logger := c.Logger()
if c.Meta() == nil {
Expand Down Expand Up @@ -98,8 +104,10 @@ func run(c common.Context, opts *common.Options) {
signal.Reset()

logger.Info("shutting down webserver...")

ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
logger.Error("could not gracefully shutdown the web server: ", err)
}
Expand All @@ -116,15 +124,16 @@ func startWebRoutine(c common.Context, opts *common.Options) (meari.Server, erro
}

c.WG().Add(1)
go func() {
go func() { // nolint
defer c.WG().Done()

err := server.Start()
err := server.Serve()
if errors.Is(err, http.ErrServerClosed) {
logger.Info("webserver closed")
} else {
logger.Error("unexpected error: ", err)
}
}()

return server, nil
}
16 changes: 12 additions & 4 deletions exporters/exporters.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Package exporters contains all exporters to provide data delivery to the
// external systems such as Cloud Monitoring or simply stadard out.
package exporters

import (
Expand All @@ -14,16 +16,18 @@ type Exporter struct {

var _ common.Plugin = &Exporter{}

// Name implements common.Plugin
// Name implements common.Plugin.
func (p *Exporter) Name() string {
return p.name
}

// Run implements common.Plugin
// Run implements common.Plugin.
func (p *Exporter) Run(c common.Context, opts common.PluginOptions, ch chan interface{}) error {
return p.runFunc(c, opts, ch)
}

// StartAll executes runners for all exporters and returns number of successful
// executions.
func StartAll(c common.Context, opts *common.Options, ch chan interface{}) int {
logger := c.Logger().WithField("module", "exporter")
n := 0
Expand All @@ -32,17 +36,21 @@ func StartAll(c common.Context, opts *common.Options, ch chan interface{}) int {
x, _ := x.(common.Plugin)
if len(opts.Exporters) > 0 && !common.Contains(opts.Exporters, x.Name()) {
logger.Debugf("%v is not on the exporter list. skipping...", x.Name())
continue
continue //nolint
}

eopts := opts.ExporterOptions[x.Name()]
logger.Debugf("--- exporter: %s %v with %v", x.Name(), x, eopts)

logger.Infof("starting exporter %v...", x.Name())

if err := x.Run(c, eopts, ch); err != nil {
logger.Errorf("%s exporter was aborted: %v", x.Name(), err)
// TODO: should returns error?
logger.Errorf("%s exporter was aborted: %v", x.Name(), err)
} else {
n++
}
}

return n
}
23 changes: 19 additions & 4 deletions exporters/stackdriver.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const (
stackdriverExporterInterval = 1 * time.Minute
)

// RegisterStackdriver returns a new Exporter and it is used by StartAll().
func (*Exporter) RegisterStackdriver() *Exporter {
return &Exporter{
name: stackdriverExporter,
Expand All @@ -38,6 +39,11 @@ var (
lossRate = stats.Float64("ping_loss", "packet loss rate", "%")
)

// stackdriverRunner is a runner function for the Stackdriver Exporter.
// It starts a go routine for the exporter and returns error status.
// The go routine runs forever until the context canceled, and will
// send received data to the Google Cloud Platform Cloud Monitoring
// (previously known as Stackdriver).
func stackdriverRunner(c common.Context, _ common.PluginOptions, in chan interface{}) error {
logger := c.Logger().WithField("exporter", stackdriverExporter)

Expand All @@ -56,7 +62,7 @@ func stackdriverRunner(c common.Context, _ common.PluginOptions, in chan interfa
}

c.WG().Add(1)
go func() {
go func() { //nolint
defer c.WG().Done()

ticker := time.NewTicker(stackdriverExporterInterval)
Expand Down Expand Up @@ -88,14 +94,17 @@ func stackdriverRunner(c common.Context, _ common.PluginOptions, in chan interfa
}
logger.Infof("%s exporter exited", stackdriverExporter)
}()

return nil
}

// getReporter configures and returns a new instance of reporter if it runs
// on GCP. Currently, only GCE VM is supported for this feature.
func getReporter(c common.Context) (*reporter, error) {
// currently, stackdriver exporter is only suppored on the GCE instance
meta := c.Meta()
if meta == nil || meta.WhereAmI() != "Google" {
return nil, common.ErrorNotOnGCE
return nil, common.ErrNotOnGCE
}

return &reporter{
Expand All @@ -105,12 +114,13 @@ func getReporter(c common.Context) (*reporter, error) {
}, nil
}

// registerViews configures and registers the views.
func registerViews() error {
v := &view.View{
Name: "ping/rtt_average",
Measure: avgRttMs,
Description: "ping average rtt",
Aggregation: view.Distribution(0, 5, 10, 50, 100, 150, 200, 400),
Aggregation: view.Distribution(0, 5, 10, 50, 100, 150, 200, 400), //nolint
TagKeys: []tag.Key{
tag.MustNewKey("node"),
tag.MustNewKey("addr"),
Expand All @@ -126,17 +136,19 @@ func registerViews() error {
Name: "ping/packet_loss",
Measure: lossRate,
Description: "ping packet loss rate",
Aggregation: view.Distribution(0, 5, 10, 50, 100),
Aggregation: view.Distribution(0, 5, 10, 50, 100), //nolint
TagKeys: []tag.Key{
tag.MustNewKey("node"),
tag.MustNewKey("addr"),
tag.MustNewKey("zone"),
tag.MustNewKey("target"),
},
}

return view.Register(vLoss)
}

// createAndStartExporter starts the stackdriver exporter.
func createAndStartExporter() (*stackdriver.Exporter, error) {
// create exporter instance for stackdriver
exporter, err := stackdriver.NewExporter(stackdriver.Options{
Expand All @@ -152,9 +164,11 @@ func createAndStartExporter() (*stackdriver.Exporter, error) {
if err := exporter.StartMetricsExporter(); err != nil {
return nil, fmt.Errorf("could not start metric exporter: %w", err)
}

return exporter, nil
}

// recordPingMessage sends the given ping message to the Cloud Monitoring.
func recordPingMessage(r *reporter, m *bogo.PingMessage) error {
if err := stats.RecordWithTags(context.Background(),
[]tag.Mutator{
Expand All @@ -168,5 +182,6 @@ func recordPingMessage(r *reporter, m *bogo.PingMessage) error {
); err != nil {
return fmt.Errorf("could not send ping stat: %w", err)
}

return nil
}
Loading

0 comments on commit 38d0ef5

Please sign in to comment.