-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
653 lines (634 loc) · 18.5 KB
/
main.go
File metadata and controls
653 lines (634 loc) · 18.5 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package main
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"os/user"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"time"
config "github.com/coccyx/gogen/internal"
log "github.com/coccyx/gogen/logger"
"github.com/coccyx/gogen/run"
"github.com/olekukonko/tablewriter"
"github.com/pkg/profile"
"gopkg.in/urfave/cli.v1"
yaml "gopkg.in/yaml.v2"
)
var c *config.Config
var envVarMap map[string]string
// Version is the version from ./VERSION set by govvv
var Version string
// BuildDate is the build date, set by govvv
var BuildDate string
// GitSummary is the git commit set by govvv
var GitSummary string
func init() {
envVarMap = map[string]string{
"info": "GOGEN_INFO",
"debug": "GOGEN_DEBUG",
"generators": "GOGEN_GENERATORS",
"outputters": "GOGEN_OUTPUTTERS",
"outputTemplate": "GOGEN_OUTPUTTEMPLATE",
"outputter": "GOGEN_OUT",
"filename": "GOGEN_FILENAME",
"topic": "GOGEN_TOPIC",
"url": "GOGEN_URL",
"splunkHECToken": "GOGEN_HEC_TOKEN",
"samplesDir": "GOGEN_SAMPLES_DIR",
"config": "GOGEN_CONFIG",
"addTime": "GOGEN_ADDTIME",
"bufferBytes": "GOGEN_BUFFERBYTES",
"cacheIntervals": "GOGEN_CACHEINTERVALS",
}
}
// Setup the running environment
func Setup(clic *cli.Context) {
if clic.Bool("debug") {
log.SetDebug(true)
} else if clic.Bool("info") {
log.SetInfo()
}
if len(clic.String("logFile")) > 0 {
log.SetOutput(os.ExpandEnv(clic.String("logFile")))
}
if clic.Bool("logJson") {
log.EnableJSONOutput()
}
if len(clic.String("configDir")) > 0 {
os.Setenv("GOGEN_CONFIG_DIR", clic.String("configDir"))
}
if len(clic.String("samplesDir")) > 0 {
os.Setenv("GOGEN_SAMPLES_DIR", clic.String("samplesDir"))
}
if len(clic.String("tempDir")) > 0 {
os.Setenv("GOGEN_TMPDIR", clic.String("tempDir"))
} else {
var tmpDir string
usr, err := user.Current()
if err != nil {
tmpDir = os.TempDir()
} else {
tmpDir = usr.HomeDir
}
os.Setenv("GOGEN_TMPDIR", tmpDir)
}
if len(clic.String("config")) > 0 {
cstr := clic.String("config")
ext := filepath.Ext(cstr)
if strings.HasPrefix(cstr, "http") || ext == ".yml" || ext == ".yaml" || ext == ".json" {
os.Setenv("GOGEN_FULLCONFIG", cstr)
} else {
config.PullFile(cstr, filepath.Join(os.ExpandEnv("$GOGEN_TMPDIR"), ".config.yml"))
config.ResetConfig()
os.Setenv("GOGEN_FULLCONFIG", filepath.Join(os.ExpandEnv("$GOGEN_TMPDIR"), ".config.yml"))
}
}
c = config.NewConfig()
if clic.Bool("utc") {
c.Global.UTC = true
}
if clic.Int("generators") > 0 {
log.Infof("Setting generators to %d", clic.Int("generators"))
c.Global.GeneratorWorkers = clic.Int("generators")
}
if clic.Int("outputters") > 0 {
log.Infof("Setting outputters to %d", clic.Int("outputters"))
c.Global.OutputWorkers = clic.Int("outputters")
}
if clic.Bool("addTime") {
log.Infof("Adding _time to all Samples")
c.Global.AddTime = true
}
if clic.Int("cacheIntervals") > 0 {
log.Infof("Setting cacheIntervals to %d", clic.Int("cacheIntervals"))
c.Global.CacheIntervals = clic.Int("cacheIntervals")
}
if clic.Bool("fullRetard") {
log.Infof("(⊙_ ☉) Going Full Retard (⊙_ ☉)")
c.Global.CacheIntervals = 2147483647
}
applySampleOutputOverrides(c, clic)
// Must call from runtime in case we are overriding AddTime or Facility from command line
c.SetupSystemTokens()
// log.Debugf("Global: %#v", c.Global)
// log.Debugf("Default Tokens: %#v", c.DefaultTokens)
// log.Debugf("Default Sample: %#v", c.DefaultSample)
// log.Debugf("Samples: %#v", c.Samples)
// log.Debugf("Pretty Values %# v\n", pretty.Formatter(c))
// j, _ := json.MarshalIndent(c, "", " ")
// log.Debugf("JSON Config: %s\n", j)
}
func applySampleOutputOverrides(c *config.Config, clic *cli.Context) {
for i := 0; i < len(c.Samples); i++ {
if len(clic.String("outputter")) > 0 {
log.Infof("Setting outputter to '%s'", clic.String("outputter"))
if clic.String("outputter") == "tcp" {
c.Samples[i].Output.Outputter = "network"
c.Samples[i].Output.Protocol = "tcp"
} else {
c.Samples[i].Output.Outputter = clic.String("outputter")
}
}
if len(clic.String("filename")) > 0 {
log.Infof("Setting filename to '%s'", clic.String("filename"))
c.Samples[i].Output.FileName = clic.String("filename")
}
if len(clic.String("topic")) > 0 {
log.Infof("Setting topic to '%s'", clic.String("topic"))
c.Samples[i].Output.Topic = clic.String("topic")
}
if len(clic.String("url")) > 0 {
log.Infof("Setting all endpoint urls to '%s'", clic.String("url"))
c.Samples[i].Output.Endpoints = []string{clic.String("url")}
}
if len(clic.String("splunkHECToken")) > 0 {
log.Infof("Setting HTTP Header to 'Authorization: Splunk %s'", clic.String("splunkHECToken"))
if c.Samples[i].Output.Headers == nil {
c.Samples[i].Output.Headers = make(map[string]string)
}
c.Samples[i].Output.Headers["Authorization"] = "Splunk " + clic.String("splunkHECToken")
}
if len(clic.String("outputTemplate")) > 0 {
log.Infof("Setting outputTemplate to '%s'", clic.String("outputTemplate"))
c.Samples[i].Output.OutputTemplate = clic.String("outputTemplate")
}
if clic.Int("bufferBytes") > 0 {
log.Infof("Setting bufferBytes to '%d'", clic.Int("bufferBytes"))
c.Samples[i].Output.BufferBytes = clic.Int("bufferBytes")
}
}
}
func table(l []config.GogenList) {
t := tablewriter.NewWriter(os.Stdout)
t.SetColWidth(132)
t.SetAutoWrapText(false)
t.SetHeader([]string{"Gogen", "Description"})
for _, li := range l {
t.Append([]string{li.Gogen, li.Description})
}
t.Render()
}
func main() {
defer func() {
os.Remove(filepath.Join(os.ExpandEnv("$GOGEN_TMPDIR"), ".config.yml"))
}()
if config.ProfileOn {
defer profile.Start(profile.CPUProfile, profile.ProfilePath(".")).Stop()
// defer profile.Start(profile.MemProfile, profile.ProfilePath(".")).Stop()
}
rand.Seed(time.Now().UnixNano())
app := cli.NewApp()
app.Name = "gogen"
app.Usage = "Generate data for demos and testing"
app.Version = Version
cli.VersionFlag = cli.BoolFlag{Name: "version"}
app.Compiled = time.Now()
app.Authors = []cli.Author{
cli.Author{
Name: "Clint Sharp",
Email: "clint@typhoon.org",
},
}
app.Commands = []cli.Command{
{
Name: "gen",
Usage: "Generate Events",
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: "sample, s",
Usage: "Only run sample `name`, can specify multiple",
},
cli.IntFlag{
Name: "count, c",
Usage: "Output `number` events",
},
cli.IntFlag{
Name: "interval, i",
Usage: "Output every `seconds` seconds",
},
cli.IntFlag{
Name: "endIntervals, ei",
Usage: "Only run from `number` intervals",
},
cli.StringFlag{
Name: "begin, b",
Usage: "Set begin time, in relative time syntax (e.g. -60m for minus 60 mins, now for now, etc)",
},
cli.StringFlag{
Name: "end, e",
Usage: "Set end time, in relative time syntax (e.g. -60m for minus 60 mins, now for now, etc)",
},
cli.BoolFlag{
Name: "realtime, r",
Usage: "Set to real time, don't stop until killed",
},
cli.BoolFlag{
Name: "wait, w",
Usage: "Wait between intervals when backfilling",
},
},
Action: func(clic *cli.Context) error {
if len(c.Samples) == 0 {
fmt.Printf("No samples configured, exiting\n")
os.Exit(1)
}
for i := 0; i < len(c.Samples); i++ {
if clic.Int("interval") > 0 {
log.Infof("Setting interval to %d for sample '%s'", clic.Int("interval"), c.Samples[i].Name)
c.Samples[i].Interval = clic.Int("interval")
}
if clic.Int("endIntervals") > 0 {
log.Infof("Setting endIntervals to %d", clic.Int("endIntervals"))
c.Samples[i].EndIntervals = clic.Int("endIntervals")
config.ParseBeginEnd(c.Samples[i])
}
if clic.Int("count") > 0 {
log.Infof("Setting count to %d for sample '%s'", clic.Int("count"), c.Samples[i].Name)
c.Samples[i].Count = clic.Int("count")
}
if len(clic.String("begin")) > 0 {
log.Infof("Setting begin to %s for sample '%s'", clic.String("begin"), c.Samples[i].Name)
c.Samples[i].Begin = clic.String("begin")
}
if len(clic.String("end")) > 0 {
log.Infof("Setting end to %s for sample '%s'", clic.String("end"), c.Samples[i].Name)
c.Samples[i].End = clic.String("end")
} else {
if clic.Bool("realtime") {
c.Samples[i].End = ""
}
}
if len(clic.String("begin")) > 0 || len(clic.String("end")) > 0 {
if clic.Int("endIntervals") == 0 {
c.Samples[i].EndIntervals = 0
}
config.ParseBeginEnd(c.Samples[i])
}
if clic.Bool("realtime") {
if clic.Int("endIntervals") == 0 {
c.Samples[i].EndIntervals = 0
}
if len(clic.String("begin")) == 0 {
c.Samples[i].Realtime = true
}
}
if clic.Bool("wait") {
c.Samples[i].Wait = true
}
}
samplesSlice := clic.StringSlice("sample")
samplesStr := strings.Join(samplesSlice, " ")
samplesMap := make(map[string]bool, len(samplesSlice))
for _, sampleName := range samplesSlice {
samplesMap[sampleName] = true
}
if len(samplesSlice) > 0 {
log.Infof("Generating only for samples '%s'", samplesStr)
matched := false
for i := 0; i < len(c.Samples); i++ {
if samplesMap[c.Samples[i].Name] {
matched = true
} else {
c.Samples[i].Disabled = true
}
}
if !matched {
log.Errorf("No sample matched for '%s'", samplesStr)
os.Exit(1)
}
c.Clean()
}
run.Run(c)
return nil
},
},
{
Name: "config",
Usage: "Print config to stdout",
Flags: []cli.Flag{
cli.StringFlag{Name: "format, f"},
cli.BoolFlag{
Name: "noexport, ne",
Usage: "Don't set to export",
},
},
Action: func(clic *cli.Context) error {
if !clic.Bool("noexport") {
os.Setenv("GOGEN_ALWAYS_REFRESH", "1")
os.Setenv("GOGEN_EXPORT", "1")
}
c = config.NewConfig()
var outb []byte
var err error
if clic.String("format") == "json" {
if outb, err = json.MarshalIndent(c, "", " "); err != nil {
log.Panicf("JSON output error: %v", err)
}
} else {
if outb, err = yaml.Marshal(c); err != nil {
log.Panicf("YAML output error: %v", err)
}
}
out := string(outb)
fmt.Print(out)
return nil
},
},
{
Name: "login",
Usage: "Login to GitHub",
Action: func(clic *cli.Context) error {
_ = config.NewGitHub(true)
return nil
},
},
{
Name: "list",
Usage: "List all published Gogens",
Action: func(clic *cli.Context) error {
fmt.Printf("Showing all Gogens:\n\n")
l, err := config.List()
if err != nil {
log.Fatalf("Error listing Gogens: %s", err)
}
table(l)
return nil
},
},
{
Name: "search",
Usage: "Search for Gogens",
Action: func(clic *cli.Context) error {
var q string
for _, a := range clic.Args() {
q += a + " "
}
q = strings.TrimRight(q, " ")
fmt.Printf("Returning results for search: \"%s\"\n\n", q)
l, err := config.Search(q)
if err != nil {
log.Fatalf("Error searching Gogens: %s", err)
}
if len(l) > 0 {
table(l)
} else {
fmt.Println(" No results found.")
}
return nil
},
},
{
Name: "info",
Usage: "Get info on a specific Gogen",
ArgsUsage: "[owner/name]",
Action: func(clic *cli.Context) error {
if len(clic.Args()) == 0 {
fmt.Println("Error: Must specify a Gogen in owner/name format")
os.Exit(1)
}
g, err := config.Get(clic.Args()[0])
if err != nil {
log.WithError(err).Fatalf("Error retrieving gogen")
}
fmt.Printf("Details for Gogen %s\n", g.Gogen)
fmt.Printf("------------------------------------------------------\n")
fmt.Printf("%15s : %s\n", "Gogen", g.Gogen)
fmt.Printf("%15s : %s\n", "Owner", g.Owner)
fmt.Printf("%15s : %s\n", "Name", g.Name)
fmt.Printf("%15s : %s\n", "Description", g.Description)
if len(g.Notes) > 0 {
fmt.Printf("Notes:\n")
fmt.Printf("------------------------------------------------------\n")
fmt.Printf("%s\n", g.Notes)
}
var event map[string]interface{}
var eventbytes []byte
err = json.Unmarshal([]byte(g.SampleEvent), &event)
if err != nil {
eventbytes = []byte(g.SampleEvent)
} else {
eventbytes, _ = json.MarshalIndent(event, "", " ")
}
fmt.Printf("Sample Event:\n")
fmt.Printf("------------------------------------------------------\n")
fmt.Printf("%s\n", string(eventbytes))
return nil
},
},
{
Name: "push",
Usage: "Push running config to Gogen sharing service",
ArgsUsage: "[name]\n\n" + "This will push your running config to the Gogen sharing API. This will publish the running config\n" +
"to the Gogen API.\n\n" +
"The [name] argument will be the name of the config published. The owner will be your GitHub ID.\n" +
"The entry in the database will get its Description and Notes from the first sample. If a mix is specified, it will\n" +
"attempt to push all referenced configs in the sample.",
Action: func(clic *cli.Context) error {
// config.ResetConfig()
// _ = config.NewConfig()
if len(clic.Args()) == 0 {
fmt.Println("Error: Must specify a name to publish this config")
os.Exit(1)
}
var r run.Runner
name := clic.Args().First()
owner := config.Push(name, r)
fmt.Printf("Push successful. Config: %s/%s\n", owner, name)
return nil
},
},
{
Name: "pull",
Usage: "Pull a config down for editing",
ArgsUsage: "[owner/name] [directory]",
Flags: []cli.Flag{
cli.BoolFlag{Name: "deconstruct, d"},
},
Action: func(clic *cli.Context) error {
if len(clic.Args()) == 0 {
fmt.Println("Error: Must specify a Gogen in owner/name format")
os.Exit(1)
} else if len(clic.Args()) < 2 {
fmt.Println("Error: Must specify a directory to place config files")
os.Exit(1)
}
config.Pull(clic.Args()[0], clic.Args()[1], clic.Bool("deconstruct"))
return nil
},
},
{
Name: "env",
Usage: "Outputs environment variables based on command line options to pass to eval $(gogen <foo> env)",
Action: func(clic *cli.Context) error {
var out string
for _, flag := range clic.GlobalFlagNames() {
if clic.GlobalIsSet(flag) {
out = fmt.Sprintf("%sexport %s=%s\n", out, envVarMap[flag], clic.GlobalString(flag))
}
}
fmt.Printf(out)
return nil
},
},
{
Name: "unsetenv",
Usage: "Outputs unset commands for environment variabels to clear config",
Action: func(clic *cli.Context) error {
var out string
for _, v := range envVarMap {
if len(os.Getenv(v)) > 0 {
out = fmt.Sprintf("%sunset %s\n", out, v)
}
}
fmt.Print(out)
return nil
},
},
{
Name: "version",
Usage: "Outputs version info",
Flags: []cli.Flag{
cli.BoolFlag{Name: "versiononly, v"},
cli.BoolFlag{Name: "buildinfo, b"},
},
Action: func(clic *cli.Context) error {
if clic.Bool("versiononly") {
fmt.Printf("%s", Version)
return nil
}
buildInfo, _ := debug.ReadBuildInfo()
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Build Date: %s\n", BuildDate)
fmt.Printf("Git Summary: %s\n", GitSummary)
fmt.Printf("Go Version: %s\n", runtime.Version())
if clic.Bool("buildinfo") {
fmt.Printf("Build Settings:\n")
for _, setting := range buildInfo.Settings {
fmt.Printf(" %s: %s\n", setting.Key, setting.Value)
}
}
return nil
},
},
}
app.Before = func(clic *cli.Context) error {
Setup(clic)
return nil
}
app.Action = func(clic *cli.Context) error {
clic.App.Command("gen").Run(clic)
return nil
}
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "utc, u",
Usage: "Outputs time in UTC",
EnvVar: "GOGEN_UTC",
},
cli.BoolFlag{
Name: "info, v",
Usage: "Sets info level logging",
EnvVar: "GOGEN_INFO",
},
cli.BoolFlag{
Name: "debug, vv",
Usage: "Sets debug level logging",
EnvVar: "GOGEN_DEBUG",
},
cli.IntFlag{
Name: "generators, g",
Usage: "Sets number of generator `threads`",
EnvVar: "GOGEN_GENERATORS",
},
cli.IntFlag{
Name: "outputters, os",
Usage: "Sets number of outputter `threads`",
EnvVar: "GOGEN_OUTPUTTERS",
},
cli.StringFlag{
Name: "outputTemplate, ot",
Usage: "Use output template (raw|csv|json|splunkhec||rfc3134|rfc5424|elasticsearch) for formatting output",
EnvVar: "GOGEN_OUTPUTTEMPLATE",
},
cli.StringFlag{
Name: "outputter, o",
Usage: "Use outputter (stdout|devnull|file|http|tcp) for output",
EnvVar: "GOGEN_OUT",
},
cli.StringFlag{
Name: "filename, f",
Usage: "Set `filename`, only usable with file output",
EnvVar: "GOGEN_FILENAME",
},
cli.StringFlag{
Name: "topic, t",
Usage: "Set `topic`, only usable with Kafka output",
EnvVar: "GOGEN_TOPIC",
},
cli.StringFlag{
Name: "url",
Usage: "Override all endpoint URLs to just `url` url",
EnvVar: "GOGEN_URL",
},
cli.StringFlag{
Name: "splunkHECToken",
Usage: "Set Authorization: Splunk <token> HTTP header for Splunk's HTTP Event Collector",
EnvVar: "GOGEN_HEC_TOKEN",
},
cli.StringFlag{
Name: "configDir, cd",
Usage: "Sets `directory` to search for config files, default '$GOGEN_HOME/config'",
EnvVar: "GOGEN_CONFIG_DIR",
},
cli.StringFlag{
Name: "samplesDir, sd",
Usage: "Sets `directory` to search for sample files, default 'config/samples'",
EnvVar: "GOGEN_SAMPLES_DIR",
},
cli.StringFlag{
Name: "tempDir, td",
Usage: "Sets `directory` to store temporary files, default $HOME",
EnvVar: "GOGEN_TMPDIR",
},
cli.StringFlag{
Name: "config, c",
Usage: "`Path` or URL to a full config",
EnvVar: "GOGEN_CONFIG",
},
cli.BoolFlag{
Name: "addTime, at",
Usage: "Always add _time field, no matter of outputTemplate",
EnvVar: "GOGEN_ADDTIME",
},
cli.IntFlag{
Name: "bufferBytes, bb",
Usage: "Sets size of output buffers",
EnvVar: "GOGEN_BUFFERBYTES",
},
cli.StringFlag{
Name: "logFile, lf",
Usage: "Output internal logs to a file instead of stderr",
EnvVar: "GOGEN_LOGFILE",
},
cli.BoolFlag{
Name: "logJson, lj",
Usage: "Output internal logs as JSON instead of human readable",
EnvVar: "GOGEN_LOGJSON",
},
cli.IntFlag{
Name: "cacheIntervals, ci",
Usage: "Number of intervals to cache generation",
EnvVar: "GOGEN_CACHEINTERVALS",
},
cli.BoolFlag{
Name: "fullRetard, fr",
Usage: "Go Full Retard",
Hidden: true,
},
}
app.Run(os.Args)
}