-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
extensions.go
351 lines (310 loc) · 11 KB
/
extensions.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright Istio 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 model
import (
"net/url"
"strings"
"time"
core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
httpwasm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/wasm/v3"
networkwasm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/wasm/v3"
wasmextensions "github.com/envoyproxy/go-control-plane/envoy/extensions/wasm/v3"
anypb "google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
"k8s.io/apimachinery/pkg/types"
extensions "istio.io/api/extensions/v1alpha1"
typeapi "istio.io/api/type/v1beta1"
"istio.io/istio/pilot/pkg/model/credentials"
istionetworking "istio.io/istio/pilot/pkg/networking"
"istio.io/istio/pilot/pkg/util/protoconv"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/gvk"
pm "istio.io/istio/pkg/model"
"istio.io/istio/pkg/util/protomarshal"
)
const (
defaultRuntime = "envoy.wasm.runtime.v8"
fileScheme = "file"
ociScheme = "oci"
WasmSecretEnv = pm.WasmSecretEnv
WasmPolicyEnv = pm.WasmPolicyEnv
WasmResourceVersionEnv = pm.WasmResourceVersionEnv
// WasmPluginResourceNamePrefix is the prefix of the resource name of WasmPlugin,
// preventing the name collision with other resources.
WasmPluginResourceNamePrefix = "extenstions.istio.io/wasmplugin/"
)
// WasmPluginType defines the type of wasm plugin
type WasmPluginType int
const (
WasmPluginTypeHTTP WasmPluginType = iota
WasmPluginTypeNetwork
WasmPluginTypeAny
)
func fromPluginType(pluginType extensions.PluginType) WasmPluginType {
switch pluginType {
case extensions.PluginType_HTTP:
return WasmPluginTypeHTTP
case extensions.PluginType_NETWORK:
return WasmPluginTypeNetwork
case extensions.PluginType_UNSPECIFIED_PLUGIN_TYPE:
return WasmPluginTypeHTTP // Return HTTP as default for backward compatibility.
}
return WasmPluginTypeHTTP
}
func workloadModeForListenerClass(class istionetworking.ListenerClass) typeapi.WorkloadMode {
switch class {
case istionetworking.ListenerClassGateway:
return typeapi.WorkloadMode_CLIENT
case istionetworking.ListenerClassSidecarInbound:
return typeapi.WorkloadMode_SERVER
case istionetworking.ListenerClassSidecarOutbound:
return typeapi.WorkloadMode_CLIENT
case istionetworking.ListenerClassUndefined:
// this should not happen, just in case
return typeapi.WorkloadMode_CLIENT
}
return typeapi.WorkloadMode_CLIENT
}
type WasmPluginWrapper struct {
*extensions.WasmPlugin
Name string
Namespace string
ResourceName string
ResourceVersion string
}
func (p *WasmPluginWrapper) MatchListener(matcher WorkloadPolicyMatcher, li WasmPluginListenerInfo) bool {
if matcher.ShouldAttachPolicy(gvk.WasmPlugin, p.NamespacedName(), p) {
return matchTrafficSelectors(p.Match, li)
}
// If it doesn't match one of the above cases, the plugin is not bound to this workload
return false
}
func (p *WasmPluginWrapper) NamespacedName() types.NamespacedName {
return types.NamespacedName{Name: p.Name, Namespace: p.Namespace}
}
func (p *WasmPluginWrapper) MatchType(pluginType WasmPluginType) bool {
return pluginType == WasmPluginTypeAny || pluginType == fromPluginType(p.WasmPlugin.Type)
}
func (p *WasmPluginWrapper) BuildHTTPWasmFilter() *httpwasm.Wasm {
if !(p.Type == extensions.PluginType_HTTP || p.Type == extensions.PluginType_UNSPECIFIED_PLUGIN_TYPE) {
return nil
}
return &httpwasm.Wasm{
Config: p.buildPluginConfig(),
}
}
func (p *WasmPluginWrapper) BuildNetworkWasmFilter() *networkwasm.Wasm {
if p.Type != extensions.PluginType_NETWORK {
return nil
}
return &networkwasm.Wasm{
Config: p.buildPluginConfig(),
}
}
func (p *WasmPluginWrapper) buildPluginConfig() *wasmextensions.PluginConfig {
cfg := &anypb.Any{}
plugin := p.WasmPlugin
if plugin.PluginConfig != nil && len(plugin.PluginConfig.Fields) > 0 {
cfgJSON, err := protomarshal.ToJSON(plugin.PluginConfig)
if err != nil {
log.Warnf("wasmplugin %v/%v discarded due to json marshaling error: %s", p.Namespace, p.Name, err)
return nil
}
cfg = protoconv.MessageToAny(&wrapperspb.StringValue{
Value: cfgJSON,
})
}
u, err := url.Parse(plugin.Url)
if err != nil {
log.Warnf("wasmplugin %v/%v discarded due to failure to parse URL: %s", p.Namespace, p.Name, err)
return nil
}
// when no scheme is given, default to oci://
if u.Scheme == "" {
u.Scheme = ociScheme
}
datasource := buildDataSource(u, plugin)
resourceName := p.Namespace + "." + p.Name
return &wasmextensions.PluginConfig{
Name: resourceName,
RootId: plugin.PluginName,
Configuration: cfg,
Vm: buildVMConfig(datasource, p.ResourceVersion, plugin),
FailOpen: plugin.FailStrategy == extensions.FailStrategy_FAIL_OPEN,
}
}
type WasmPluginListenerInfo struct {
Port int
Class istionetworking.ListenerClass
// Service that WasmPlugins can attach to via targetRefs (optional)
Service *Service
}
// If anyListener is used as a listener info,
// the listener is matched with any TrafficSelector.
var anyListener = WasmPluginListenerInfo{
Port: 0,
Class: istionetworking.ListenerClassUndefined,
}
func matchTrafficSelectors(ts []*extensions.WasmPlugin_TrafficSelector, li WasmPluginListenerInfo) bool {
if (li.Class == istionetworking.ListenerClassUndefined && li.Port == 0) || len(ts) == 0 {
return true
}
for _, match := range ts {
if matchMode(match.Mode, li.Class) && matchPorts(match.Ports, li.Port) {
return true
}
}
return false
}
func matchMode(workloadMode typeapi.WorkloadMode, class istionetworking.ListenerClass) bool {
switch workloadMode {
case typeapi.WorkloadMode_CLIENT_AND_SERVER, typeapi.WorkloadMode_UNDEFINED:
return true
default:
return workloadMode == workloadModeForListenerClass(class)
}
}
func matchPorts(portSelectors []*typeapi.PortSelector, port int) bool {
if len(portSelectors) == 0 {
// If there is no specified port, match with all the ports.
return true
}
for _, ps := range portSelectors {
if ps.GetNumber() != 0 && ps.GetNumber() == uint32(port) {
return true
}
}
return false
}
func convertToWasmPluginWrapper(originPlugin config.Config) *WasmPluginWrapper {
var ok bool
// Make a deep copy since we are going to mutate the resource later for secret env variable.
// We do not want to mutate the underlying resource at informer cache.
plugin := originPlugin.DeepCopy()
var wasmPlugin *extensions.WasmPlugin
if wasmPlugin, ok = plugin.Spec.(*extensions.WasmPlugin); !ok {
return nil
}
if wasmPlugin.PluginConfig != nil && len(wasmPlugin.PluginConfig.Fields) > 0 {
_, err := protomarshal.ToJSON(wasmPlugin.PluginConfig)
if err != nil {
log.Warnf("wasmplugin %v/%v discarded due to json marshaling error: %s", plugin.Namespace, plugin.Name, err)
return nil
}
}
u, err := url.Parse(wasmPlugin.Url)
if err != nil {
log.Warnf("wasmplugin %v/%v discarded due to failure to parse URL: %s", plugin.Namespace, plugin.Name, err)
return nil
}
// when no scheme is given, default to oci://
if u.Scheme == "" {
u.Scheme = ociScheme
}
// Normalize the image pull secret to the full resource name.
wasmPlugin.ImagePullSecret = toSecretResourceName(wasmPlugin.ImagePullSecret, plugin.Namespace)
return &WasmPluginWrapper{
Name: plugin.Name,
Namespace: plugin.Namespace,
ResourceName: WasmPluginResourceNamePrefix + plugin.Namespace + "." + plugin.Name,
WasmPlugin: wasmPlugin,
ResourceVersion: plugin.ResourceVersion,
}
}
// toSecretResourceName converts a imagePullSecret to a resource name referenced at Wasm SDS.
// NOTE: the secret referenced by WasmPlugin has to be in the same namespace as the WasmPlugin,
// so this function makes sure that the secret resource name, which will be used to retrieve secret at
// xds generation time, has the same namespace as the WasmPlugin.
func toSecretResourceName(name, pluginNamespace string) string {
if name == "" {
return ""
}
// Convert user provided secret name to secret resource name.
rn := credentials.ToResourceName(name)
// Parse the secret resource name.
sr, err := credentials.ParseResourceName(rn, pluginNamespace, "", "")
if err != nil {
log.Debugf("Failed to parse wasm secret resource name %v", err)
return ""
}
// Forcely rewrite secret namespace to plugin namespace, since we require secret resource
// referenced by WasmPlugin co-located with WasmPlugin in the same namespace.
sr.Namespace = pluginNamespace
return sr.KubernetesResourceName()
}
func buildDataSource(u *url.URL, wasmPlugin *extensions.WasmPlugin) *core.AsyncDataSource {
if u.Scheme == fileScheme {
return &core.AsyncDataSource{
Specifier: &core.AsyncDataSource_Local{
Local: &core.DataSource{
Specifier: &core.DataSource_Filename{
Filename: strings.TrimPrefix(wasmPlugin.Url, "file://"),
},
},
},
}
}
return &core.AsyncDataSource{
Specifier: &core.AsyncDataSource_Remote{
Remote: &core.RemoteDataSource{
HttpUri: &core.HttpUri{
Uri: u.String(),
Timeout: durationpb.New(30 * time.Second), // TODO: make this configurable?
HttpUpstreamType: &core.HttpUri_Cluster{
// the agent will fetch this anyway, so no need for a cluster
Cluster: "_",
},
},
Sha256: wasmPlugin.Sha256,
},
},
}
}
func buildVMConfig(
datasource *core.AsyncDataSource,
resourceVersion string,
wasmPlugin *extensions.WasmPlugin,
) *wasmextensions.PluginConfig_VmConfig {
cfg := &wasmextensions.PluginConfig_VmConfig{
VmConfig: &wasmextensions.VmConfig{
Runtime: defaultRuntime,
Code: datasource,
EnvironmentVariables: &wasmextensions.EnvironmentVariables{
KeyValues: map[string]string{},
},
},
}
if wasmPlugin.ImagePullSecret != "" {
cfg.VmConfig.EnvironmentVariables.KeyValues[WasmSecretEnv] = wasmPlugin.ImagePullSecret
}
if wasmPlugin.ImagePullPolicy != extensions.PullPolicy_UNSPECIFIED_POLICY {
cfg.VmConfig.EnvironmentVariables.KeyValues[WasmPolicyEnv] = wasmPlugin.ImagePullPolicy.String()
}
cfg.VmConfig.EnvironmentVariables.KeyValues[WasmResourceVersionEnv] = resourceVersion
vm := wasmPlugin.VmConfig
if vm != nil && len(vm.Env) != 0 {
hostEnvKeys := make([]string, 0, len(vm.Env))
for _, e := range vm.Env {
switch e.ValueFrom {
case extensions.EnvValueSource_INLINE:
cfg.VmConfig.EnvironmentVariables.KeyValues[e.Name] = e.Value
case extensions.EnvValueSource_HOST:
hostEnvKeys = append(hostEnvKeys, e.Name)
}
}
cfg.VmConfig.EnvironmentVariables.HostEnvKeys = hostEnvKeys
}
return cfg
}