Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

Commit

Permalink
kube-apiserver: improve reliability when upgrading standalone helm re…
Browse files Browse the repository at this point in the history
…lease

This commit attempts to improve the reliability of the upgrade process of
the self-hosted kube-apiserver when having only one controller node. If
running more than one kube-apiserver replica, the setup does not change.

Currently, kube-apiserver runs as a DaemonSet, which means that if
there is only one node, where the pod is assigned, it must be removed
before a new one will be scheduled. This causes a short outage when doing a
rolling update of kube-apiserver. During the outage, the pod checkpointer
kicks in and brings up a temporary kube-apiserver as a static pod to
recover the cluster and waits until kube-apiserver pod is scheduled on
the node. Then, it shuts down the temporary kube-apiserver pod and removes
its manifest. As there cannot be 2 instances of kube-apiserver running
at the same time on the node, the pod checkpointer is not able to wait until
the updated pod starts up, as it must shut down the temporary one. This has a
bad side-effect: if the new pod is wrongly configured (e.g. has a
non-existent flag specified), kube-apiserver will never recover, which
brings down the cluster and then manual intervention is needed.

See #72 PR for more details.

If it would be possible to run more than one instance of kube-apiserver
on a single node, that would make the upgrade process easier. When you try
to do that now, the 2nd instance will not run, as the secure port is
already bound by the first instance.

In Linux, there is a way to have multiple processes bind the same
address and port: the SO_REUSEPORT socket option. More details
under this link: https://lwn.net/Articles/542629/.

Unfortunately, kube-apiserver does not create a listening socket with
that option.

To mimic the SO_REUSEPORT option in kube-apiserver, this commit adds a
HAProxy instance as a side-container to kube-apiserver. HAProxy does
support SO_REUSEPORT, so multiple instances can bind to the same address
and port and then traffic between the processes will be equally
distributed by the kernel.

As kube-apiserver still runs on the host network, we need to either
randomize the IP address or the port it listens on, in order to be able
to run multiple instances on a single host.

In this case, randomizing the IP address for binding is easier than
randomizing the port, as kube-apiserver advertises its own IP address and
port where it binds to the 'kubernetes' service in 'default' namespace
in the cluster, which means that pods on the cluster would bypass
HAProxy and connect to kube-apiserver directly, which requires opening
such random ports on the firewall for the controller nodes, which is
undesired.

If we randomize IP address to bind, we can use the loopback interface, which
by default in Linux has a /8 IP address assigned, which means that we can
select a random IP address like 127.155.125.53 and bind to it.

To avoid advertising localhost IP address to the cluster, which obviously
wouldn't work, we use --advertise-address kube-apiserver flag, which
allows us to override IP address advertised to the cluster and always
set it to the address where HAProxy is listening, for example using
the HOST_IP environment variable pulled from the Kubernetes node information
in the pod status.

HAProxy runs in TCP mode to minimize the required configuration
and possible impact of misconfiguration. In my testing, I didn't
experience any breakage because of using a proxy, however, we may need to
pay attention to parameters like session timeouts, to make sure they
don't affect connections.

Once we are able to run multiple instances of kube-apiserver on a single
node, we need to change the way we deploy the self-hosted kube-apiserver
from DaemonSet to Deployment to allow running multiple instances on a
single node.

As running multiple instances on a single node should only be done
temporarily, as single kube-apiserver is able to scale very well, we add
podAntiAffinity to make sure that replicas of Deployment are equally
spread across controller nodes. This also makes sense, as each
kube-apiserver instance consumes at least 500MB of RAM, which means that
if a controller node has 2GB of RAM, it might be not enough to run 2
instances for a longer period, meaning at least 4GB of RAM are
recommended for the controller nodes. This also make sense from a
stability point of view, as with many workloads, controller node
resource usage will grow.

By default, the number of replicas equals the number of controller nodes.

For podAntiAffinity, preferredDuringSchedulingIgnoredDuringExecution is
used instead of requiredDuringSchedulingIgnoredDuringExecution, as with
a single controller node, we should actually allow multiple
instances on a single node to perform graceful updates.

See #90 for more details.

If there is just one replica of kube-apiserver requested, we set
maxUnavailable: 0, to make sure that there is always at least one
instance running. We also add a PodDisruptionBudget to which also makes
sure that there is at least one instance running. If there are more
replicas requested, then PodDisruptionBudget controls that only one
kube-apiserver can be shut down at a time, to avoid overloading other
running instances.

On platforms where kube-apiserver needs to be exposed on all interfaces
(e.g. Packet), we switch kube-apiserver in-cluster port to 7443 (on this
port, kube-apiserver will listen on random local IP address and HAProxy
will listen on the Node IP), then in addition HAProxy will also listen on
0.0.0.0:6443 to export the API on all interfaces (including the public
ones). This is required as you cannot have 2 processes, one listening
on 127.0.0.1:6443 and another on 0.0.0.0:6443.

