-
Notifications
You must be signed in to change notification settings - Fork 316
/
container_init.go
287 lines (259 loc) · 7.95 KB
/
container_init.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package webhookv2
import (
"bytes"
"strconv"
"strings"
"text/template"
corev1 "k8s.io/api/core/v1"
"k8s.io/utils/pointer"
"github.com/hashicorp/consul-k8s/control-plane/connect-inject/common"
"github.com/hashicorp/consul-k8s/control-plane/connect-inject/constants"
)
const (
injectInitContainerName = "consul-mesh-init"
rootUserAndGroupID = 0
sidecarUserAndGroupID = 5995
initContainersUserAndGroupID = 5996
netAdminCapability = "NET_ADMIN"
)
type initContainerCommandData struct {
ServiceName string
ServiceAccountName string
AuthMethod string
// Log settings for the mesh-init command.
LogLevel string
LogJSON bool
}
// containerInit returns the init container spec for mesh-init that polls for the workload's bootstrap config
// so that it optionally set up iptables for transparent proxy. Otherwise, it ensures the workload exists before
// the pod starts.
func (w *MeshWebhook) containerInit(namespace corev1.Namespace, pod corev1.Pod) (corev1.Container, error) {
// Check if tproxy is enabled on this pod.
tproxyEnabled, err := common.TransparentProxyEnabled(namespace, pod, w.EnableTransparentProxy)
if err != nil {
return corev1.Container{}, err
}
data := initContainerCommandData{
AuthMethod: w.AuthMethod,
LogLevel: w.LogLevel,
LogJSON: w.LogJSON,
}
// Create expected volume mounts
volMounts := []corev1.VolumeMount{
{
Name: volumeName,
MountPath: "/consul/mesh-inject",
},
}
data.ServiceName = pod.Annotations[constants.AnnotationService]
var bearerTokenFile string
if w.AuthMethod != "" {
data.ServiceAccountName = pod.Spec.ServiceAccountName
// Extract the service account token's volume mount
var saTokenVolumeMount corev1.VolumeMount
saTokenVolumeMount, bearerTokenFile, err = findServiceAccountVolumeMount(pod)
if err != nil {
return corev1.Container{}, err
}
// Append to volume mounts
volMounts = append(volMounts, saTokenVolumeMount)
}
// Render the command
var buf bytes.Buffer
tpl := template.Must(template.New("root").Parse(strings.TrimSpace(
initContainerCommandTpl)))
err = tpl.Execute(&buf, &data)
if err != nil {
return corev1.Container{}, err
}
initContainerName := injectInitContainerName
container := corev1.Container{
Name: initContainerName,
Image: w.ImageConsulK8S,
Env: []corev1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "metadata.name"},
},
},
{
Name: "POD_NAMESPACE",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "metadata.namespace"},
},
},
{
Name: "CONSUL_ADDRESSES",
Value: w.ConsulAddress,
},
{
Name: "CONSUL_GRPC_PORT",
Value: strconv.Itoa(w.ConsulConfig.GRPCPort),
},
{
Name: "CONSUL_HTTP_PORT",
Value: strconv.Itoa(w.ConsulConfig.HTTPPort),
},
{
Name: "CONSUL_API_TIMEOUT",
Value: w.ConsulConfig.APITimeout.String(),
},
},
Resources: w.InitContainerResources,
VolumeMounts: volMounts,
Command: []string{"/bin/sh", "-ec", buf.String()},
}
if w.TLSEnabled {
container.Env = append(container.Env,
corev1.EnvVar{
Name: constants.UseTLSEnvVar,
Value: "true",
},
corev1.EnvVar{
Name: constants.CACertPEMEnvVar,
Value: w.ConsulCACert,
},
corev1.EnvVar{
Name: constants.TLSServerNameEnvVar,
Value: w.ConsulTLSServerName,
})
}
if w.AuthMethod != "" {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_LOGIN_AUTH_METHOD",
Value: w.AuthMethod,
},
corev1.EnvVar{
Name: "CONSUL_LOGIN_BEARER_TOKEN_FILE",
Value: bearerTokenFile,
},
corev1.EnvVar{
Name: "CONSUL_LOGIN_META",
Value: "pod=$(POD_NAMESPACE)/$(POD_NAME)",
})
if w.EnableNamespaces {
if w.EnableK8SNSMirroring {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_LOGIN_NAMESPACE",
Value: "default",
})
} else {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_LOGIN_NAMESPACE",
Value: w.consulNamespace(namespace.Name),
})
}
}
if w.ConsulPartition != "" {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_LOGIN_PARTITION",
Value: w.ConsulPartition,
})
}
}
if w.EnableNamespaces {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_NAMESPACE",
Value: w.consulNamespace(namespace.Name),
})
}
if w.ConsulPartition != "" {
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_PARTITION",
Value: w.ConsulPartition,
})
}
// OpenShift without CNI is the only environment where privileged must be true.
privileged := false
if w.EnableOpenShift && !w.EnableCNI {
privileged = true
}
if tproxyEnabled {
if !w.EnableCNI {
// Set redirect traffic config for the container so that we can apply iptables rules.
redirectTrafficConfig, err := w.iptablesConfigJSON(pod, namespace)
if err != nil {
return corev1.Container{}, err
}
container.Env = append(container.Env,
corev1.EnvVar{
Name: "CONSUL_REDIRECT_TRAFFIC_CONFIG",
Value: redirectTrafficConfig,
})
// Running consul mesh-init redirect-traffic with iptables
// requires both being a root user and having NET_ADMIN capability.
container.SecurityContext = &corev1.SecurityContext{
RunAsUser: pointer.Int64(rootUserAndGroupID),
RunAsGroup: pointer.Int64(rootUserAndGroupID),
// RunAsNonRoot overrides any setting in the Pod so that we can still run as root here as required.
RunAsNonRoot: pointer.Bool(false),
Privileged: pointer.Bool(privileged),
Capabilities: &corev1.Capabilities{
Add: []corev1.Capability{netAdminCapability},
},
}
} else {
container.SecurityContext = &corev1.SecurityContext{
RunAsUser: pointer.Int64(initContainersUserAndGroupID),
RunAsGroup: pointer.Int64(initContainersUserAndGroupID),
RunAsNonRoot: pointer.Bool(true),
Privileged: pointer.Bool(privileged),
Capabilities: &corev1.Capabilities{
Drop: []corev1.Capability{"ALL"},
},
ReadOnlyRootFilesystem: pointer.Bool(true),
AllowPrivilegeEscalation: pointer.Bool(false),
}
}
}
return container, nil
}
// consulDNSEnabled returns true if Consul DNS should be enabled for this pod.
// It returns an error when the annotation value cannot be parsed by strconv.ParseBool or if we are unable
// to read the pod's namespace label when it exists.
func consulDNSEnabled(namespace corev1.Namespace, pod corev1.Pod, globalDNSEnabled bool, globalTProxyEnabled bool) (bool, error) {
// DNS is only possible when tproxy is also enabled because it relies
// on traffic being redirected.
tproxy, err := common.TransparentProxyEnabled(namespace, pod, globalTProxyEnabled)
if err != nil {
return false, err
}
if !tproxy {
return false, nil
}
// First check to see if the pod annotation exists to override the namespace or global settings.
if raw, ok := pod.Annotations[constants.KeyConsulDNS]; ok {
return strconv.ParseBool(raw)
}
// Next see if the namespace has been defaulted.
if raw, ok := namespace.Labels[constants.KeyConsulDNS]; ok {
return strconv.ParseBool(raw)
}
// Else fall back to the global default.
return globalDNSEnabled, nil
}
// splitCommaSeparatedItemsFromAnnotation takes an annotation and a pod
// and returns the comma-separated value of the annotation as a list of strings.
func splitCommaSeparatedItemsFromAnnotation(annotation string, pod corev1.Pod) []string {
var items []string
if raw, ok := pod.Annotations[annotation]; ok {
items = append(items, strings.Split(raw, ",")...)
}
return items
}
// initContainerCommandTpl is the template for the command executed by
// the init container.
const initContainerCommandTpl = `
consul-k8s-control-plane mesh-init -proxy-name=${POD_NAME} \
-log-level={{ .LogLevel }} \
-log-json={{ .LogJSON }} \
`