forked from knative/eventing
/
adapter.go
256 lines (218 loc) · 6.66 KB
/
adapter.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
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 apiserver
import (
"context"
"flag"
"fmt"
"strings"
"time"
cloudevents "github.com/cloudevents/sdk-go"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"knative.dev/eventing/pkg/adapter"
"knative.dev/pkg/logging"
"knative.dev/pkg/source"
)
var (
masterURL = flag.String("master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
kubeconfig = flag.String("kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
)
type StringList []string
// Decode splits list of strings separated by '|',
// overriding the default comma separator which is
// a valid label selector character.
func (s *StringList) Decode(value string) error {
*s = strings.Split(value, ";")
return nil
}
type envConfig struct {
adapter.EnvConfig
Mode string `envconfig:"MODE"`
ApiVersion StringList `split_words:"true" required:"true"`
Kind StringList `required:"true"`
Controller []bool `required:"true"`
LabelSelector StringList `envconfig:"SELECTOR" required:"true"`
OwnerApiVersion StringList `envconfig:"OWNER_API_VERSION" required:"true"`
OwnerKind StringList `envconfig:"OWNER_KIND" required:"true"`
Name string `envconfig:"NAME" required:"true"`
}
const (
// RefMode produces payloads of ObjectReference
RefMode = "Ref"
// ResourceMode produces payloads of ResourceEvent
ResourceMode = "Resource"
resourceGroup = "apiserversources.sources.eventing.knative.dev"
)
// GVRC is a combination of GroupVersionResource, Controller flag, LabelSelector and OwnerRef
type GVRC struct {
GVR schema.GroupVersionResource
Controller bool
LabelSelector string
OwnerApiVersion string
OwnerKind string
}
type apiServerAdapter struct {
namespace string
ce cloudevents.Client
reporter source.StatsReporter
logger *zap.SugaredLogger
gvrcs []GVRC
k8s dynamic.Interface
source string
mode string
delegate eventDelegate
name string
}
func NewEnvConfig() adapter.EnvConfigAccessor {
return &envConfig{}
}
func NewAdapter(ctx context.Context, processed adapter.EnvConfigAccessor, ceClient cloudevents.Client, reporter source.StatsReporter) adapter.Adapter {
logger := logging.FromContext(ctx)
env := processed.(*envConfig)
cfg, err := clientcmd.BuildConfigFromFlags(*masterURL, *kubeconfig)
if err != nil {
logger.Fatal("error building kubeconfig", zap.Error(err))
}
client, err := dynamic.NewForConfig(cfg)
if err != nil {
logger.Fatal("error building dynamic client", zap.Error(err))
}
gvrcs := []GVRC(nil)
for i, apiVersion := range env.ApiVersion {
kind := env.Kind[i]
controlled := env.Controller[i]
selector := env.LabelSelector[i]
ownerApiVersion := env.OwnerApiVersion[i]
ownerKind := env.OwnerKind[i]
gv, err := schema.ParseGroupVersion(apiVersion)
if err != nil {
logger.Fatal("error parsing APIVersion", zap.Error(err))
}
// TODO: pass down the resource and the kind so we do not have to guess.
gvr, _ := meta.UnsafeGuessKindToResource(schema.GroupVersionKind{Kind: kind, Group: gv.Group, Version: gv.Version})
gvrcs = append(gvrcs, GVRC{
GVR: gvr,
Controller: controlled,
LabelSelector: selector,
OwnerApiVersion: ownerApiVersion,
OwnerKind: ownerKind,
})
}
mode := env.Mode
switch env.Mode {
case ResourceMode, RefMode:
// ok
default:
logger.Warn("unknown mode ", mode)
mode = RefMode
logger.Warn("defaulting mode to ", mode)
}
a := &apiServerAdapter{
k8s: client,
ce: ceClient,
source: cfg.Host,
logger: logger,
gvrcs: gvrcs,
namespace: env.Namespace,
mode: mode,
reporter: reporter,
name: env.Name,
}
return a
}
type eventDelegate interface {
cache.Store
addControllerWatch(gvr schema.GroupVersionResource)
}
func (a *apiServerAdapter) Start(stopCh <-chan struct{}) error {
// Local stop channel.
stop := make(chan struct{})
resyncPeriod := time.Duration(10 * time.Hour)
var d eventDelegate
switch a.mode {
case ResourceMode:
d = &resource{
ce: a.ce,
source: a.source,
logger: a.logger,
reporter: a.reporter,
namespace: a.namespace,
name: a.name,
}
case RefMode:
d = &ref{
ce: a.ce,
source: a.source,
logger: a.logger,
reporter: a.reporter,
namespace: a.namespace,
name: a.name,
}
default:
return fmt.Errorf("mode %q not understood", a.mode)
}
for _, gvrc := range a.gvrcs {
lw := &cache.ListWatch{
ListFunc: asUnstructuredLister(a.k8s.Resource(gvrc.GVR).Namespace(a.namespace).List, gvrc.LabelSelector),
WatchFunc: asUnstructuredWatcher(a.k8s.Resource(gvrc.GVR).Namespace(a.namespace).Watch, gvrc.LabelSelector),
}
if gvrc.Controller {
d.addControllerWatch(gvrc.GVR)
}
var store cache.Store
if gvrc.OwnerApiVersion != "" || gvrc.OwnerKind != "" {
store = &controller{
apiVersion: gvrc.OwnerApiVersion,
kind: gvrc.OwnerKind,
delegate: store,
}
} else {
store = d
}
reflector := cache.NewReflector(lw, &unstructured.Unstructured{}, store, resyncPeriod)
go reflector.Run(stop)
}
<-stopCh
stop <- struct{}{}
return nil
}
type unstructuredLister func(metav1.ListOptions) (*unstructured.UnstructuredList, error)
func asUnstructuredLister(ulist unstructuredLister, selector string) cache.ListFunc {
return func(opts metav1.ListOptions) (runtime.Object, error) {
if selector != "" && opts.LabelSelector == "" {
opts.LabelSelector = selector
}
ul, err := ulist(opts)
if err != nil {
return nil, err
}
return ul, nil
}
}
func asUnstructuredWatcher(wf cache.WatchFunc, selector string) cache.WatchFunc {
return func(lo metav1.ListOptions) (watch.Interface, error) {
if selector != "" && lo.LabelSelector == "" {
lo.LabelSelector = selector
}
return wf(lo)
}
}