This repository has been archived by the owner on Jun 19, 2022. It is now read-only.
/
lifecycle.go
224 lines (194 loc) · 6.69 KB
/
lifecycle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lib
import (
"context"
"errors"
"fmt"
"log"
"strings"
"sync"
"testing"
"time"
"google.golang.org/api/iterator"
monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"knative.dev/eventing/test/lib"
pkgTest "knative.dev/pkg/test"
knativegcp "github.com/google/knative-gcp/pkg/client/clientset/versioned"
"github.com/google/knative-gcp/test/e2e/lib/metrics"
"github.com/google/knative-gcp/test/e2e/lib/operations"
)
// Setup runs the Setup in the common eventing test framework.
func Setup(t *testing.T, runInParallel, workloadIdentity bool) *Client {
client, err := newClient(pkgTest.Flags.Kubeconfig, pkgTest.Flags.Cluster)
if err != nil {
t.Fatalf("Failed to initialize client for Knative GCP: %v", err)
}
coreClient := lib.Setup(t, runInParallel)
client.Core = coreClient
client.Namespace = coreClient.Namespace
client.Tracker = coreClient.Tracker
client.T = t
GetCredential(coreClient, workloadIdentity)
return client
}
func newClient(configPath string, clusterName string) (*Client, error) {
config, err := pkgTest.BuildClientConfig(configPath, clusterName)
if err != nil {
return nil, err
}
kgc, err := knativegcp.NewForConfig(config)
if err != nil {
return nil, err
}
return &Client{KnativeGCP: kgc}, nil
}
// TearDown runs the TearDown in the common eventing test framework.
func TearDown(client *Client) {
lib.TearDown(client.Core)
}
// Client holds instances of interfaces for making requests to Knative.
type Client struct {
Core *lib.Client
KnativeGCP *knativegcp.Clientset
Namespace string
T *testing.T
Tracker *lib.Tracker
}
var setStackDriverConfigOnce = sync.Once{}
func (c *Client) SetupStackDriverMetrics(t *testing.T) {
setStackDriverConfigOnce.Do(func() {
err := c.Core.Kube.UpdateConfigMap("cloud-run-events", "config-observability", map[string]string{
"metrics.allow-stackdriver-custom-metrics": "true",
"metrics.backend-destination": "stackdriver",
"metrics.stackdriver-custom-metrics-subdomain": "cloud.google.com",
"metrics.reporting-period-seconds": "60",
})
if err != nil {
t.Fatalf("Unable to set the ConfigMap: %v", err)
}
})
}
const (
interval = 1 * time.Second
timeout = 5 * time.Minute
)
// TODO(chizhg): move this function to knative/pkg/test or knative/eventing/test
// WaitForResourceReady waits until the specified resource in the given namespace are ready.
func (c *Client) WaitUntilJobDone(namespace, name string) (string, error) {
cc := c.Core
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
job, err := cc.Kube.Kube.BatchV1().Jobs(namespace).Get(name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
log.Println(namespace, name, "not found", err)
// keep polling
return false, nil
}
return false, err
}
return operations.IsJobComplete(job), nil
})
if err != nil {
return "", err
}
// poll until the pod is terminated.
err = wait.PollImmediate(interval, timeout, func() (bool, error) {
pod, err := operations.GetJobPodByJobName(context.TODO(), cc.Kube.Kube, namespace, name)
if err != nil {
if apierrors.IsNotFound(err) {
log.Println(namespace, name, "not found", err)
// keep polling
return false, nil
}
return false, err
}
if pod != nil {
for _, cs := range pod.Status.ContainerStatuses {
if cs.State.Terminated != nil {
return true, nil
}
}
}
return false, nil
})
if err != nil {
return "", err
}
pod, err := operations.GetJobPodByJobName(context.TODO(), cc.Kube.Kube, namespace, name)
if err != nil {
return "", err
}
return operations.GetFirstTerminationMessage(pod), nil
}
// TODO(chizhg): move this function to knative/pkg/test or knative/eventing/test
func (c *Client) LogsFor(namespace, name string, tm *metav1.TypeMeta) (string, error) {
cc := c.Core
// Get all pods in this namespace.
pods, err := cc.Kube.Kube.CoreV1().Pods(namespace).List(metav1.ListOptions{})
if err != nil {
return "", err
}
logs := make([]string, 0)
// Look for a pod with the name that was passed in inside the pod name.
for _, pod := range pods.Items {
if strings.HasPrefix(pod.Name, name) {
// Collect all the logs from all the containers for this pod.
if l, err := cc.Kube.Kube.CoreV1().Pods(namespace).GetLogs(pod.Name, &corev1.PodLogOptions{}).DoRaw(); err != nil {
logs = append(logs, err.Error())
} else {
logs = append(logs, string(l))
}
}
}
// Did we find a match like the given name?
if len(logs) == 0 {
return "", fmt.Errorf(`pod for "%s/%s" [%s] not found`, namespace, name, tm.String())
}
return strings.Join(logs, "\n"), nil
}
// TODO make this function more generic.
func (c *Client) StackDriverEventCountMetricFor(namespace, projectID, filter string) (*int64, error) {
metricClient, err := metrics.NewStackDriverMetricClient()
if err != nil {
return nil, fmt.Errorf("failed to create stackdriver metric client: %v", err)
}
// TODO make times configurable if needed.
metricRequest := metrics.NewStackDriverListTimeSeriesRequest(projectID,
metrics.WithStackDriverFilter(filter),
// Starting 5 minutes back until now.
metrics.WithStackDriverInterval(time.Now().Add(-5*time.Minute).Unix(), time.Now().Unix()),
// Delta counts aggregated every 2 minutes.
// We aggregate for count as other aggregations will give higher values.
// The reason is that PubSub upon an error, will retry, thus we will be recording multiple events.
metrics.WithStackDriverAlignmentPeriod(2*int64(time.Minute.Seconds())),
metrics.WithStackDriverPerSeriesAligner(monitoringpb.Aggregation_ALIGN_DELTA),
metrics.WithStackDriverCrossSeriesReducer(monitoringpb.Aggregation_REDUCE_COUNT),
)
it := metricClient.ListTimeSeries(context.TODO(), metricRequest)
for {
res, err := it.Next()
if err == iterator.Done {
return nil, errors.New("no metric reported")
}
if err != nil {
return nil, fmt.Errorf("failed to iterate over result: %v", err)
}
actualCount := res.GetPoints()[0].GetValue().GetInt64Value()
return &actualCount, nil
}
}