logs_generator.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package logsgen
  14. import (
  15. "fmt"
  16. "time"
  17. "github.com/spf13/cobra"
  18. "k8s.io/apimachinery/pkg/util/rand"
  19. "k8s.io/klog"
  20. )
  21. var (
  22. httpMethods = []string{
  23. "GET",
  24. "POST",
  25. "PUT",
  26. }
  27. namespaces = []string{
  28. "kube-system",
  29. "default",
  30. "ns",
  31. }
  32. )
  33. // CmdLogsGenerator is used by agnhost Cobra.
  34. var CmdLogsGenerator = &cobra.Command{
  35. Use: "logs-generator",
  36. Short: "Outputs lines of logs to stdout uniformly",
  37. Long: "Outputs <linesTotal> lines of logs to stdout uniformly for <duration>",
  38. Args: cobra.MaximumNArgs(0),
  39. Run: generateLogs,
  40. }
  41. var (
  42. linesTotal int
  43. duration time.Duration
  44. )
  45. func init() {
  46. CmdLogsGenerator.Flags().IntVarP(&linesTotal, "log-lines-total", "t", 0, "Total lines that should be generated by the end of the run")
  47. CmdLogsGenerator.Flags().DurationVarP(&duration, "run-duration", "d", 0, "Total duration of the run")
  48. }
  49. // Outputs linesTotal lines of logs to stdout uniformly for duration
  50. func generateLogs(cmd *cobra.Command, args []string) {
  51. if linesTotal <= 0 {
  52. klog.Fatalf("Invalid total number of lines: %d", linesTotal)
  53. }
  54. if duration <= 0 {
  55. klog.Fatalf("Invalid duration: %v", duration)
  56. }
  57. delay := duration / time.Duration(linesTotal)
  58. ticker := time.NewTicker(delay)
  59. defer ticker.Stop()
  60. for id := 0; id < linesTotal; id++ {
  61. klog.Info(generateLogLine(id))
  62. <-ticker.C
  63. }
  64. }
  65. // Generates apiserver-like line with average length of 100 symbols
  66. func generateLogLine(id int) string {
  67. method := httpMethods[rand.Intn(len(httpMethods))]
  68. namespace := namespaces[rand.Intn(len(namespaces))]
  69. podName := rand.String(rand.IntnRange(3, 5))
  70. url := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s", namespace, podName)
  71. status := rand.IntnRange(200, 600)
  72. return fmt.Sprintf("%d %s %s %d", id, method, url, status)
  73. }