-
Notifications
You must be signed in to change notification settings - Fork 1
/
scanner.go
211 lines (175 loc) · 5.25 KB
/
scanner.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package cosmovisor
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"cosmossdk.io/log"
upgradetypes "cosmossdk.io/x/upgrade/types"
)
type fileWatcher struct {
filename string // full path to a watched file
interval time.Duration
currentBin string
currentInfo upgradetypes.Plan
lastModTime time.Time
cancel chan bool
ticker *time.Ticker
needsUpdate bool
initialized bool
disableRecase bool
}
func newUpgradeFileWatcher(cfg *Config, logger log.Logger) (*fileWatcher, error) {
filename := cfg.UpgradeInfoFilePath()
if filename == "" {
return nil, errors.New("filename undefined")
}
filenameAbs, err := filepath.Abs(filename)
if err != nil {
return nil, fmt.Errorf("invalid path: %s must be a valid file path: %w", filename, err)
}
dirname := filepath.Dir(filename)
if info, err := os.Stat(dirname); err != nil || !info.IsDir() {
return nil, fmt.Errorf("invalid path: %s must be an existing directory: %w", dirname, err)
}
bin, err := cfg.CurrentBin()
if err != nil {
return nil, fmt.Errorf("error creating symlink to genesis: %w", err)
}
return &fileWatcher{
currentBin: bin,
filename: filenameAbs,
interval: cfg.PollInterval,
currentInfo: upgradetypes.Plan{},
lastModTime: time.Time{},
cancel: make(chan bool),
ticker: time.NewTicker(cfg.PollInterval),
needsUpdate: false,
initialized: false,
disableRecase: cfg.DisableRecase,
}, nil
}
func (fw *fileWatcher) Stop() {
close(fw.cancel)
}
// MonitorUpdate pools the filesystem to check for new upgrade currentInfo.
// currentName is the name of currently running upgrade. The check is rejected if it finds
// an upgrade with the same name.
func (fw *fileWatcher) MonitorUpdate(currentUpgrade upgradetypes.Plan) <-chan struct{} {
fw.ticker.Reset(fw.interval)
done := make(chan struct{})
fw.cancel = make(chan bool)
fw.needsUpdate = false
go func() {
for {
select {
case <-fw.ticker.C:
if fw.CheckUpdate(currentUpgrade) {
done <- struct{}{}
return
}
case <-fw.cancel:
return
}
}
}()
return done
}
// CheckUpdate reads update plan from file and checks if there is a new update request
// currentName is the name of currently running upgrade. The check is rejected if it finds
// an upgrade with the same name.
func (fw *fileWatcher) CheckUpdate(currentUpgrade upgradetypes.Plan) bool {
if fw.needsUpdate {
return true
}
stat, err := os.Stat(fw.filename)
if err != nil {
// file doesn't exists
return false
}
if !stat.ModTime().After(fw.lastModTime) {
return false
}
info, err := parseUpgradeInfoFile(fw.filename, fw.disableRecase)
if err != nil {
panic(fmt.Errorf("failed to parse upgrade info file: %w", err))
}
// file exist but too early in height
currentHeight, _ := fw.checkHeight()
if currentHeight != 0 && currentHeight < info.Height {
return false
}
if !fw.initialized {
// daemon has restarted
fw.initialized = true
fw.currentInfo = info
fw.lastModTime = stat.ModTime()
// Heuristic: Deamon has restarted, so we don't know if we successfully
// downloaded the upgrade or not. So we try to compare the running upgrade
// name (read from the cosmovisor file) with the upgrade info.
if !strings.EqualFold(currentUpgrade.Name, fw.currentInfo.Name) {
fw.needsUpdate = true
return true
}
}
if info.Height > fw.currentInfo.Height {
fw.currentInfo = info
fw.lastModTime = stat.ModTime()
fw.needsUpdate = true
return true
}
return false
}
// checkHeight checks if the current block height
func (fw *fileWatcher) checkHeight() (int64, error) {
// TODO(@julienrbrt) use `if !testing.Testing()` from Go 1.22
// The tests from `process_test.go`, which run only on linux, are failing when using `autod` that is a bash script.
// In production, the binary will always be an application with a status command, but in tests it isn't not.
if strings.HasSuffix(os.Args[0], ".test") {
return 0, nil
}
result, err := exec.Command(fw.currentBin, "status").Output() //nolint:gosec // we want to execute the status command
if err != nil {
return 0, err
}
type response struct {
SyncInfo struct {
LatestBlockHeight string `json:"latest_block_height"`
} `json:"SyncInfo"`
}
var resp response
if err := json.Unmarshal(result, &resp); err != nil {
return 0, err
}
if resp.SyncInfo.LatestBlockHeight == "" {
return 0, errors.New("latest block height is empty")
}
return strconv.ParseInt(resp.SyncInfo.LatestBlockHeight, 10, 64)
}
func parseUpgradeInfoFile(filename string, disableRecase bool) (upgradetypes.Plan, error) {
f, err := os.ReadFile(filename)
if err != nil {
return upgradetypes.Plan{}, err
}
if len(f) == 0 {
return upgradetypes.Plan{}, errors.New("empty upgrade-info.json")
}
var upgradePlan upgradetypes.Plan
if err := json.Unmarshal(f, &upgradePlan); err != nil {
return upgradetypes.Plan{}, err
}
// required values must be set
if err := upgradePlan.ValidateBasic(); err != nil {
return upgradetypes.Plan{}, fmt.Errorf("invalid upgrade-info.json content: %w, got: %v", err, upgradePlan)
}
// normalize name to prevent operator error in upgrade name case sensitivity errors.
if !disableRecase {
upgradePlan.Name = strings.ToLower(upgradePlan.Name)
}
return upgradePlan, err
}