This repository has been archived by the owner on Jun 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 225
/
prometheussource.go
177 lines (149 loc) · 5.98 KB
/
prometheussource.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
/*
Copyright 2019 The Knative Authors
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 reconciler
import (
"context"
"fmt"
"k8s.io/client-go/kubernetes"
"knative.dev/eventing/pkg/reconciler/source"
"knative.dev/pkg/controller"
"github.com/kelseyhightower/envconfig"
"github.com/robfig/cron"
"go.uber.org/zap"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
appsv1listers "k8s.io/client-go/listers/apps/v1"
"knative.dev/eventing-contrib/prometheus/pkg/reconciler/resources"
"knative.dev/pkg/apis"
duckv1 "knative.dev/pkg/apis/duck/v1"
"knative.dev/pkg/logging"
pkgreconciler "knative.dev/pkg/reconciler"
"knative.dev/pkg/resolver"
"knative.dev/eventing-contrib/prometheus/pkg/apis/sources/v1alpha1"
promreconciler "knative.dev/eventing-contrib/prometheus/pkg/client/injection/reconciler/sources/v1alpha1/prometheussource"
)
const (
// Name of the corev1.Events emitted from the reconciliation process
prometheussourceDeploymentCreated = "PrometheusSourceDeploymentCreated"
prometheussourceDeploymentUpdated = "PrometheusSourceDeploymentUpdated"
)
type envConfig struct {
Image string `envconfig:"PROMETHEUS_RA_IMAGE" required:"true"`
}
// Reconciler reconciles a PrometheusSource object
type Reconciler struct {
kubeClientSet kubernetes.Interface
// listers index properties about resources
deploymentLister appsv1listers.DeploymentLister
sinkResolver *resolver.URIResolver
configs *source.ConfigWatcher
}
var _ promreconciler.Interface = (*Reconciler)(nil)
func (r *Reconciler) ReconcileKind(ctx context.Context, source *v1alpha1.PrometheusSource) pkgreconciler.Event {
source.Status.InitializeConditions()
if source.Spec.Sink == nil {
source.Status.MarkNoSink("SinkMissing", "")
return fmt.Errorf("spec.sink missing")
}
dest := source.Spec.Sink.DeepCopy()
if dest.Ref != nil {
// To call URIFromDestination(), dest.Ref must have a Namespace. If there is
// no Namespace defined in dest.Ref, we will use the Namespace of the source
// as the Namespace of dest.Ref.
if dest.Ref.Namespace == "" {
dest.Ref.Namespace = source.GetNamespace()
}
}
sinkURI, err := r.sinkResolver.URIFromDestinationV1(*dest, source)
if err != nil {
source.Status.MarkNoSink("NotFound", "")
return err
}
source.Status.MarkSink(sinkURI)
_, err = cron.ParseStandard(source.Spec.Schedule)
if err != nil {
source.Status.MarkInvalidSchedule("Invalid", "Reason: "+err.Error())
return fmt.Errorf("invalid schedule: %v", err)
}
source.Status.MarkValidSchedule()
ra, err := r.createReceiveAdapter(ctx, source, sinkURI)
if err != nil {
logging.FromContext(ctx).Errorw("Unable to create the receive adapter", zap.Error(err))
return err
}
// Update source status// Update source status
source.Status.PropagateDeploymentAvailability(ra)
source.Status.CloudEventAttributes = []duckv1.CloudEventAttributes{{
Type: v1alpha1.PromQLPrometheusSourceEventType,
Source: r.makeEventSource(source),
}}
return nil
}
func (r *Reconciler) createReceiveAdapter(ctx context.Context, src *v1alpha1.PrometheusSource, sinkURI *apis.URL) (*appsv1.Deployment, error) {
eventSource := r.makeEventSource(src)
logging.FromContext(ctx).Debug("event source", zap.Any("source", eventSource))
env := &envConfig{}
if err := envconfig.Process("", env); err != nil {
logging.FromContext(ctx).Panicf("required environment variable is not defined: %v", err)
}
adapterArgs := resources.ReceiveAdapterArgs{
EventSource: eventSource,
Image: env.Image,
Source: src,
Labels: resources.Labels(src.Name),
SinkURI: sinkURI.String(),
AdditionalEnvs: r.configs.ToEnvVars(),
}
expected := resources.MakeReceiveAdapter(&adapterArgs)
ra, err := r.kubeClientSet.AppsV1().Deployments(src.Namespace).Get(expected.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
ra, err = r.kubeClientSet.AppsV1().Deployments(src.Namespace).Create(expected)
controller.GetEventRecorder(ctx).Eventf(src, corev1.EventTypeNormal, prometheussourceDeploymentCreated, "Deployment created, error: %v", err)
return ra, err
} else if err != nil {
return nil, fmt.Errorf("error getting receive adapter: %v", err)
} else if !metav1.IsControlledBy(ra, src) {
return nil, fmt.Errorf("deployment %q is not owned by PrometheusSource %q", ra.Name, src.Name)
} else if r.podSpecChanged(ra.Spec.Template.Spec, expected.Spec.Template.Spec) {
ra.Spec.Template.Spec = expected.Spec.Template.Spec
if ra, err = r.kubeClientSet.AppsV1().Deployments(src.Namespace).Update(ra); err != nil {
return ra, err
}
controller.GetEventRecorder(ctx).Eventf(src, corev1.EventTypeNormal, prometheussourceDeploymentUpdated, "Deployment updated")
return ra, nil
} else {
logging.FromContext(ctx).Debug("Reusing existing receive adapter", zap.Any("receiveAdapter", ra))
}
return ra, nil
}
func (r *Reconciler) podSpecChanged(oldPodSpec corev1.PodSpec, newPodSpec corev1.PodSpec) bool {
if !equality.Semantic.DeepDerivative(newPodSpec, oldPodSpec) {
return true
}
if len(oldPodSpec.Containers) != len(newPodSpec.Containers) {
return true
}
for i := range newPodSpec.Containers {
if !equality.Semantic.DeepEqual(newPodSpec.Containers[i].Env, oldPodSpec.Containers[i].Env) {
return true
}
}
return false
}
// makeEventSource computes the Cloud Event source attribute for the given source
func (r *Reconciler) makeEventSource(src *v1alpha1.PrometheusSource) string {
return src.Namespace + "/" + src.Name
}