-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
284 lines (266 loc) · 7.95 KB
/
main.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 main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sort"
"sync"
"github.com/AtlantPlatform/ethfw"
"github.com/AtlantPlatform/ethfw/sol"
cli "github.com/jawher/mow.cli"
log "github.com/sirupsen/logrus"
yaml "github.com/xlab/yamlx"
"github.com/AtlantPlatform/ethereum-playbook/executor"
"github.com/AtlantPlatform/ethereum-playbook/model"
)
var app = cli.App("ethereum-playbook", "Ethereum contracts deployment and management tool.")
var (
specPath = flag.String("f", "playbook.yml", "Custom path to playbook.yml spec file.")
solcPath = flag.String("s", "solc", "Name or path of Solidity compiler (solc, not solcjs).")
nodeGroup = flag.String("g", "genesis", "Inventory group name, corresponding to Geth nodes.")
printHelp = flag.Bool("h", false, "Print help.")
logLevel *int
)
func init() {
app.StringOpt("f", "playbook.yml", "Custom path to playbook.yml spec file.")
app.StringOpt("s", "solc", "Name or path of Solidity compiler (solc, not solcjs).")
app.StringOpt("g", "genesis", "Inventory group name, corresponding to Geth nodes.")
app.BoolOpt("h", false, "Print help.")
logLevel = app.IntOpt("l log-level", 4, "Sets the log level (default: info)")
}
func main() {
flag.Parse()
spec, ok := loadSpec()
if !ok {
if *printHelp {
flag.Usage()
os.Exit(0)
}
os.Exit(-1)
}
registerCommands(app, spec)
app.Before = func() {
if *printHelp {
app.PrintLongHelp()
os.Exit(0)
}
log.SetLevel(log.Level(*logLevel))
}
app.Action = func() {
validateSpec(spec, "", nil)
log.Infoln("spec validated")
}
if err := app.Run(os.Args); err != nil {
log.Fatalln(err)
}
}
func registerCommands(app *cli.Cli, spec *model.Spec) {
targetsNames := make([]string, 0, len(spec.Targets))
for name := range spec.Targets {
targetsNames = append(targetsNames, name)
}
sort.Strings(targetsNames)
for _, name := range targetsNames {
targetSpec, _ := spec.Targets.TargetSpec(name)
argCount := targetSpec.ArgCount(spec)
cmdNames := targetSpec.CmdNames()
desc := fmt.Sprintf("Target with %d commands, accepts %d args", len(cmdNames), argCount)
app.Command(name, desc, newTarget(spec, name, argCount))
}
callCmdNames := make([]string, 0, len(spec.CallCmds))
for name := range spec.CallCmds {
callCmdNames = append(callCmdNames, name)
}
sort.Strings(callCmdNames)
for _, name := range callCmdNames {
cmd, _ := spec.CallCmds.CallCmdSpec(name)
desc := cmd.Description
argCount := cmd.ArgCount()
if len(desc) == 0 {
desc = fmt.Sprintf("Generic CALL command, accepts %d args", argCount)
}
app.Command(name, desc, newCommand(spec, name, argCount))
}
viewCmdNames := make([]string, 0, len(spec.ViewCmds))
for name := range spec.ViewCmds {
viewCmdNames = append(viewCmdNames, name)
}
sort.Strings(viewCmdNames)
for _, name := range viewCmdNames {
cmd, _ := spec.ViewCmds.ViewCmdSpec(name)
desc := cmd.Description
argCount := cmd.ArgCount()
if len(desc) == 0 {
desc = fmt.Sprintf("Generic VIEW command, accepts %d args", argCount)
}
app.Command(name, desc, newCommand(spec, name, argCount))
}
writeCmdNames := make([]string, 0, len(spec.WriteCmds))
for name := range spec.WriteCmds {
writeCmdNames = append(writeCmdNames, name)
}
sort.Strings(writeCmdNames)
for _, name := range writeCmdNames {
cmd, _ := spec.WriteCmds.WriteCmdSpec(name)
desc := cmd.Description
argCount := cmd.ArgCount()
if len(desc) == 0 {
desc = fmt.Sprintf("Generic WRITE command, accepts %d args", argCount)
}
app.Command(name, desc, newCommand(spec, name, argCount))
}
}
func newCommand(spec *model.Spec, name string, argCount int) cli.CmdInitializer {
return func(cmd *cli.Cmd) {
args := make([]*string, argCount)
for i := 0; i < argCount; i++ {
args[i] = cmd.StringArg(fmt.Sprintf("ARG%d", i+1), "", fmt.Sprintf("Command argument $%d", i+1))
}
cmd.Action = func() {
appArgs := []string{name}
for _, arg := range args {
appArgs = append(appArgs, *arg)
}
ctx := validateSpec(spec, name, appArgs)
cmdLog := log.WithFields(log.Fields{
"command": name,
})
executor, err := executor.New(ctx, spec)
if err != nil {
cmdLog.WithError(err).Fatalln("failed to init executor")
}
results, found := executor.RunCommand(ctx, name)
if !found {
cmdLog.Fatalln("command not found")
}
exportResultsText(spec, results, "")
}
}
}
func newTarget(spec *model.Spec, name string, argCount int) cli.CmdInitializer {
return func(cmd *cli.Cmd) {
args := make([]*string, argCount)
for i := 0; i < argCount; i++ {
args[i] = cmd.StringArg(fmt.Sprintf("ARG%d", i+1), "", fmt.Sprintf("Target argument $%d", i+1))
}
cmd.Action = func() {
appArgs := []string{name}
for _, arg := range args {
appArgs = append(appArgs, *arg)
}
ctx := validateSpec(spec, name, appArgs)
cmdLog := log.WithFields(log.Fields{
"target": name,
})
exec, err := executor.New(ctx, spec)
if err != nil {
cmdLog.WithError(err).Fatalln("failed to init executor")
}
resultsC := make(chan []*executor.CommandResult, 100)
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
for results := range resultsC {
fmt.Printf("%s:\n", results[0].Name)
exportResultsText(spec, results, "\t")
}
}()
if found := exec.RunTarget(ctx, name, resultsC); !found {
cmdLog.Fatalln("target not found")
}
wg.Wait()
}
}
}
func loadSpec() (*model.Spec, bool) {
var spec *model.Spec
specLog := log.WithFields(log.Fields{
"filename": *specPath,
})
specData, err := ioutil.ReadFile(*specPath)
if err != nil {
specLog.WithError(err).Errorln("failed to load spec file")
return nil, false
}
if err := yaml.Unmarshal(specData, &spec); err != nil {
specLog.WithError(err).Errorln("failed to parse YAML in the spec file")
return nil, false
}
absSpecPath, err := filepath.Abs(*specPath)
if err != nil {
specLog.WithError(err).Errorln("failed to get absolute path of the spec file")
return nil, false
}
if spec.Config == nil {
spec.Config = model.DefaultConfigSpec
}
spec.Config.SpecDir = filepath.Dir(absSpecPath)
return spec, true
}
func validateSpec(spec *model.Spec, appCommand string, appArgs []string) model.AppContext {
specLog := log.WithFields(log.Fields{
"filename": *specPath,
})
var solcCompiler sol.Compiler
if spec.Contracts.UseSolc() {
solcAbsPath, err := exec.LookPath(*solcPath)
if err != nil {
solcAbsPath = *solcPath
}
compiler, err := sol.NewSolCompiler(solcAbsPath)
if err != nil {
specLog.WithError(err).Fatalln("spec uses .sol contracts, but no solc compiler found")
}
solcCompiler = compiler
}
ctx := model.NewAppContext(context.Background(), appCommand, appArgs, *nodeGroup,
spec.Config.SpecDir, solcCompiler, ethfw.NewKeyCache())
if ok := spec.Validate(ctx); !ok {
os.Exit(-1)
}
return ctx
}
func exportResultsText(spec *model.Spec, results []*executor.CommandResult, padding string) {
if len(results) == 0 {
text := jsonPaddedString(&ErrorObject{Error: "no results"}, padding)
fmt.Println(padding + text)
return
} else if len(results) == 1 {
if len(results[0].Wallet) == 0 {
if results[0].Error != nil {
text := jsonPaddedString(&ErrorObject{Error: results[0].Error.Error()}, padding)
fmt.Println(padding + text)
return
}
text := jsonPaddedString(prettify(results[0].Result), padding)
fmt.Println(padding + text)
return
}
}
for _, result := range results {
walletName := spec.Wallets.NameOf(result.Wallet)
if result.Error != nil {
text := jsonPaddedString(&ErrorObject{Error: result.Error.Error()}, padding)
fmt.Printf("%s%s (@%s): %s\n", padding, result.Wallet, walletName, text)
continue
}
text := jsonPaddedString(prettify(result.Result), padding)
fmt.Printf("%s%s (@%s): %s\n", padding, result.Wallet, walletName, text)
}
}
func jsonPaddedString(v interface{}, padding string) string {
vv, err := json.MarshalIndent(v, padding, "\t")
if err != nil {
panic(err)
}
return string(vv)
}
type ErrorObject struct {
Error string `json:"error"`
}