events.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 events
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/util/wait"
  21. clientset "k8s.io/client-go/kubernetes"
  22. )
  23. // WaitTimeoutForEvent waits the given timeout duration for an event to occur.
  24. func WaitTimeoutForEvent(c clientset.Interface, namespace, eventSelector, msg string, timeout time.Duration) error {
  25. interval := 2 * time.Second
  26. return wait.PollImmediate(interval, timeout, eventOccurred(c, namespace, eventSelector, msg))
  27. }
  28. func eventOccurred(c clientset.Interface, namespace, eventSelector, msg string) wait.ConditionFunc {
  29. options := metav1.ListOptions{FieldSelector: eventSelector}
  30. return func() (bool, error) {
  31. events, err := c.CoreV1().Events(namespace).List(context.TODO(), options)
  32. if err != nil {
  33. return false, fmt.Errorf("got error while getting events: %v", err)
  34. }
  35. for _, event := range events.Items {
  36. if strings.Contains(event.Message, msg) {
  37. return true, nil
  38. }
  39. }
  40. return false, nil
  41. }
  42. }