1/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package events
18
19import (
20	"context"
21	"fmt"
22	"strings"
23	"time"
24
25	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26	"k8s.io/apimachinery/pkg/util/wait"
27	clientset "k8s.io/client-go/kubernetes"
28)
29
30// Action is a function to be performed by the system.
31type Action func() error
32
33// WaitTimeoutForEvent waits the given timeout duration for an event to occur.
34// Please note delivery of events is not guaranteed. Asserting on events can lead to flaky tests.
35func WaitTimeoutForEvent(c clientset.Interface, namespace, eventSelector, msg string, timeout time.Duration) error {
36	interval := 2 * time.Second
37	return wait.PollImmediate(interval, timeout, eventOccurred(c, namespace, eventSelector, msg))
38}
39
40func eventOccurred(c clientset.Interface, namespace, eventSelector, msg string) wait.ConditionFunc {
41	options := metav1.ListOptions{FieldSelector: eventSelector}
42	return func() (bool, error) {
43		events, err := c.CoreV1().Events(namespace).List(context.TODO(), options)
44		if err != nil {
45			return false, fmt.Errorf("got error while getting events: %v", err)
46		}
47		for _, event := range events.Items {
48			if strings.Contains(event.Message, msg) {
49				return true, nil
50			}
51		}
52		return false, nil
53	}
54}
55