-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmain.go
360 lines (314 loc) · 9.79 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"sort"
"strings"
"time"
"github.com/ferranbt/builder-playground/internal"
"github.com/spf13/cobra"
)
var outputFlag string
var genesisDelayFlag uint64
var withOverrides []string
var watchdog bool
var dryRun bool
var interactive bool
var timeout time.Duration
var logLevelFlag string
var bindExternal bool
var withPrometheus bool
var networkName string
var rootCmd = &cobra.Command{
Use: "playground",
Short: "",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
return nil
},
}
var cookCmd = &cobra.Command{
Use: "cook",
Short: "Cook a recipe",
RunE: func(cmd *cobra.Command, args []string) error {
recipeNames := []string{}
for _, recipe := range recipes {
recipeNames = append(recipeNames, recipe.Name())
}
return fmt.Errorf("please specify a recipe to cook. Available recipes: %s", recipeNames)
},
}
var artifactsCmd = &cobra.Command{
Use: "artifacts",
Short: "List available artifacts",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("please specify a service name")
}
serviceName := args[0]
component := internal.FindComponent(serviceName)
if component == nil {
return fmt.Errorf("service %s not found", serviceName)
}
releaseService, ok := component.(internal.ReleaseService)
if !ok {
return fmt.Errorf("service %s is not a release service", serviceName)
}
output := outputFlag
if output == "" {
homeDir, err := internal.GetHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
output = homeDir
}
location, err := internal.DownloadRelease(output, releaseService.ReleaseArtifact())
if err != nil {
return fmt.Errorf("failed to download release: %w", err)
}
fmt.Println(location)
return nil
},
}
var artifactsAllCmd = &cobra.Command{
Use: "artifacts-all",
Short: "Download all the artifacts available in the catalog (Used for testing purposes)",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("Downloading all artifacts...")
output := outputFlag
if output == "" {
homeDir, err := internal.GetHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
output = homeDir
}
for _, component := range internal.Components {
releaseService, ok := component.(internal.ReleaseService)
if !ok {
continue
}
location, err := internal.DownloadRelease(output, releaseService.ReleaseArtifact())
if err != nil {
return fmt.Errorf("failed to download release: %w", err)
}
// make sure the artifact is valid to be executed on this platform
log.Printf("Downloaded %s to %s\n", releaseService.ReleaseArtifact().Name, location)
if err := isExecutableValid(location); err != nil {
return fmt.Errorf("failed to check if artifact is valid: %w", err)
}
}
return nil
},
}
var inspectCmd = &cobra.Command{
Use: "inspect",
Short: "Inspect a connection between two services",
RunE: func(cmd *cobra.Command, args []string) error {
// two arguments, the name of the service and the name of the connection
if len(args) != 2 {
return fmt.Errorf("please specify a service name and a connection name")
}
serviceName := args[0]
connectionName := args[1]
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-sig
cancel()
}()
if err := internal.Inspect(ctx, serviceName, connectionName); err != nil {
return fmt.Errorf("failed to inspect connection: %w", err)
}
return nil
},
}
var recipes = []internal.Recipe{
&internal.L1Recipe{},
&internal.OpRecipe{},
&internal.BuilderNetRecipe{},
}
func main() {
for _, recipe := range recipes {
recipeCmd := &cobra.Command{
Use: recipe.Name(),
Short: recipe.Description(),
RunE: func(cmd *cobra.Command, args []string) error {
return runIt(recipe)
},
}
// add the flags from the recipe
recipeCmd.Flags().AddFlagSet(recipe.Flags())
// add the common flags
recipeCmd.Flags().StringVar(&outputFlag, "output", "", "Output folder for the artifacts")
recipeCmd.Flags().BoolVar(&watchdog, "watchdog", false, "enable watchdog")
recipeCmd.Flags().StringArrayVar(&withOverrides, "override", []string{}, "override a service's config")
recipeCmd.Flags().BoolVar(&dryRun, "dry-run", false, "dry run the recipe")
recipeCmd.Flags().BoolVar(&dryRun, "mise-en-place", false, "mise en place mode")
recipeCmd.Flags().Uint64Var(&genesisDelayFlag, "genesis-delay", internal.MinimumGenesisDelay, "")
recipeCmd.Flags().BoolVar(&interactive, "interactive", false, "interactive mode")
recipeCmd.Flags().DurationVar(&timeout, "timeout", 0, "") // Used for CI
recipeCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "log level")
recipeCmd.Flags().BoolVar(&bindExternal, "bind-external", false, "bind host ports to external interface")
recipeCmd.Flags().BoolVar(&withPrometheus, "with-prometheus", false, "whether to gather the Prometheus metrics")
recipeCmd.Flags().StringVar(&networkName, "network", "", "network name")
cookCmd.AddCommand(recipeCmd)
}
// reuse the same output flag for the artifacts command
artifactsCmd.Flags().StringVar(&outputFlag, "output", "", "Output folder for the artifacts")
artifactsAllCmd.Flags().StringVar(&outputFlag, "output", "", "Output folder for the artifacts")
rootCmd.AddCommand(cookCmd)
rootCmd.AddCommand(artifactsCmd)
rootCmd.AddCommand(artifactsAllCmd)
rootCmd.AddCommand(inspectCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func runIt(recipe internal.Recipe) error {
var logLevel internal.LogLevel
if err := logLevel.Unmarshal(logLevelFlag); err != nil {
return fmt.Errorf("failed to parse log level: %w", err)
}
log.Printf("Log level: %s\n", logLevel)
// parse the overrides
overrides := map[string]string{}
for _, val := range withOverrides {
parts := strings.SplitN(val, "=", 2)
if len(parts) != 2 {
return fmt.Errorf("invalid override format: %s, expected service=val", val)
}
overrides[parts[0]] = parts[1]
}
builder := recipe.Artifacts()
builder.OutputDir(outputFlag)
builder.GenesisDelay(genesisDelayFlag)
artifacts, err := builder.Build()
if err != nil {
return err
}
svcManager := recipe.Apply(&internal.ExContext{LogLevel: logLevel}, artifacts)
if err := svcManager.Validate(); err != nil {
return fmt.Errorf("failed to validate manifest: %w", err)
}
// generate the dot graph
dotGraph := svcManager.GenerateDotGraph()
if err := artifacts.Out.WriteFile("graph.dot", dotGraph); err != nil {
return err
}
if withPrometheus {
if err := internal.CreatePrometheusServices(svcManager, artifacts.Out); err != nil {
return fmt.Errorf("failed to create prometheus services: %w", err)
}
}
if dryRun {
return nil
}
// validate that override is being applied to a service in the manifest
for k := range overrides {
if _, ok := svcManager.GetService(k); !ok {
return fmt.Errorf("service '%s' in override not found in manifest", k)
}
}
dockerRunner, err := internal.NewLocalRunner(artifacts.Out, svcManager, overrides, interactive, !bindExternal, networkName)
if err != nil {
return fmt.Errorf("failed to create docker runner: %w", err)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-sig
cancel()
}()
if err := dockerRunner.Run(); err != nil {
dockerRunner.Stop()
return fmt.Errorf("failed to run docker: %w", err)
}
if !interactive {
// print services info
fmt.Printf("\n========= Services started =========\n")
for _, ss := range svcManager.Services() {
ports := ss.Ports()
sort.Slice(ports, func(i, j int) bool {
return ports[i].Name < ports[j].Name
})
portsStr := []string{}
for _, p := range ports {
protocol := ""
if p.Protocol == internal.ProtocolUDP {
protocol = "/udp"
}
portsStr = append(portsStr, fmt.Sprintf("%s: %d/%d%s", p.Name, p.Port, p.HostPort, protocol))
}
fmt.Printf("- %s (%s)\n", ss.Name, strings.Join(portsStr, ", "))
}
}
if err := dockerRunner.WaitForReady(ctx, 20*time.Second); err != nil {
dockerRunner.Stop()
return fmt.Errorf("failed to wait for service readiness: %w", err)
}
if err := svcManager.CompleteReady(); err != nil {
dockerRunner.Stop()
return fmt.Errorf("failed to complete ready: %w", err)
}
// get the output from the recipe
output := recipe.Output(svcManager)
if len(output) > 0 {
fmt.Printf("\n========= Output =========\n")
for k, v := range output {
fmt.Printf("- %s: %v\n", k, v)
}
}
watchdogErr := make(chan error, 1)
if watchdog {
go func() {
if err := internal.RunWatchdog(svcManager); err != nil {
watchdogErr <- fmt.Errorf("watchdog failed: %w", err)
}
}()
}
var timerCh <-chan time.Time
if timeout > 0 {
timerCh = time.After(timeout)
}
select {
case <-ctx.Done():
fmt.Println("Stopping...")
case err := <-dockerRunner.ExitErr():
fmt.Println("Service failed:", err)
case err := <-watchdogErr:
fmt.Println("Watchdog failed:", err)
case <-timerCh:
fmt.Println("Timeout reached")
}
if err := dockerRunner.Stop(); err != nil {
return fmt.Errorf("failed to stop docker: %w", err)
}
return nil
}
func isExecutableValid(path string) error {
// First check if file exists
_, err := os.Stat(path)
if err != nil {
return fmt.Errorf("file does not exist or is inaccessible: %w", err)
}
// Try to execute with a harmless flag or in a way that won't run the main program
cmd := exec.Command(path, "--version")
// Redirect output to /dev/null
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Start(); err != nil {
return fmt.Errorf("cannot start executable: %w", err)
}
// Immediately kill the process since we just want to test if it starts
cmd.Process.Kill()
return nil
}