...
1
16
17 package logsgen
18
19 import (
20 "fmt"
21 "time"
22
23 "github.com/spf13/cobra"
24
25 "k8s.io/apimachinery/pkg/util/rand"
26 "k8s.io/klog/v2"
27 )
28
29 var (
30 httpMethods = []string{
31 "GET",
32 "POST",
33 "PUT",
34 }
35 namespaces = []string{
36 "kube-system",
37 "default",
38 "ns",
39 }
40 )
41
42
43 var CmdLogsGenerator = &cobra.Command{
44 Use: "logs-generator",
45 Short: "Outputs lines of logs to stdout uniformly",
46 Long: "Outputs <linesTotal> lines of logs to stdout uniformly for <duration>",
47 Args: cobra.MaximumNArgs(0),
48 Run: generateLogs,
49 }
50
51 var (
52 linesTotal int
53 duration time.Duration
54 )
55
56 func init() {
57 CmdLogsGenerator.Flags().IntVarP(&linesTotal, "log-lines-total", "t", 0, "Total lines that should be generated by the end of the run")
58 CmdLogsGenerator.Flags().DurationVarP(&duration, "run-duration", "d", 0, "Total duration of the run")
59 }
60
61
62 func generateLogs(cmd *cobra.Command, args []string) {
63 if linesTotal <= 0 {
64 klog.Fatalf("Invalid total number of lines: %d", linesTotal)
65 }
66
67 if duration <= 0 {
68 klog.Fatalf("Invalid duration: %v", duration)
69 }
70
71 delay := duration / time.Duration(linesTotal)
72
73 ticker := time.NewTicker(delay)
74 defer ticker.Stop()
75 for id := 0; id < linesTotal; id++ {
76 klog.Info(generateLogLine(id))
77 <-ticker.C
78 }
79 }
80
81
82 func generateLogLine(id int) string {
83 method := httpMethods[rand.Intn(len(httpMethods))]
84 namespace := namespaces[rand.Intn(len(namespaces))]
85
86 podName := rand.String(rand.IntnRange(3, 5))
87 url := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s", namespace, podName)
88 status := rand.IntnRange(200, 600)
89
90 return fmt.Sprintf("%d %s %s %d", id, method, url, status)
91 }
92
View as plain text