/
mesh.go
343 lines (309 loc) · 12 KB
/
mesh.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
// 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 mesh
import (
"fmt"
"os"
"time"
"github.com/hashicorp/go-multierror"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
wrappers "google.golang.org/protobuf/types/known/wrapperspb"
"sigs.k8s.io/yaml"
meshconfig "istio.io/api/mesh/v1alpha1"
"istio.io/api/networking/v1alpha3"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/validation/agent"
"istio.io/istio/pkg/log"
"istio.io/istio/pkg/ptr"
"istio.io/istio/pkg/util/protomarshal"
"istio.io/istio/pkg/util/sets"
)
// DefaultProxyConfig for individual proxies
func DefaultProxyConfig() *meshconfig.ProxyConfig {
// TODO: include revision based on REVISION env
// TODO: set default namespace based on POD_NAMESPACE env
return &meshconfig.ProxyConfig{
ConfigPath: constants.ConfigPathDir,
ClusterName: &meshconfig.ProxyConfig_ServiceCluster{ServiceCluster: constants.ServiceClusterName},
DrainDuration: durationpb.New(45 * time.Second),
TerminationDrainDuration: durationpb.New(5 * time.Second),
ProxyAdminPort: 15000,
ControlPlaneAuthPolicy: meshconfig.AuthenticationPolicy_MUTUAL_TLS,
DiscoveryAddress: "istiod.istio-system.svc:15012",
// Code defaults
BinaryPath: constants.BinaryPathFilename,
StatNameLength: 189,
StatusPort: 15020,
}
}
// DefaultMeshNetworks returns a default meshnetworks configuration.
// By default, it is empty.
func DefaultMeshNetworks() *meshconfig.MeshNetworks {
return ptr.Of(EmptyMeshNetworks())
}
// DefaultMeshConfig returns the default mesh config.
// This is merged with values from the mesh config map.
func DefaultMeshConfig() *meshconfig.MeshConfig {
proxyConfig := DefaultProxyConfig()
// Defaults matching the standard install
// order matches the generated mesh config.
return &meshconfig.MeshConfig{
EnableTracing: true,
AccessLogFile: "",
AccessLogEncoding: meshconfig.MeshConfig_TEXT,
AccessLogFormat: "",
EnableEnvoyAccessLogService: false,
ProtocolDetectionTimeout: durationpb.New(0),
IngressService: "istio-ingressgateway",
IngressControllerMode: meshconfig.MeshConfig_STRICT,
IngressClass: "istio",
TrustDomain: constants.DefaultClusterLocalDomain,
TrustDomainAliases: []string{},
EnableAutoMtls: wrappers.Bool(true),
OutboundTrafficPolicy: &meshconfig.MeshConfig_OutboundTrafficPolicy{Mode: meshconfig.MeshConfig_OutboundTrafficPolicy_ALLOW_ANY},
InboundTrafficPolicy: &meshconfig.MeshConfig_InboundTrafficPolicy{Mode: meshconfig.MeshConfig_InboundTrafficPolicy_PASSTHROUGH},
LocalityLbSetting: &v1alpha3.LocalityLoadBalancerSetting{
Enabled: wrappers.Bool(true),
},
Certificates: []*meshconfig.Certificate{},
DefaultConfig: proxyConfig,
RootNamespace: constants.IstioSystemNamespace,
ProxyListenPort: 15001,
ProxyInboundListenPort: 15006,
ConnectTimeout: durationpb.New(10 * time.Second),
DefaultServiceExportTo: []string{"*"},
DefaultVirtualServiceExportTo: []string{"*"},
DefaultDestinationRuleExportTo: []string{"*"},
// DnsRefreshRate is only used when DNS requests fail (NXDOMAIN or SERVFAIL). For success, the TTL
// will be used.
// https://datatracker.ietf.org/doc/html/rfc2308#section-3 defines how negative DNS results should handle TTLs,
// but Envoy does not respect this (https://github.com/envoyproxy/envoy/issues/20885).
// To counter this, we bump up the default to 60s to avoid overloading DNS servers.
DnsRefreshRate: durationpb.New(60 * time.Second),
ServiceSettings: make([]*meshconfig.MeshConfig_ServiceSettings, 0),
EnablePrometheusMerge: wrappers.Bool(true),
DefaultProviders: &meshconfig.MeshConfig_DefaultProviders{},
ExtensionProviders: []*meshconfig.MeshConfig_ExtensionProvider{
{
Name: "prometheus",
Provider: &meshconfig.MeshConfig_ExtensionProvider_Prometheus{
Prometheus: &meshconfig.MeshConfig_ExtensionProvider_PrometheusMetricsProvider{},
},
},
{
Name: "stackdriver",
Provider: &meshconfig.MeshConfig_ExtensionProvider_Stackdriver{
Stackdriver: &meshconfig.MeshConfig_ExtensionProvider_StackdriverProvider{},
},
},
{
Name: "envoy",
Provider: &meshconfig.MeshConfig_ExtensionProvider_EnvoyFileAccessLog{
EnvoyFileAccessLog: &meshconfig.MeshConfig_ExtensionProvider_EnvoyFileAccessLogProvider{
Path: "/dev/stdout",
},
},
},
},
}
}
// ApplyProxyConfig applies the give proxy config yaml to a mesh config object. The passed in mesh config
// will not be modified.
func ApplyProxyConfig(yaml string, meshConfig *meshconfig.MeshConfig) (*meshconfig.MeshConfig, error) {
mc := proto.Clone(meshConfig).(*meshconfig.MeshConfig)
pc, err := MergeProxyConfig(yaml, mc.DefaultConfig)
if err != nil {
return nil, err
}
mc.DefaultConfig = pc
return mc, nil
}
// MergeProxyConfig merges the given proxy config yaml with the given proxy config object.
func MergeProxyConfig(yaml string, proxyConfig *meshconfig.ProxyConfig) (*meshconfig.ProxyConfig, error) {
origMetadata := proxyConfig.ProxyMetadata
origProxyHeaders := proxyConfig.ProxyHeaders
if err := protomarshal.ApplyYAML(yaml, proxyConfig); err != nil {
return nil, fmt.Errorf("could not parse proxy config: %v", err)
}
newMetadata := proxyConfig.ProxyMetadata
proxyConfig.ProxyMetadata = mergeMap(origMetadata, newMetadata)
correctProxyHeaders(proxyConfig, origProxyHeaders)
return proxyConfig, nil
}
func correctProxyHeaders(proxyConfig *meshconfig.ProxyConfig, orig *meshconfig.ProxyConfig_ProxyHeaders) {
ph := proxyConfig.ProxyHeaders
if ph != nil && orig != nil {
ph.ForwardedClientCert = ptr.NonEmptyOrDefault(ph.ForwardedClientCert, orig.ForwardedClientCert)
ph.RequestId = ptr.NonEmptyOrDefault(ph.RequestId, orig.RequestId)
ph.AttemptCount = ptr.NonEmptyOrDefault(ph.AttemptCount, orig.AttemptCount)
ph.Server = ptr.NonEmptyOrDefault(ph.Server, orig.Server)
ph.EnvoyDebugHeaders = ptr.NonEmptyOrDefault(ph.EnvoyDebugHeaders, orig.EnvoyDebugHeaders)
}
}
func extractYamlField(key string, mp map[string]any) (string, error) {
proxyConfig := mp[key]
if proxyConfig == nil {
return "", nil
}
bytes, err := yaml.Marshal(proxyConfig)
if err != nil {
return "", err
}
return string(bytes), nil
}
func toMap(yamlText string) (map[string]any, error) {
mp := map[string]any{}
if err := yaml.Unmarshal([]byte(yamlText), &mp); err != nil {
return nil, err
}
return mp, nil
}
// ApplyMeshConfig returns a new MeshConfig decoded from the
// input YAML with the provided defaults applied to omitted configuration values.
func ApplyMeshConfig(yaml string, defaultConfig *meshconfig.MeshConfig) (*meshconfig.MeshConfig, error) {
// We want to keep semantics that all fields are overrides, except proxy config is a merge. This allows
// decent customization while also not requiring users to redefine the entire proxy config if they want to override
// Note: if we want to add more structure in the future, we will likely need to revisit this idea.
// Store the current set proxy config so we don't wipe it out, we will configure this later
prevProxyConfig := defaultConfig.DefaultConfig
prevDefaultProvider := defaultConfig.DefaultProviders
prevExtensionProviders := defaultConfig.ExtensionProviders
prevTrustDomainAliases := defaultConfig.TrustDomainAliases
defaultConfig.DefaultConfig = DefaultProxyConfig()
if err := protomarshal.ApplyYAML(yaml, defaultConfig); err != nil {
return nil, multierror.Prefix(err, "failed to convert to proto.")
}
defaultConfig.DefaultConfig = prevProxyConfig
raw, err := toMap(yaml)
if err != nil {
return nil, err
}
// Get just the proxy config yaml
pc, err := extractYamlField("defaultConfig", raw)
if err != nil {
return nil, multierror.Prefix(err, "failed to extract proxy config")
}
if pc != "" {
pc, err := MergeProxyConfig(pc, defaultConfig.DefaultConfig)
if err != nil {
return nil, err
}
defaultConfig.DefaultConfig = pc
}
defaultConfig.DefaultProviders = prevDefaultProvider
dp, err := extractYamlField("defaultProviders", raw)
if err != nil {
return nil, multierror.Prefix(err, "failed to extract default providers")
}
if dp != "" {
if err := protomarshal.ApplyYAML(dp, defaultConfig.DefaultProviders); err != nil {
return nil, fmt.Errorf("could not parse default providers: %v", err)
}
}
newExtensionProviders := defaultConfig.ExtensionProviders
defaultConfig.ExtensionProviders = prevExtensionProviders
for _, p := range newExtensionProviders {
found := false
for _, e := range defaultConfig.ExtensionProviders {
if p.Name == e.Name {
e.Provider = p.Provider
found = true
break
}
}
if !found {
defaultConfig.ExtensionProviders = append(defaultConfig.ExtensionProviders, p)
}
}
defaultConfig.TrustDomainAliases = sets.SortedList(sets.New(append(defaultConfig.TrustDomainAliases, prevTrustDomainAliases...)...))
warn, err := agent.ValidateMeshConfig(defaultConfig)
if err != nil {
return nil, err
}
if warn != nil {
log.Warnf("warnings occurred during mesh validation: %v", warn)
}
return defaultConfig, nil
}
func mergeMap(original map[string]string, merger map[string]string) map[string]string {
if original == nil && merger == nil {
return nil
}
if original == nil {
original = map[string]string{}
}
for k, v := range merger {
original[k] = v
}
return original
}
// ApplyMeshConfigDefaults returns a new MeshConfig decoded from the
// input YAML with defaults applied to omitted configuration values.
func ApplyMeshConfigDefaults(yaml string) (*meshconfig.MeshConfig, error) {
return ApplyMeshConfig(yaml, DefaultMeshConfig())
}
func DeepCopyMeshConfig(mc *meshconfig.MeshConfig) (*meshconfig.MeshConfig, error) {
j, err := protomarshal.ToJSON(mc)
if err != nil {
return nil, err
}
nmc := &meshconfig.MeshConfig{}
if err := protomarshal.ApplyJSON(j, nmc); err != nil {
return nil, err
}
return nmc, nil
}
// EmptyMeshNetworks configuration with no networks
func EmptyMeshNetworks() meshconfig.MeshNetworks {
return meshconfig.MeshNetworks{
Networks: map[string]*meshconfig.Network{},
}
}
// ParseMeshNetworks returns a new MeshNetworks decoded from the
// input YAML.
func ParseMeshNetworks(yaml string) (*meshconfig.MeshNetworks, error) {
out := EmptyMeshNetworks()
if err := protomarshal.ApplyYAML(yaml, &out); err != nil {
return nil, multierror.Prefix(err, "failed to convert to proto.")
}
if err := agent.ValidateMeshNetworks(&out); err != nil {
return nil, err
}
return &out, nil
}
// ReadMeshNetworks gets mesh networks configuration from a config file
func ReadMeshNetworks(filename string) (*meshconfig.MeshNetworks, error) {
yaml, err := os.ReadFile(filename)
if err != nil {
return nil, multierror.Prefix(err, "cannot read networks config file")
}
return ParseMeshNetworks(string(yaml))
}
// ReadMeshConfig gets mesh configuration from a config file
func ReadMeshConfig(filename string) (*meshconfig.MeshConfig, error) {
yaml, err := os.ReadFile(filename)
if err != nil {
return nil, multierror.Prefix(err, "cannot read mesh config file")
}
return ApplyMeshConfigDefaults(string(yaml))
}
// ReadMeshConfigData gets mesh configuration yaml from a config file
func ReadMeshConfigData(filename string) (string, error) {
yaml, err := os.ReadFile(filename)
if err != nil {
return "", multierror.Prefix(err, "cannot read mesh config file")
}
return string(yaml), nil
}