2022-08-30 10:30:43 -05:00
|
|
|
package process
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/grafana/grafana/pkg/plugins"
|
|
|
|
)
|
|
|
|
|
2023-09-12 03:34:12 -05:00
|
|
|
var (
|
|
|
|
keepPluginAliveTickerDuration = time.Second * 1
|
|
|
|
)
|
|
|
|
|
2023-08-16 03:46:00 -05:00
|
|
|
type Service struct{}
|
2022-08-30 10:30:43 -05:00
|
|
|
|
2023-08-16 03:46:00 -05:00
|
|
|
func ProvideService() *Service {
|
|
|
|
return &Service{}
|
2022-08-30 10:30:43 -05:00
|
|
|
}
|
|
|
|
|
2023-08-16 03:46:00 -05:00
|
|
|
func (*Service) Start(ctx context.Context, p *plugins.Plugin) error {
|
2022-08-30 10:30:43 -05:00
|
|
|
if !p.IsManaged() || !p.Backend || p.SignatureError != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-12 03:34:12 -05:00
|
|
|
if err := startPluginAndKeepItAlive(ctx, p); err != nil {
|
2022-08-30 10:30:43 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
p.Logger().Debug("Successfully started backend plugin process")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-08-16 03:46:00 -05:00
|
|
|
func (*Service) Stop(ctx context.Context, p *plugins.Plugin) error {
|
|
|
|
p.Logger().Debug("Stopping plugin process")
|
2022-08-30 10:30:43 -05:00
|
|
|
if err := p.Decommission(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := p.Stop(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-12 03:34:12 -05:00
|
|
|
func startPluginAndKeepItAlive(ctx context.Context, p *plugins.Plugin) error {
|
2022-08-30 10:30:43 -05:00
|
|
|
if err := p.Start(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-02 07:01:52 -05:00
|
|
|
if p.IsCorePlugin() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-12 03:34:12 -05:00
|
|
|
go func(p *plugins.Plugin) {
|
|
|
|
if err := keepPluginAlive(p); err != nil {
|
2022-08-30 10:30:43 -05:00
|
|
|
p.Logger().Error("Attempt to restart killed plugin process failed", "error", err)
|
|
|
|
}
|
2023-09-12 03:34:12 -05:00
|
|
|
}(p)
|
2022-08-30 10:30:43 -05:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-12 03:34:12 -05:00
|
|
|
// keepPluginAlive will restart the plugin if the process is killed or exits
|
|
|
|
func keepPluginAlive(p *plugins.Plugin) error {
|
|
|
|
ticker := time.NewTicker(keepPluginAliveTickerDuration)
|
2022-08-30 10:30:43 -05:00
|
|
|
|
|
|
|
for {
|
2023-09-12 03:34:12 -05:00
|
|
|
<-ticker.C
|
|
|
|
if p.IsDecommissioned() {
|
|
|
|
p.Logger().Debug("Plugin decommissioned")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if !p.Exited() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
p.Logger().Debug("Restarting plugin")
|
|
|
|
if err := p.Start(context.Background()); err != nil {
|
|
|
|
p.Logger().Error("Failed to restart plugin", "error", err)
|
|
|
|
continue
|
2022-08-30 10:30:43 -05:00
|
|
|
}
|
2023-09-12 03:34:12 -05:00
|
|
|
p.Logger().Debug("Plugin restarted")
|
2022-08-30 10:30:43 -05:00
|
|
|
}
|
|
|
|
}
|