-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
appstate.go
284 lines (233 loc) · 6.58 KB
/
appstate.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"github.com/cosmos/relayer/v2/relayer"
"github.com/gofrs/flock"
"github.com/spf13/viper"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
// appState is the modifiable state of the application.
type appState struct {
// Log is the root logger of the application.
// Consumers are expected to store and use local copies of the logger
// after modifying with the .With method.
log *zap.Logger
viper *viper.Viper
homePath string
debug bool
config *Config
}
func (a *appState) configPath() string {
return path.Join(a.homePath, "config", "config.yaml")
}
// loadConfigFile reads config file into a.Config if file is present.
func (a *appState) loadConfigFile(ctx context.Context) error {
cfgPath := a.configPath()
if _, err := os.Stat(cfgPath); err != nil {
// don't return error if file doesn't exist
return nil
}
// read the config file bytes
file, err := os.ReadFile(cfgPath)
if err != nil {
return fmt.Errorf("error reading file: %w", err)
}
// unmarshall them into the wrapper struct
cfgWrapper := &ConfigInputWrapper{}
err = yaml.Unmarshal(file, cfgWrapper)
if err != nil {
return fmt.Errorf("error unmarshalling config: %w", err)
}
// retrieve the runtime configuration from the disk configuration.
newCfg, err := cfgWrapper.RuntimeConfig(ctx, a)
if err != nil {
return err
}
// validate runtime configuration
if err := newCfg.validateConfig(); err != nil {
return fmt.Errorf("error parsing chain config: %w", err)
}
// save runtime configuration in app state
a.config = newCfg
return nil
}
// addPathFromFile modifies a.config.Paths to include the content stored in the given file.
// If a non-nil error is returned, a.config.Paths is not modified.
func (a *appState) addPathFromFile(ctx context.Context, stderr io.Writer, file, name string) error {
if _, err := os.Stat(file); err != nil {
return err
}
byt, err := os.ReadFile(file)
if err != nil {
return err
}
p := &relayer.Path{}
if err = json.Unmarshal(byt, &p); err != nil {
return err
}
if err = a.config.ValidatePath(ctx, stderr, p); err != nil {
return err
}
return a.config.AddPath(name, p)
}
// addPathFromUserInput manually prompts the user to specify all the path details.
// It returns any input or validation errors.
// If the path was successfully added, it returns nil.
func (a *appState) addPathFromUserInput(
ctx context.Context,
stdin io.Reader,
stderr io.Writer,
src, dst, name string,
) error {
// TODO: confirm name is available before going through input.
var (
value string
err error
path = &relayer.Path{
Src: &relayer.PathEnd{
ChainID: src,
},
Dst: &relayer.PathEnd{
ChainID: dst,
},
}
)
fmt.Fprintf(stderr, "enter src(%s) client-id...\n", src)
if value, err = readLine(stdin); err != nil {
return err
}
path.Src.ClientID = value
if err = path.Src.Vclient(); err != nil {
return err
}
fmt.Fprintf(stderr, "enter src(%s) connection-id...\n", src)
if value, err = readLine(stdin); err != nil {
return err
}
path.Src.ConnectionID = value
if err = path.Src.Vconn(); err != nil {
return err
}
fmt.Fprintf(stderr, "enter dst(%s) client-id...\n", dst)
if value, err = readLine(stdin); err != nil {
return err
}
path.Dst.ClientID = value
if err = path.Dst.Vclient(); err != nil {
return err
}
fmt.Fprintf(stderr, "enter dst(%s) connection-id...\n", dst)
if value, err = readLine(stdin); err != nil {
return err
}
path.Dst.ConnectionID = value
if err = path.Dst.Vconn(); err != nil {
return err
}
if err := a.config.ValidatePath(ctx, stderr, path); err != nil {
return err
}
return a.config.AddPath(name, path)
}
func (a *appState) performConfigLockingOperation(ctx context.Context, operation func() error) error {
lockFilePath := path.Join(a.homePath, "config", "config.lock")
fileLock := flock.New(lockFilePath)
_, err := fileLock.TryLock()
if err != nil {
return fmt.Errorf("failed to acquire config lock: %w", err)
}
defer func() {
if err := fileLock.Unlock(); err != nil {
a.log.Error("error unlocking config file lock, please manually delete",
zap.String("filepath", lockFilePath),
)
}
}()
// load config from file and validate it. don't want to miss
// any changes that may have been made while unlocked.
if err := a.loadConfigFile(ctx); err != nil {
return fmt.Errorf("failed to initialize config from file: %w", err)
}
// perform the operation that requires config flock.
if err := operation(); err != nil {
return err
}
// validate config after changes have been made.
if err := a.config.validateConfig(); err != nil {
return fmt.Errorf("error parsing chain config: %w", err)
}
// marshal the new config
out, err := yaml.Marshal(a.config.Wrapped())
if err != nil {
return err
}
cfgPath := a.configPath()
// Overwrite the config file.
if err := os.WriteFile(cfgPath, out, 0600); err != nil {
return fmt.Errorf("failed to write config file at %s: %w", cfgPath, err)
}
return nil
}
// updatePathConfig overwrites the config file concurrently,
// locking to read, modify, then write the config.
func (a *appState) updatePathConfig(
ctx context.Context,
pathName string,
clientSrc, clientDst string,
connectionSrc, connectionDst string,
) error {
if pathName == "" {
return errors.New("empty path name not allowed")
}
return a.performConfigLockingOperation(ctx, func() error {
path, ok := a.config.Paths[pathName]
if !ok {
return fmt.Errorf("config does not exist for that path: %s", pathName)
}
if clientSrc != "" {
path.Src.ClientID = clientSrc
}
if clientDst != "" {
path.Dst.ClientID = clientDst
}
if connectionSrc != "" {
path.Src.ConnectionID = connectionSrc
}
if connectionDst != "" {
path.Dst.ConnectionID = connectionDst
}
return nil
})
}
func (a *appState) useKey(chainName, key string) error {
chain, exists := a.config.Chains[chainName]
if !exists {
return fmt.Errorf("chain %s not found in config", chainName)
}
cc := chain.ChainProvider
info, err := cc.ListAddresses()
if err != nil {
return err
}
value, exists := info[key]
currentValue := a.config.Chains[chainName].ChainProvider.Key()
if currentValue == key {
return fmt.Errorf("config is already using %s -> %s for %s", key, value, cc.ChainName())
}
if exists {
fmt.Printf("Config will now use %s -> %s for %s\n", key, value, cc.ChainName())
} else {
return fmt.Errorf("key %s does not exist for chain %s", key, cc.ChainName())
}
return a.performConfigLockingOperation(context.Background(), func() error {
a.config.Chains[chainName].ChainProvider.UseKey(key)
return nil
})
}