On platforms with private network only, where kube-apiserver is accessed
via a load balancer (e.g. AWS), port setup remains the same.

The whole setup would be much simpler, if kube-apiserver would support
SO_REUSEPORT. I have opened an upstream issue about that and implemented a
working PoC. More details here: kubernetes/kubernetes#88785.

With SO_REUSEPORT support in kube-apiserver, there is no need to run
HAProxy as a side-container, no need for listening on random IP address
and no need to use multiple ports, which simplifies the whole solution.
However, the change from DaemonSet to Deployment and pod anti affinities are
still needed.

Signed-off-by: Mateusz Gozdek <mateusz@kinvolk.io>
  • Loading branch information
invidian committed Mar 10, 2020
1 parent 3a9c455 commit f95da19
Show file tree
Hide file tree
Showing 10 changed files with 243 additions and 35 deletions.
36 changes: 19 additions & 17 deletions assets/lokomotive-kubernetes/bootkube/assets.tf
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,25 @@ resource "template_dir" "bootstrap-manifests" {
resource "local_file" "kube-apiserver" {
filename = "${var.asset_dir}/charts/kube-system/kube-apiserver.yaml"
content = templatefile("${path.module}/resources/charts/kube-apiserver.yaml", {
hyperkube_image = var.container_images["hyperkube"]
pod_checkpointer_image = var.container_images["pod_checkpointer"]
etcd_servers = join(",", formatlist("https://%s:2379", var.etcd_servers))
cloud_provider = var.cloud_provider
service_cidr = var.service_cidr
trusted_certs_dir = var.trusted_certs_dir
ca_cert = base64encode(tls_self_signed_cert.kube-ca.cert_pem)
apiserver_key = base64encode(tls_private_key.apiserver.private_key_pem)
apiserver_cert = base64encode(tls_locally_signed_cert.apiserver.cert_pem)
serviceaccount_pub = base64encode(tls_private_key.service-account.public_key_pem)
etcd_ca_cert = base64encode(tls_self_signed_cert.etcd-ca.cert_pem)
etcd_client_cert = base64encode(tls_locally_signed_cert.client.cert_pem)
etcd_client_key = base64encode(tls_private_key.client.private_key_pem)
enable_aggregation = var.enable_aggregation
aggregation_ca_cert = var.enable_aggregation == true ? base64encode(join(" ", tls_self_signed_cert.aggregation-ca.*.cert_pem)) : ""
aggregation_client_cert = var.enable_aggregation == true ? base64encode(join(" ", tls_locally_signed_cert.aggregation-client.*.cert_pem)) : ""
aggregation_client_key = var.enable_aggregation == true ? base64encode(join(" ", tls_private_key.aggregation-client.*.private_key_pem)) : ""
hyperkube_image = var.container_images["hyperkube"]
pod_checkpointer_image = var.container_images["pod_checkpointer"]
etcd_servers = join(",", formatlist("https://%s:2379", var.etcd_servers))
cloud_provider = var.cloud_provider
service_cidr = var.service_cidr
trusted_certs_dir = var.trusted_certs_dir
ca_cert = base64encode(tls_self_signed_cert.kube-ca.cert_pem)
apiserver_key = base64encode(tls_private_key.apiserver.private_key_pem)
apiserver_cert = base64encode(tls_locally_signed_cert.apiserver.cert_pem)
serviceaccount_pub = base64encode(tls_private_key.service-account.public_key_pem)
etcd_ca_cert = base64encode(tls_self_signed_cert.etcd-ca.cert_pem)
etcd_client_cert = base64encode(tls_locally_signed_cert.client.cert_pem)
etcd_client_key = base64encode(tls_private_key.client.private_key_pem)
enable_aggregation = var.enable_aggregation
aggregation_ca_cert = var.enable_aggregation == true ? base64encode(join(" ", tls_self_signed_cert.aggregation-ca.*.cert_pem)) : ""
aggregation_client_cert = var.enable_aggregation == true ? base64encode(join(" ", tls_locally_signed_cert.aggregation-client.*.cert_pem)) : ""
aggregation_client_key = var.enable_aggregation == true ? base64encode(join(" ", tls_private_key.aggregation-client.*.private_key_pem)) : ""
replicas = length(var.etcd_servers)
expose_on_all_interfaces = var.expose_on_all_interfaces
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ apiserver:
enableAggregation: ${enable_aggregation}
serviceCIDR: ${service_cidr}
trustedCertsDir: ${trusted_certs_dir}
replicas: ${replicas}
exposeOnAllInterfaces: ${expose_on_all_interfaces}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{{- if eq (int .Values.apiserver.replicas) 1 }}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
name: kube-apiserver
spec:
minAvailable: 1
selector:
matchLabels:
k8s-app: kube-apiserver
{{- end }}
Original file line number Diff line number Diff line change
@@ -1,20 +1,42 @@
{{ define "port" }}
{{- if and .Values.apiserver.exposeOnAllInterfaces (eq (int .Values.apiserver.replicas) 1) -}}
7443
{{- else -}}
6443
{{- end -}}
{{ end }}
apiVersion: apps/v1
{{- if eq (int .Values.apiserver.replicas) 1 }}
kind: Deployment
{{- else }}
kind: DaemonSet
{{- end }}
metadata:
name: kube-apiserver
namespace: kube-system
labels:
tier: control-plane
k8s-app: kube-apiserver
spec:
{{- if eq (int .Values.apiserver.replicas) 1 }}
replicas: 1
{{- end }}
selector:
matchLabels:
tier: control-plane
k8s-app: kube-apiserver
{{- if eq (int .Values.apiserver.replicas) 1 }}
strategy:
{{- else }}
updateStrategy:
{{- end }}
type: RollingUpdate
rollingUpdate:
{{- if eq (int .Values.apiserver.replicas) 1 }}
maxUnavailable: 0
{{- else }}
maxUnavailable: 1
{{- end }}
template:
metadata:
labels:
Expand All @@ -24,6 +46,37 @@ spec:
checkpointer.alpha.coreos.com/checkpoint: "true"
seccomp.security.alpha.kubernetes.io/pod: 'docker/default'
spec:
affinity:
podAntiAffinity:
{{- if eq (int .Values.apiserver.replicas) 1 }}
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: tier
operator: In
values:
- controlplane
- key: k8s-app
operator: In
values:
- kube-apiserver
topologyKey: kubernetes.io/hostname
{{- else }}
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: tier
operator: In
values:
- controlplane
- key: k8s-app
operator: In
values:
- kube-apiserver
topologyKey: kubernetes.io/hostname
{{- end }}
hostNetwork: true
nodeSelector:
node.kubernetes.io/master: ""
Expand All @@ -37,6 +90,44 @@ spec:
- name: kube-apiserver
image: {{ .Values.apiserver.image }}
command:
{{- if eq (int .Values.apiserver.replicas) 1 }}
- /bin/sh
- -c
- |
set -xe
exec /hyperkube \
kube-apiserver \
--advertise-address=$(POD_IP) \
--allow-privileged=true \
--anonymous-auth=false \
--authorization-mode=RBAC \
--bind-address=$(cat /run/kube-apiserver/address) \
--client-ca-file=/etc/kubernetes/secrets/ca.crt \
--cloud-provider={{ .Values.apiserver.cloudProvider }} \
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultTolerationSeconds,DefaultStorageClass,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota,Priority,PodSecurityPolicy \
--etcd-cafile=/etc/kubernetes/secrets/etcd-client-ca.crt \
--etcd-certfile=/etc/kubernetes/secrets/etcd-client.crt \
--etcd-keyfile=/etc/kubernetes/secrets/etcd-client.key \
--etcd-servers={{ .Values.apiserver.etcdServers}} \
--insecure-port=0 \
--kubelet-client-certificate=/etc/kubernetes/secrets/apiserver.crt \
--kubelet-client-key=/etc/kubernetes/secrets/apiserver.key \
--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \
--secure-port={{ template "port" . }} \
--service-account-key-file=/etc/kubernetes/secrets/service-account.pub \
--service-cluster-ip-range={{ .Values.apiserver.serviceCIDR }} \
--tls-cert-file=/etc/kubernetes/secrets/apiserver.crt \
--tls-private-key-file=/etc/kubernetes/secrets/apiserver.key \
{{ if .Values.apiserver.enableAggregation -}}
--proxy-client-cert-file=/etc/kubernetes/secrets/aggregation-client.crt \
--proxy-client-key-file=/etc/kubernetes/secrets/aggregation-client.key \
--requestheader-client-ca-file=/etc/kubernetes/secrets/aggregation-ca.crt \
--requestheader-extra-headers-prefix=X-Remote-Extra- \
--requestheader-group-headers=X-Remote-Group \
--requestheader-username-headers=X-Remote-User \
{{ end -}}
--storage-backend=etcd3
{{- else }}
- /hyperkube
- kube-apiserver
- --advertise-address=$(POD_IP)
Expand Down Expand Up @@ -69,6 +160,7 @@ spec:
- --requestheader-group-headers=X-Remote-Group
- --requestheader-username-headers=X-Remote-User
{{- end }}
{{- end }}
env:
- name: POD_IP
valueFrom:
Expand All @@ -81,6 +173,78 @@ spec:
- name: ssl-certs-host
mountPath: /etc/ssl/certs
readOnly: true
{{- if eq (int .Values.apiserver.replicas) 1 }}
- name: data
mountPath: /run/kube-apiserver
- name: haproxy
image: haproxy:2.1.3-alpine
volumeMounts:
- name: data
mountPath: /run/kube-apiserver
command:
- /bin/sh
- -c
- |
set -xe
export ADDRESS=$(cat /run/kube-apiserver/address)
# Make sure initContainer generated kube-apiserver address.
if [ -z $ADDRESS ]; then
echo "ADDRESS not found"
exit 1
fi
echo "Connecting to $ADDRESS:{{ template "port" . }}"
# We use TCP readiness probe and HAProxy does not reject connections if no backend is available,
# so we wait until kube-apiserver is available here, so readiness of haproxy container represents
# readiness of kube-apiserver, as kube-apiserver cannot have readiness probe set, as it listens
# on random IP address.
until nc -zv $ADDRESS {{ template "port" . }}; do sleep 1; done
echo "Connected"
# From https://github.com/docker-library/haproxy/blob/master/Dockerfile-debian.template#L70
exec haproxy -f /run/kube-apiserver/haproxy.cfg
readinessProbe:
tcpSocket:
port: {{ template "port" . }}
initContainers:
- name: config-generator
image: haproxy:2.1.3-alpine
command:
- /bin/sh
- -c
- |
set -xe
export ADDRESS="127.$(shuf -i 0-255 -n 1).$(shuf -i 0-255 -n 1).$(shuf -i 1-253 -n 1)"
echo $ADDRESS > /run/kube-apiserver/address
echo "defaults
# Do TLS passthrough
mode tcp
# Required values for both frontend and backend
timeout connect 5s
timeout client 30s
timeout client-fin 30s
timeout server 30s
timeout tunnel 21d
frontend kube-apiserver-internal
bind $POD_IP:{{ template "port" . }}
default_backend kube-apiserver
{{- if .Values.apiserver.exposeOnAllInterfaces }}
frontend kube-apiserver-external
bind 0.0.0.0:6443
default_backend kube-apiserver
{{ end }}
backend kube-apiserver
server 1 $ADDRESS:{{ template "port" . }} check" > /run/kube-apiserver/haproxy.cfg
volumeMounts:
- name: data
mountPath: /run/kube-apiserver
env:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
{{- end }}
securityContext:
runAsNonRoot: true
runAsUser: 65534
Expand All @@ -91,3 +255,7 @@ spec:
- name: ssl-certs-host
hostPath:
path: {{ .Values.apiserver.trustedCertsDir }}
{{- if eq (int .Values.apiserver.replicas) 1 }}
- name: data
emptyDir: {}
{{- end }}
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ apiserver:
aggregationFlags:
serviceCIDR: 10.0.0.0/24
trustedCertsDir: /usr/share/ca-certificates
replicas: 1
# If this is true, kube-apiserver will be exposed on HostIP on port 7443 to the cluster
# service (kubernetes.default.svc) and on all interfaces on port 6443.
# If false, it will be exposed only on HostIP on port 6443.
exposeOnAllInterfaces: false
6 changes: 6 additions & 0 deletions assets/lokomotive-kubernetes/bootkube/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,9 @@ variable "external_apiserver_port" {
type = number
default = 6443
}

variable "expose_on_all_interfaces" {
description = "If true, kube-apiserver will be exposed on all controller node interfaces on port 6443. If false, it will be exposed only one kubelet's node IP."
type = bool
default = false
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ module "bootkube" {
certs_validity_period_hours = var.certs_validity_period_hours

container_arch = var.os_arch

expose_on_all_interfaces = true
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,9 @@ storage:
-A INPUT -p tcp --dport 2380 -j ACCEPT
-A INPUT -p tcp --dport 2381 -j ACCEPT
-A INPUT -p tcp --dport 6443 -j ACCEPT
%{~ if controllers == "1" ~}
-A INPUT -p tcp --dport 7443 -j ACCEPT
%{~ endif }
-A INPUT -p tcp --dport 10250 -j ACCEPT
-A INPUT -p tcp --dport 10256 -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ data "template_file" "controller-configs" {
ssh_keys = jsonencode(var.ssh_keys)
k8s_dns_service_ip = cidrhost(var.service_cidr, 10)
cluster_domain_suffix = var.cluster_domain_suffix
controllers = var.controller_count

# we need to prepend a prefix 'docker://' for arm64, because arm64 images
# on quay prevent us from downloading ACI correctly.
Expand Down
Loading

0 comments on commit f95da19

Please sign in to comment.