storj/private/lifecycle/group.go
Jeff Wendling 7999d24f81 all: use monkit v3
this commit updates our monkit dependency to the v3 version where
it outputs in an influx style. this makes discovery much easier
as many tools are built to look at it this way.

graphite and rothko will suffer some due to no longer being a tree
based on dots. hopefully time will exist to update rothko to
index based on the new metric format.

it adds an influx output for the statreceiver so that we can
write to influxdb v1 or v2 directly.

Change-Id: Iae9f9494a6d29cfbd1f932a5e71a891b490415ff
2020-02-05 23:53:17 +00:00

77 lines
1.5 KiB
Go

// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
// Package lifecycle allows controlling group of items.
package lifecycle
import (
"context"
"github.com/spacemonkeygo/monkit/v3"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"storj.io/common/errs2"
)
var mon = monkit.Package()
// Group implements a collection of items that have a
// concurrent start and are closed in reverse order.
type Group struct {
log *zap.Logger
items []Item
}
// Item is the lifecycle item that group runs and closes.
type Item struct {
Name string
Run func(ctx context.Context) error
Close func() error
}
// NewGroup creates a new group.
func NewGroup(log *zap.Logger) *Group {
return &Group{log: log}
}
// Add adds item to the group.
func (group *Group) Add(item Item) {
group.items = append(group.items, item)
}
// Run starts all items concurrently under group g.
func (group *Group) Run(ctx context.Context, g *errgroup.Group) {
defer mon.Task()(&ctx)(nil)
var started []string
for _, item := range group.items {
item := item
started = append(started, item.Name)
if item.Run == nil {
continue
}
g.Go(func() error {
return errs2.IgnoreCanceled(item.Run(ctx))
})
}
group.log.Debug("started", zap.Strings("items", started))
}
// Close closes all items in reverse order.
func (group *Group) Close() error {
var errlist errs.Group
for i := len(group.items) - 1; i >= 0; i-- {
item := group.items[i]
if item.Close == nil {
continue
}
errlist.Add(item.Close())
}
return errlist.Err()
}