github.com/evrenkutar/randevent@v0.0.0-20210506235643-7d1e39a375e1/cmd/cmd.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 "time" 7 8 log "github.com/sirupsen/logrus" 9 "github.com/spf13/cobra" 10 "gopkg.in/confluentinc/confluent-kafka-go.v1/kafka" 11 ) 12 13 var ( 14 protoFile string 15 interval int32 16 rootCmd = &cobra.Command{ 17 Use: "randevent", 18 Short: "Randevent is random event pusher to kafka", 19 Run: func(cmd *cobra.Command, args []string) { 20 log.Info("hello friend!") 21 }, 22 } 23 genProtoCmd = &cobra.Command{ 24 Use: "generate", 25 Run: func(cmd *cobra.Command, args []string) { 26 err := GenerateProto(protoFile) 27 if err != nil { 28 log.Fatalf("proto generation failed: %d", err) 29 } 30 log.Info("proto files generated") 31 }, 32 } 33 emitCmd = &cobra.Command{ 34 Use: "emit", 35 Run: func(cmd *cobra.Command, args []string) { 36 emit() 37 }, 38 } 39 ) 40 41 func Execute() { 42 if err := rootCmd.Execute(); err != nil { 43 _, err := fmt.Fprintln(os.Stderr, err) 44 if err != nil { 45 return 46 } 47 os.Exit(1) 48 } 49 } 50 51 func init() { 52 genProtoCmd.PersistentFlags().StringVarP(&protoFile, "protofile", "p", "", "proto file to generate random events") 53 emitCmd.PersistentFlags().Int32VarP(&interval, "interval", "i", 50, "interval to generate") 54 err := genProtoCmd.MarkPersistentFlagRequired("protofile") 55 if err != nil { 56 return 57 } 58 rootCmd.AddCommand(emitCmd, genProtoCmd) 59 } 60 61 func emit() { 62 done := make(chan bool) 63 ticker := time.NewTicker(time.Duration(interval) * time.Millisecond) 64 kafkaProducer, err := kafka.NewProducer(&kafka.ConfigMap{ 65 "bootstrap.servers": "localhost", 66 }) 67 if err != nil { 68 log.Error("kafka producer can not be initialized") 69 panic(err) 70 } 71 72 emitter := Emitter{ 73 doneChan: make(chan bool), 74 tickChan: make(chan time.Time), 75 kafkaProducer: kafkaProducer, 76 } 77 go emitter.emit() 78 go start(done, ticker, emitter) 79 80 time.Sleep(10 * time.Second) 81 done <- true 82 }