Debian Codegraph @

images/base/files/usr/local/bin/entrypoint

raw symbols SCIP
1 #!/bin/bash
2
3 # Copyright 2019 The Kubernetes Authors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 set -o errexit
18 set -o nounset
19 set -o pipefail
20
21 # logging helpers
22 log_info() {
23 echo "INFO: $1" >&2
24 }
25 log_warn() {
26 echo "WARN: $1" >&2
27 }
28 log_error() {
29 echo "ERROR: $1" >&2
30 }
31
32 # If /proc/self/uid_map 4294967295 mappings, we are in the initial user namespace, i.e. the host.
33 # Otherwise we are in a non-initial user namespace.
34 # https://github.com/opencontainers/runc/blob/v1.0.0-rc92/libcontainer/system/linux.go#L109-L118
35 userns=""
36 if grep -Eqv "0[[:space:]]+0[[:space:]]+4294967295" /proc/self/uid_map; then
37 userns="1"
38 log_info 'running in a user namespace (experimental)'
39 fi
40
41 grep_allow_nomatch() {
42 # grep exits 0 on match, 1 on no match, 2 on error
43 grep "$@" || [[ $? == 1 ]]
44 }
45
46 # regex_escape_ip converts IP address string $1 to a regex-escaped literal
47 regex_escape_ip(){
48 sed -e 's#\.#\\.#g' -e 's#\[#\\[#g' -e 's#\]#\\]#g' <<<"$1"
49 }
50
51 validate_userns() {
52 if [[ -z "${userns}" ]]; then
53 return
54 fi
55
56 local nofile_hard
57 nofile_hard="$(ulimit -Hn)"
58 local nofile_hard_expected="64000"
59 if [[ "${nofile_hard}" -lt "${nofile_hard_expected}" ]]; then
60 log_warn "UserNS: expected RLIMIT_NOFILE to be at least ${nofile_hard_expected}, got ${nofile_hard}"
61 fi
62
63 if [[ -f "/sys/fs/cgroup/cgroup.controllers" ]]; then
64 for f in cpu memory pids; do
65 if ! grep -qw $f /sys/fs/cgroup/cgroup.controllers; then
66 log_error "UserNS: $f controller needs to be delegated"
67 exit 1
68 fi
69 done
70 fi
71 }
72
73 overlayfs_preferrable() {
74 if [[ -z "$userns" ]]; then
75 # If we are outside userns, we can always assume overlayfs is preferrable
76 return 0
77 fi
78
79 # Debian 10 and 11 supports overlayfs in userns with a "permit_mount_in_userns" kernel patch,
80 # but known to be unstable, so we avoid using it https://github.com/moby/moby/issues/42302
81 if [[ -e "/sys/module/overlay/parameters/permit_mounts_in_userns" ]]; then
82 log_info "UserNS: kernel seems supporting overlayfs with permit_mounts_in_userns, but avoiding due to instability."
83 return 1
84 fi
85
86 # Check overlayfs availability, by attempting to mount it.
87 #
88 # Overlayfs inside userns is known to be available for the following environments:
89 # - Kernel >= 5.11 (but 5.11 and 5.12 have issues on SELinux hosts. Fixed in 5.13.)
90 # - Ubuntu kernel
91 # - Debian kernel (but avoided due to instability, see the /sys/module/overlay/... check above)
92 # - Sysbox
93 tmp=$(mktemp -d)
94 mkdir -p "${tmp}/l" "${tmp}/u" "${tmp}/w" "${tmp}/m"
95 if ! mount -t overlay -o lowerdir="${tmp}/l,upperdir=${tmp}/u,workdir=${tmp}/w" overlay "${tmp}/m"; then
96 log_info "UserNS: kernel does not seem to support overlayfs."
97 rm -rf "${tmp}"
98 return 1
99 fi
100 umount "${tmp}/m"
101 rm -rf "${tmp}"
102
103 # Detect whether SELinux is Enforcing (or Permitted) by grepping /proc/self/attr/current .
104 # Note that we cannot use `getenforce` command here because /sys/fs/selinux is typically not mounted for containers.
105 if grep -q "_t:" "/proc/self/attr/current"; then
106 # When the kernel is before v5.13 and SELinux is enforced, fuse-overlayfs might be safer, so we print a warning (but not an error).
107 # https://github.com/torvalds/linux/commit/7fa2e79a6bb924fa4b2de5766dab31f0f47b5ab6
108 log_warn "UserNS: SELinux might be Enforcing. If you see an error related to overlayfs, try setting \`KIND_EXPERIMENTAL_CONTAINERD_SNAPSHOTTER=fuse-overlayfs\` ."
109 fi
110 return 0
111 }
112
113 configure_containerd() {
114 local snapshotter=${KIND_EXPERIMENTAL_CONTAINERD_SNAPSHOTTER:-}
115
116 # if we have not already overridden the snapshotter, attempt to auto select
117 if [[ -z "$snapshotter" ]]; then
118 # we need to switch to 'native' or 'fuse-overlayfs' on zfs
119 container_filesystem="$(stat -f -c %T /kind)"
120 if [[ "$container_filesystem" == 'zfs' ]]; then
121 # we do not use the ZFS snapshotter because of skew issues vs the host
122 snapshotter="native"
123 # fuse should imply fuse-overlayfs, we should switch to fuse-overlayfs (or native)
124 elif [[ "$container_filesystem" == 'fuseblk' ]]; then
125 snapshotter="fuse-overlayfs"
126 # Otherwise use fuse-overlayfs if overlayfs is not preferrable
127 # https://github.com/kubernetes-sigs/kind/issues/2275
128 elif [[ -n "$userns" ]] && ! overlayfs_preferrable; then
129 snapshotter="fuse-overlayfs"
130 fi
131 fi
132
133 # handle userns (rootless)
134 if [[ -n "$userns" ]]; then
135 # enable restrict_oom_score_adj
136 sed -i 's/restrict_oom_score_adj = false/restrict_oom_score_adj = true/' /etc/containerd/config.toml
137 fi
138
139 # if we've overridden or auto-selected the snapshotter vs the default, update containerd
140 if [[ -n "$snapshotter" ]]; then
141 log_info "changing snapshotter from \"overlayfs\" to \"$snapshotter\""
142 sed -i "s/snapshotter = \"overlayfs\"/snapshotter = \"$snapshotter\"/" /etc/containerd/config.toml
143 if [[ "$snapshotter" = "fuse-overlayfs" ]]; then
144 log_info 'enabling containerd-fuse-overlayfs service'
145 systemctl enable containerd-fuse-overlayfs
146 fi
147 fi
148 }
149
150 configure_proxy() {
151 # ensure all processes receive the proxy settings by default
152 # https://www.freedesktop.org/software/systemd/man/systemd-system.conf.html
153 mkdir -p /etc/systemd/system.conf.d/
154 cat <<EOF >/etc/systemd/system.conf.d/proxy-default-environment.conf
155 [Manager]
156 DefaultEnvironment="HTTP_PROXY=${HTTP_PROXY:-}" "HTTPS_PROXY=${HTTPS_PROXY:-}" "NO_PROXY=${NO_PROXY:-}"
157 EOF
158 }
159
160 fix_mount() {
161 log_info 'ensuring we can execute mount/umount even with userns-remap'
162 # necessary only when userns-remap is enabled on the host, but harmless
163 # The binary /bin/mount should be owned by root and have the setuid bit
164 chown root:root "$(which mount)" "$(which umount)"
165 chmod -s "$(which mount)" "$(which umount)"
166
167 # This is a workaround to an AUFS bug that might cause `Text file
168 # busy` on `mount` command below. See more details in
169 # https://github.com/moby/moby/issues/9547
170 if [[ "$(stat -f -c %T "$(which mount)")" == 'aufs' ]]; then
171 log_info 'detected aufs, calling sync'
172 sync
173 fi
174
175 log_info 'remounting /sys read-only'
176 # systemd-in-a-container should have read only /sys
177 # https://systemd.io/CONTAINER_INTERFACE/
178 # however, we need other things from `docker run --privileged` ...
179 # and this flag also happens to make /sys rw, amongst other things
180 #
181 # This step is ignored when running inside UserNS, because it fails with EACCES.
182 if ! mount -o remount,ro /sys; then
183 if [[ -n "$userns" ]]; then
184 log_info 'UserNS: ignoring mount fail'
185 else
186 exit 1
187 fi
188 fi
189
190 log_info 'making mounts shared'
191 # for mount propagation
192 mount --make-rshared /
193 }
194
195 # helper used by mount_kubelet_cgroup_root
196 mount_kubelet_cgroup_root_subsystem() {
197 local cgroup_root=$1
198 local subsystem=$2
199 if [ -z "${cgroup_root}" ]; then
200 return 0
201 fi
202 mkdir -p "${subsystem}/${cgroup_root}"
203 if [ "${subsystem}" == "/sys/fs/cgroup/cpuset" ]; then
204 # This is needed. Otherwise, assigning process to the cgroup
205 # (or any nested cgroup) would result in ENOSPC.
206 cat "${subsystem}/cpuset.cpus" > "${subsystem}/${cgroup_root}/cpuset.cpus"
207 cat "${subsystem}/cpuset.mems" > "${subsystem}/${cgroup_root}/cpuset.mems"
208 fi
209 # We need to perform a self bind mount here because otherwise,
210 # systemd might delete the cgroup unintentionally before the
211 # kubelet starts.
212 mount --bind "${subsystem}/${cgroup_root}" "${subsystem}/${cgroup_root}"
213 }
214
215 # helper used by fix_cgroup
216 mount_kubelet_cgroup_root() {
217 local cgroup_subsystems=$1
218 echo "${cgroup_subsystems}" |
219 while IFS= read -r subsystem; do
220 mount_kubelet_cgroup_root_subsystem /kubelet "${subsystem}"
221 mount_kubelet_cgroup_root_subsystem /kubelet.slice "${subsystem}"
222 done
223 # workaround for hosts not running systemd
224 # we only do this for kubelet.slice because it's not relevant when not using
225 # the systemd cgroup driver
226 if [[ ! "${cgroup_subsystems}" = */sys/fs/cgroup/systemd* ]]; then
227 mount_kubelet_cgroup_root_subsystem /kubelet.slice /sys/fs/cgroup/systemd
228 fi
229 }
230
231 # helper for cgroups v1, to eliminate the misc cgroup
232 # see: https://github.com/kubernetes-sigs/kind/issues/3223
233 # basically: this cgroup is not very useful for us, and until recently wasn't
234 # supported by runc on cgroups v1 anyhow.
235 # on cgroupsv2 we can leave it, but on v1 the mismatch in support from container
236 # nesting causes problems
237 remove_misc_controller() {
238 local misc_controller='/sys/fs/cgroup/misc'
239 if [[ ! -d $misc_controller ]]; then
240 return 0
241 fi
242 log_info "removing misc controller"
243 umount $misc_controller || log_warn "failed umount $misc_controller"
244 rmdir $misc_controller || log_warn "failed rmdir $misc_controller"
245 # systemd will discover misc controller is available here and re-mount it
246 # we will pretend it isn't available with a bind mount
247 # this mount will be removed by undo-mount-hacks.service
248 grep -v 'misc' /proc/cgroups >/kind/fake-cgroups
249 mount --bind /kind/fake-cgroups /proc/cgroups
250 }
251
252 fix_cgroup() {
253 if [[ -f "/sys/fs/cgroup/cgroup.controllers" ]]; then
254 log_info 'detected cgroup v2'
255 # Both Docker and Podman enable CgroupNS on cgroup v2 hosts by default.
256 #
257 # So mostly we do not need to mess around with the cgroup path stuff,
258 # however, we still need to create the "/kubelet" cgroup at least.
259 # (Otherwise kubelet fails with `cgroup-root ["kubelet"] doesn't exist` error, see #1969)
260 #
261 # The "/kubelet" cgroup is created in ExecStartPre of the kubeadm service.
262 #
263 # [FAQ: Why not create "/kubelet" cgroup here?]
264 # We can't create the cgroup with controllers here, because /sys/fs/cgroup/cgroup.subtree_control is empty.
265 # And yet we can't write controllers to /sys/fs/cgroup/cgroup.subtree_control by ourselves either, because
266 # /sys/fs/cgroup/cgroup.procs is not empty at this moment.
267 #
268 # After switching from this entrypoint script to systemd, systemd evacuates the processes in the root
269 # group to "/init.scope" group, so we can write the root subtree_control and create "/kubelet" cgroup.
270 return
271 fi
272 log_info 'detected cgroup v1'
273 # We're looking for the cgroup-path for the cpu controller for the
274 # current process. this tells us what cgroup-path the container is in.
275 local current_cgroup
276 current_cgroup=$(grep -E '^[^:]*:([^:]*,)?cpu(,[^,:]*)?:.*' /proc/self/cgroup | cut -d: -f3)
277 if [ "$current_cgroup" = "/" ]; then
278 log_info 'detected cgroupns'
279 # we don't need or want the misc controller, see comments on this function
280 remove_misc_controller
281 # kubelet will try to manage cgroups / pods that are not owned by it when
282 # "nesting" clusters, unless we instruct it to use a different cgroup root.
283 # We do this, and when doing so we must fixup this alternative root
284 # currently this is hardcoded to be /kubelet
285 # under systemd cgroup driver, kubelet appends .slice
286 local cgroup_subsystems
287 cgroup_subsystems=$(findmnt -lun -o source,target -t cgroup | grep -F "${current_cgroup}" | awk '{print $2}')
288 mount --make-rprivate /sys/fs/cgroup
289 mount_kubelet_cgroup_root "${cgroup_subsystems}"
290 return
291 fi
292
293 # NOTE The rest of this function deals with the unfortunate situation of
294 # cgroup v1 with no cgroupns enabled. One fine day every user will have
295 # cgroupns enabled (or switch or cgroup v2 which has it enabled by default).
296 # Once that happens, this function can be removed completely.
297
298 log_warn 'cgroupns not enabled! Please use cgroup v2, or cgroup v1 with cgroupns enabled.'
299
300 # See: https://d2iq.com/blog/running-kind-inside-a-kubernetes-cluster-for-continuous-integration
301 # Capture initial state before modifying
302 #
303 # Then we collect the subsystems that are active on our current process.
304 # We assume the cpu controller is in use on all node containers,
305 # and other controllers use the same sub-path.
306 #
307 # See: https://man7.org/linux/man-pages/man7/cgroups.7.html
308 log_info 'fixing cgroup mounts for all subsystems'
309 local cgroup_subsystems
310 cgroup_subsystems=$(findmnt -lun -o source,target -t cgroup | grep -F "${current_cgroup}" | awk '{print $2}')
311 # Unmount the cgroup subsystems that are not known to runtime used to
312 # run the container we are in. Those subsystems are not properly scoped
313 # (i.e. the root cgroup is exposed, rather than something like docker/xxxx).
314 # In case a runtime (which is aware of more subsystems -- such as rdma,
315 # misc, or unified) is used inside the container, it may create cgroups for
316 # these subsystems, and as they are not scoped, they will leak to the host
317 # and thus will become non-removable.
318 #
319 # See https://github.com/kubernetes/kubernetes/issues/109182
320 local unsupported_cgroups
321 unsupported_cgroups=$(findmnt -lun -o source,target -t cgroup | grep_allow_nomatch -v -F "${current_cgroup}" | awk '{print $2}')
322 if [ -n "$unsupported_cgroups" ]; then
323 local mnt
324 echo "$unsupported_cgroups" |
325 while IFS= read -r mnt; do
326 log_info "unmounting and removing $mnt"
327 umount "$mnt" || log_warn "failed to unmount $mnt"
328 rmdir "$mnt" || log_warn "failed to rmdir $mnt"
329 done
330 fi
331 # always remove misc on v1, see comments on this function
332 remove_misc_controller
333
334 # For each cgroup subsystem, Docker does a bind mount from the current
335 # cgroup to the root of the cgroup subsystem. For instance:
336 # /sys/fs/cgroup/memory/docker/<cid> -> /sys/fs/cgroup/memory
337 #
338 # This will confuse Kubelet and cadvisor and will dump the following error
339 # messages in kubelet log:
340 # `summary_sys_containers.go:47] Failed to get system container stats for ".../kubelet.service"`
341 #
342 # This is because `/proc/<pid>/cgroup` is not affected by the bind mount.
343 # The following is a workaround to recreate the original cgroup
344 # environment by doing another bind mount for each subsystem.
345 local cgroup_mounts
346 # xref: https://github.com/kubernetes/minikube/pull/9508
347 # Example inputs:
348 #
349 # Docker: /docker/562a56986a84b3cd38d6a32ac43fdfcc8ad4d2473acf2839cbf549273f35c206 /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:143 master:23 - cgroup devices rw,devices
350 # podman: /libpod_parent/libpod-73a4fb9769188ae5dc51cb7e24b9f2752a4af7b802a8949f06a7b2f2363ab0e9 ...
351 # Cloud Shell: /kubepods/besteffort/pod3d6beaa3004913efb68ce073d73494b0/accdf94879f0a494f317e9a0517f23cdd18b35ff9439efd0175f17bbc56877c4 /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime master:19 - cgroup cgroup rw,memory
352 # GitHub actions #9304: /actions_job/0924fbbcf7b18d2a00c171482b4600747afc367a9dfbeac9d6b14b35cda80399 /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:263 master:24 - cgroup cgroup rw,memory
353 cgroup_mounts=$(grep -E -o '/[[:alnum:]].* /sys/fs/cgroup.*.*cgroup' /proc/self/mountinfo || true)
354 if [[ -n "${cgroup_mounts}" ]]; then
355 local mount_root
356 mount_root=$(head -n 1 <<<"${cgroup_mounts}" | cut -d' ' -f1)
357 for mount_point in $(echo "${cgroup_mounts}" | cut -d' ' -f 2); do
358 # bind mount each mount_point to mount_point + mount_root
359 # mount --bind /sys/fs/cgroup/cpu /sys/fs/cgroup/cpu/docker/fb07bb6daf7730a3cb14fc7ff3e345d1e47423756ce54409e66e01911bab2160
360 local target="${mount_point}${mount_root}"
361 if ! findmnt "${target}"; then
362 mkdir -p "${target}"
363 mount --bind "${mount_point}" "${target}"
364 fi
365 done
366 fi
367 # kubelet will try to manage cgroups / pods that are not owned by it when
368 # "nesting" clusters, unless we instruct it to use a different cgroup root.
369 # We do this, and when doing so we must fixup this alternative root
370 # currently this is hardcoded to be /kubelet
371 # under systemd cgroup driver, kubelet appends .slice
372 mount --make-rprivate /sys/fs/cgroup
373 cgroup_subsystems=$(findmnt -lun -o source,target -t cgroup | grep -F "${current_cgroup}" | awk '{print $2}')
374 mount_kubelet_cgroup_root "${cgroup_subsystems}"
375 }
376
377 fix_machine_id() {
378 # Deletes the machine-id embedded in the node image and generates a new one.
379 # This is necessary because both kubelet and other components like weave net
380 # use machine-id internally to distinguish nodes.
381 log_info 'clearing and regenerating /etc/machine-id'
382 rm -f /etc/machine-id
383 systemd-machine-id-setup
384 }
385
386 fix_product_name() {
387 # this is a small fix to hide the underlying hardware and fix issue #426
388 # https://github.com/kubernetes-sigs/kind/issues/426
389 if [[ -f /sys/class/dmi/id/product_name ]]; then
390 log_info 'faking /sys/class/dmi/id/product_name to be "kind"'
391 echo 'kind' > /kind/product_name
392 mount -o ro,bind /kind/product_name /sys/class/dmi/id/product_name
393 fi
394 }
395
396 fix_product_uuid() {
397 # The system UUID is usually read from DMI via sysfs, the problem is that
398 # in the kind case this means that all (container) nodes share the same
399 # system/product uuid, as they share the same DMI.
400 # Note: The UUID is read from DMI, this tool is overwriting the sysfs files
401 # which should fix the attached issue, but this workaround does not address
402 # the issue if a tool is reading directly from DMI.
403 # https://github.com/kubernetes-sigs/kind/issues/1027
404 [[ ! -f /kind/product_uuid ]] && cat /proc/sys/kernel/random/uuid > /kind/product_uuid
405 if [[ -f /sys/class/dmi/id/product_uuid ]]; then
406 log_info 'faking /sys/class/dmi/id/product_uuid to be random'
407 mount -o ro,bind /kind/product_uuid /sys/class/dmi/id/product_uuid
408 fi
409 if [[ -f /sys/devices/virtual/dmi/id/product_uuid ]]; then
410 log_info 'faking /sys/devices/virtual/dmi/id/product_uuid as well'
411 mount -o ro,bind /kind/product_uuid /sys/devices/virtual/dmi/id/product_uuid
412 fi
413 }
414
415 select_iptables() {
416 # based on: https://github.com/kubernetes-sigs/iptables-wrappers/blob/97b01f43a8e8db07840fc4b95e833a37c0d36b12/iptables-wrapper-installer.sh
417 local mode num_legacy_lines num_nft_lines
418 num_legacy_lines=$( (iptables-legacy-save || true; ip6tables-legacy-save || true) 2>/dev/null | grep -c '^-' || true)
419 num_nft_lines=$( (timeout 5 sh -c "iptables-nft-save; ip6tables-nft-save" || true) 2>/dev/null | grep -c '^-' || true)
420 if [ "${num_legacy_lines}" -ge "${num_nft_lines}" ]; then
421 mode=legacy
422 else
423 mode=nft
424 fi
425 log_info "setting iptables to detected mode: ${mode}"
426 update-alternatives --set iptables "/usr/sbin/iptables-${mode}" > /dev/null
427 update-alternatives --set ip6tables "/usr/sbin/ip6tables-${mode}" > /dev/null
428 }
429
430 fix_certificate() {
431 local apiserver_crt_file="/etc/kubernetes/pki/apiserver.crt"
432 local apiserver_key_file="/etc/kubernetes/pki/apiserver.key"
433
434 # Skip if this Node doesn't run kube-apiserver
435 if [[ ! -f ${apiserver_crt_file} ]] || [[ ! -f ${apiserver_key_file} ]]; then
436 return
437 fi
438
439 # Deletes the certificate for kube-apiserver and generates a new one.
440 # This is necessary because the old one doesn't match the current IP.
441 log_info 'clearing and regenerating the certificate for serving the Kubernetes API'
442 rm -f ${apiserver_crt_file} ${apiserver_key_file}
443 kubeadm init phase certs apiserver --config /kind/kubeadm.conf
444 }
445
446 enable_network_magic(){
447 # well-known docker embedded DNS is at 127.0.0.11:53
448 local docker_embedded_dns_ip='127.0.0.11'
449
450 # first we need to detect an IP to use for reaching the docker host
451 local docker_host_ip
452 docker_host_ip="$( (head -n1 <(timeout 5 getent ahostsv4 'host.docker.internal') | cut -d' ' -f1) || true)"
453 # if the ip doesn't exist or is a loopback address use the default gateway
454 if [[ -z "${docker_host_ip}" ]] || [[ $docker_host_ip =~ ^127\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
455 docker_host_ip=$(ip -4 route show default | cut -d' ' -f3)
456 fi
457
458 # patch docker's iptables rules to switch out the DNS IP
459 iptables-save \
460 | sed \
461 `# switch docker DNS DNAT rules to our chosen IP` \
462 -e "s/-d ${docker_embedded_dns_ip}/-d ${docker_host_ip}/g" \
463 `# we need to also apply these rules to non-local traffic (from pods)` \
464 -e 's/-A OUTPUT \(.*\) -j DOCKER_OUTPUT/\0\n-A PREROUTING \1 -j DOCKER_OUTPUT/' \
465 `# switch docker DNS SNAT rules rules to our chosen IP` \
466 -e "s/--to-source :53/--to-source ${docker_host_ip}:53/g"\
467 `# nftables incompatibility between 1.8.8 and 1.8.7 omit the --dport flag on DNAT rules` \
468 `# ensure --dport on DNS rules, due to https://github.com/kubernetes-sigs/kind/issues/3054` \
469 -e "s/p -j DNAT --to-destination ${docker_embedded_dns_ip}/p --dport 53 -j DNAT --to-destination ${docker_embedded_dns_ip}/g" \
470 | iptables-restore
471
472 # now we can ensure that DNS is configured to use our IP
473 cp /etc/resolv.conf /etc/resolv.conf.original
474 replaced="$(sed -e "s/${docker_embedded_dns_ip}/${docker_host_ip}/g" /etc/resolv.conf.original)"
475 if [[ "${KIND_DNS_SEARCH+x}" == "" ]]; then
476 # No DNS search set, just pass through as is
477 echo "$replaced" >/etc/resolv.conf
478 elif [[ -z "$KIND_DNS_SEARCH" ]]; then
479 # Empty search - remove all current search clauses
480 echo "$replaced" | grep -v "^search" >/etc/resolv.conf
481 else
482 # Search set - remove all current search clauses, and add the configured search
483 {
484 echo "search $KIND_DNS_SEARCH";
485 echo "$replaced" | grep -v "^search";
486 } >/etc/resolv.conf
487 fi
488
489 local files_to_update=(
490 /etc/kubernetes/manifests/etcd.yaml
491 /etc/kubernetes/manifests/kube-apiserver.yaml
492 /etc/kubernetes/manifests/kube-controller-manager.yaml
493 /etc/kubernetes/manifests/kube-scheduler.yaml
494 /etc/kubernetes/controller-manager.conf
495 /etc/kubernetes/scheduler.conf
496 /etc/kubernetes/kubelet.conf
497 /kind/kubeadm.conf
498 /var/lib/kubelet/kubeadm-flags.env
499 )
500 local should_fix_certificate=false
501 # fixup IPs in manifests ...
502 curr_ipv4="$( (head -n1 <(timeout 5 getent ahostsv4 "$(hostname)") | cut -d' ' -f1) || true)"
503 log_info "detected IPv4 address: ${curr_ipv4}"
504 if [ -f /kind/old-ipv4 ]; then
505 old_ipv4=$(cat /kind/old-ipv4)
506 log_info "detected old IPv4 address: ${old_ipv4}"
507 # sanity check that we have a current address
508 if [[ -z $curr_ipv4 ]]; then
509 log_error "have an old IPv4 address but no current IPv4 address (!)"
510 exit 1
511 fi
512 if [[ "${old_ipv4}" != "${curr_ipv4}" ]]; then
513 should_fix_certificate=true
514 sed_ipv4_command="s#\b$(regex_escape_ip "${old_ipv4}")\b#${curr_ipv4}#g"
515 for f in "${files_to_update[@]}"; do
516 # kubernetes manifests are only present on control-plane nodes
517 if [[ -f "$f" ]]; then
518 sed -i "${sed_ipv4_command}" "$f"
519 fi
520 done
521 fi
522 fi
523 if [[ -n $curr_ipv4 ]]; then
524 echo -n "${curr_ipv4}" >/kind/old-ipv4
525 fi
526
527 # do IPv6
528 curr_ipv6="$( (head -n1 <(timeout 5 getent ahostsv6 "$(hostname)") | cut -d' ' -f1) || true)"
529 log_info "detected IPv6 address: ${curr_ipv6}"
530 if [ -f /kind/old-ipv6 ]; then
531 old_ipv6=$(cat /kind/old-ipv6)
532 log_info "detected old IPv6 address: ${old_ipv6}"
533 # sanity check that we have a current address
534 if [[ -z $curr_ipv6 ]]; then
535 log_error "have an old IPv6 address but no current IPv6 address (!)"
536 fi
537 if [[ "${old_ipv6}" != "${curr_ipv6}" ]]; then
538 should_fix_certificate=true
539 sed_ipv6_command="s#\b$(regex_escape_ip "${old_ipv6}")\b#${curr_ipv6}#g"
540 for f in "${files_to_update[@]}"; do
541 # kubernetes manifests are only present on control-plane nodes
542 if [[ -f "$f" ]]; then
543 sed -i "${sed_ipv6_command}" "$f"
544 fi
545 done
546 fi
547 fi
548 if [[ -n $curr_ipv6 ]]; then
549 echo -n "${curr_ipv6}" >/kind/old-ipv6
550 fi
551
552 if $should_fix_certificate; then
553 fix_certificate
554 fi
555 }
556
557 # validate state
558 validate_userns
559
560 # run pre-init fixups
561 # NOTE: it's important that we do configure* first in this order to avoid races
562 configure_containerd
563 configure_proxy
564 fix_mount
565 fix_cgroup
566 fix_machine_id
567 fix_product_name
568 fix_product_uuid
569 select_iptables
570 enable_network_magic
571
572 # we want the command (expected to be systemd) to be PID1, so exec to it
573 log_info 'starting init'
574 exec "$@"