/
plugin.go
73 lines (58 loc) · 1.77 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package clock
import (
"context"
"math/rand"
"time"
"go.uber.org/dig"
"github.com/iotaledger/hive.go/core/daemon"
"github.com/iotaledger/hive.go/core/generics/event"
"github.com/iotaledger/hive.go/core/node"
"github.com/iotaledger/hive.go/core/timeutil"
"github.com/iotaledger/goshimmer/packages/node/clock"
"github.com/iotaledger/goshimmer/packages/node/shutdown"
)
const (
maxTries = 3
syncInterval = 30 * time.Minute
)
// Plugin is the plugin instance of the clock plugin.
var Plugin *node.Plugin
func init() {
Plugin = node.NewPlugin("Clock", nil, node.Enabled, configure, run)
Plugin.Events.Init.Hook(event.NewClosure[*node.InitEvent](func(event *node.InitEvent) {
if err := event.Container.Provide(func() *node.Plugin {
return Plugin
}, dig.Name("clock")); err != nil {
Plugin.Panic(err)
}
}))
}
func configure(plugin *node.Plugin) {
if len(Parameters.NTPPools) == 0 {
plugin.LogFatalfAndExit("at least 1 NTP pool needs to be provided to synchronize the local clock.")
}
}
func run(plugin *node.Plugin) {
if err := daemon.BackgroundWorker(plugin.Name, func(ctx context.Context) {
// sync clock on startup
queryNTPPool()
// sync clock every 30min to counter drift
timeutil.NewTicker(queryNTPPool, syncInterval, ctx)
<-ctx.Done()
}, shutdown.PrioritySynchronization); err != nil {
plugin.Panicf("Failed to start as daemon: %s", err)
}
}
// queryNTPPool queries configured ntpPools for maxTries.
func queryNTPPool() {
Plugin.LogDebug("Synchronizing clock...")
for t := maxTries; t > 0; t-- {
index := rand.Int() % len(Parameters.NTPPools)
err := clock.FetchTimeOffset(Parameters.NTPPools[index])
if err == nil {
Plugin.LogDebug("Synchronizing clock... done")
return
}
}
Plugin.LogWarn("error while trying to sync clock")
}