I was helping a customer improve their capacity management practice for Red Hat OpenShift Virtualization. Research in this space was difficult because to do capacity management, you must understand how resources are managed by Kubernetes and, in particular, for the virtualization use case. In this article, I share the lessons I learned from this experience. .In particular, I explore memory, CPU, network and storage considerations for nodes, pods and virtual machines (when applicable). That being said, most of the discussion focuses on memory, which is often the most scarce resource in a Red Hat Openshift Virtualization deployment (and recently it has become the most expensive one, too).
When it comes to capacity management, I attempt to answer the following questions:
- Cluster capacity availability: How many more virtual machines (VM) of this shape can a cluster support?
- Cluster growth rate: Given the current adoption rate, when will the cluster run out of capacity?
- Cluster overcommit optimization: Given the current workload profile and a certain level of acceptable risk, what level of memory overcommit would be possible?
All the dashboards, alerts, and prometheus recording rules discussed in this article can be found in this accompanying repository.
Before discussing each resource, it's best to recall the concept of compressible and incompressible resources as these categories inform us of how we should deal with resource management and noisy neighbor configurations.
Compressible and incompressible resources
Compressible resources are resources limited in a given period of time, but renew themselves in the next period of time. Examples of these resources include CPUs, I/O bandwidth, network bandwidth, GPUs,and so on. As such, these resources are unlimited as long as the process using it is willing to wait for the next time cycle.
Incompressible resources are resources that have an absolute limit after which no more of that resources is available for any potential consumers. Examples include memory, disk space, and so on.
It's important to understand that compressible and incompressible resources need to be managed differently when it comes to the "noisy neighbor" problem (resource contention between different processes, or perhaps VMs, in this case).
The recommended way to manage incompressible resources is to ensure that every consumer gets a fair share of the resource in a given time period when there's resource contention. But when there isn't resource contention, a single consumer should be able to consume as much as it wants. For the CPU use case, this is managed in Kubernetes by setting a request on the container. This configuration translates to a complete fair share cgroup, which ensures fair sharing.
The fair sharing cgroup does not limit the CPU consumption when there is no resource contention, allowing a single process to consume as many CPUs as it can. Having a CPU limit prevents that, forcing the process to consume up to the given limit. This is why it is almost always a bad idea to put a limit on CPU.
The recommended way to manage compressible resources is to ensure that processes cannot overrun the use of that resource and, in doing so, deny due access to other processes. This is normally facilitated by setting the resource in the Guarantee QoS, where both request and limit are set to the same value. This applies in particular to memory, which is probably the most scarce and expensive incompressible resource. Setting a limit on memory has the additional consideration that if the application requests more memory than the set limit, then the process is killed by the OOM daemon.
Memory management
As described previously, memory is a bit special as it is a scarce, valuable, incompressible resource. For this reason, we need to explore in depth how memory is managed at different aggregation levels: At the node, pod, and VM.
Before we delve into the details, let's briefly talk about cgroups (control groups). A cgroup is the main mechanism available to slice and assign memory portions from the host to a group of processes. Because they are hierarchical, cgroups can be nested into other cgroups. For example, for each pod, a cgroup is created within the pod cgroup slice, and for each container in that pod, a cgroup is created within that pod cgroup.
An enhanced version of cgroups, known as cgroups v2, is available in Kubernetes and OpenShift. cgroups v2 have the following settings:
| Setting | Without MemoryQoS | With MemoryQoS | Behavior |
|---|---|---|---|
| memory.max | limits.memoryIf not set defaults to kubepod.slice, i.e. allocatable | limits.memory If not set defaults to kubepod.slice, i.e. allocatable | Crossing this threshold causes the OOM reaper to kill this process |
| memory.high | Not set, defaults to memory.max | If QoS burstable, set to requests + memoryThrottlingFactor × (limits − requests) If QoS Best Effort set to allocatable * memoryThrottlingFactor | Crossing this threshold cause the kernel to aggressively reclaim all the reclaimable memory |
| memory.low | 0 | If QoS burstable, set to requests.memoryelse set to 0 | Soft protection, kernel tries not to reclaim below this threshold (i.e. will reclaim from other groups if possible) |
| memory.min | 0 | If QoS guaranteed, set to limits.memory, else set to 0 | Kernel never reclaims below this value. |
| memory.swap.max | If QoS Burstable set to (request / nodeMemoryCapacity) × nodeSwapCapacityElse set to 0 (i.e. no swap) | Maximum amount of non-reclaimable memory which can be swapped. |
Notice that currently in OpenShift (version 4.22 at the time of the writing), while cgroups v2 are available, the MemoryQoS feature is not available.
Cgroups help slice memory into separate portions and assign it to workloads. But, we also need to understand how the kernel manages memory. Here, things can become extremely detail oriented and complicated. To keep it simple, we adopt the following mental model: A process has 2 types of memory: Reclaimable (file caches and other temporary kernel structure) and non-reclaimable (the actual memory used by the process).
Reclaimable memory is classified by the OS into 2 ways: Hot (recently used) and cold (not used for some time). The OS assumes cold memory pages can be reclaimed with no impact to the process. Non-reclaimable memory can be in DRAM (the norm) or moved to secondary storage with swap or computer access link (CLX) technologies. CLX requires special hardware and provides better performance than swap. CLX will be enabled in a future version of Red Hat OpenShift.
The following memory runtime metrics help observe the concept described above:
- Used memory:
container_memory_usage_bytes - Non reclaimable memory in DRAM:
container_memory_rss - Non-reclaimable memory in swap:
container_memory_swap - Reclaimable memory hot:
container_memory_total_active_file_bytes - Reclaimable memory cold:
container_memory_total_inactive_file_bytes
It's a normal practice to use container_memory_working_set_bytes as the metric to measure the memory used by a process. The formula for memory working set is:
container_memory_working_set_bytes = container_memory_usage_bytes - container_memory_total_inactive_file_bytesThe meaning of this metric is, really, the amount of memory that this process needs if we don't want to slow its execution due to reclaimed memory and missed memory pages.
Notice that swapped out memory does not count against the cgroup accounting and the risk of being OOM (in cgroup v2). Also, for the remainder of this article, we assume that swap is disabled (the default on Red Hat OpenShift). As a result, we are not going to focus on this capability.
Node memory management
The node is sliced into 2 major memory cgroups: system.slice and kubepods.slice. The system.slice cgroup is dedicated to OS and node critical services while the kubepod.slice cgroup is dedicated to the workload running on the node.
The system cgroup is unlimited when it comes to memory management, while the workload cgroup is capped at:
node capacity - (system.reserved + kube-reserved)Aside from cgroup, the node has another self-protection mechanism, called eviction. The actual capacity that the node makes available to a workload is less than the size of the pod cgroup by the hard eviction threshold. What's allocatable is calculated with the following formula:
Allocatable = node capacity - system-reserved - kube reserved - hard eviction thresholdFigure 1 depicts these configurations:
In OpenShift, the systemreserved and kube-reserved values are automatically calculated based on the size of the node.
The relevant metrics to track the node memory configuration are found in the following table:
- Node capacity:
kube_node_status_capacity{resource="memory"} - Node allocatable:
kube_node_status_allocatable{resource="memory"} - System and kube reserved: Approximately
node-capacity - node-allocatable - Eviction hard threshold: Not exposed as metric
The relevant metrics to track the node memory layout at runtime are the same as seen above, provided one selects the correct slice: /system.slice and /kubepods.slice. For example, for used memory, the Prometheus expressions would be container_memory_usage_bytes{id="/system.slice"} and container_memory_usage_bytes{id="/kubepods.slice"}.
Node memory dashboard
A dashboard showing memory decomposition is useful when exploring how memory is being used by nodes. This dashboard, show in figure 2, is included in this article's Git repository.
Node memory alerts
For a Red Hat OpenShift administrator, it's important to be alerted when nodes are under stress. Red Hat OpenShift includes the following alerts as it relates to node memory management: KubeNodePressure, KubeNodeEviction, and SystemMemoryExceedsReservation. These alerts are reactive to conditions ongoing in the environment. We can complement these with a set of proactive alerts of our own.
In terms of an alert, the signal that something is about to go wrong include memory utilization (non-reclaimable memory plus reclaimable host memory) approaching the hard eviction threshold, and high churning of memory pages (a sign that the kernel is frantically trying to free memory). In addition, a high count of memory corrective and non-corrective errors might indicate that a memory bank (the actual memory chip) is about to give up. These alerts are included in this article's Git repository.
Pod memory management
Pods and containers in pods are organized in a hierarchical cgroup system, as shown in figure 3:.
Each cgroup works as described in the introductory section on memory management.
A relatively new feature allows for setting resources at the pod level instead of at the individual container level. This new approach can make resource accounting simpler, especially when container sidecars are dynamically added to the pod.
We can visualize the memory layout for a pod or a container with a dashboard similar to figure 4::
When we look at the runtime behavior of memory, the same considerations we discuss for a node apply. In particular, when a memory limit is set, we probably want to be alerted when the pod is getting close to being OOM terminated. The alerts (ContainerMemoryApproachingOOM and PodMemoryApproachingOOM) exist for this very purpose.
Knowing the memory request and limit for a pod, and the historical consumption allows us to estimate the best sizing for a pod.
Read Optimize workloads with right-sizing recommendations for approaches for right-sizing pods.
VM memory management
As VMs run within pods in Red Hat OpenShift Virtualization, there are additional considerations for memory management for VM instances. The memory request for a VM pod consists of 2 factors: The amount of memory needed by the VM domain and the estimated memory used by the QEMU and other virt-launcher pod processes (often referred to as kubevirt memory overhead). "Domain" is the libvirt terminology to indicate both the running VM as well as the VM definition. Figure 5 illustrates this principle:
Because QEMU enforces that the memory used by the VM never exceeds the memory defined in the VM domain definition and assuming that the KubeVirt memory overhead is estimated correctly and assuming no memory overcommitment is defined, the memory used by this pod can never exceed the requested memory. Thanks to technologies such as free page reporting (FPR) (for Linux) and KSM zero pages (for Windows), the used memory will actually be less, reflecting what the guest OS is currently using.
Given the above consideration, and in case of no memory overcommitment, setting a limit to the memory used by the pod becomes redundant. In fact, by default Red Hat OpenShift Virtualization does not set one.
Thanks to the QEMU quest tools, we gain an understanding of the memory runtime composition within the guest OS. These details are exposed through a set of metrics with names that should sound familiar at this point:
- Available memory:
kubevirt_vmi_memory_available_bytes - Free memory:
kubevirt_vmi_memory_unused_bytes - Reclaimable memory:
kubevirt_vmi_memory_usable_bytes-kubevirt_vmi_memory_unused_bytes - Non reclaimable memory:
kubevirt_vmi_memory_used_bytes
The dashboard shown in figure 6 enables gaining insight on how the guest OS is managing memory:
The KubeVirtVMGuestMemoryAvailableLow and KubeVirtVMGuestMemoryPressure alerts are available for situations in which the guest is running out of memory and when the guest is churning with a lot of page reclamation operations. We added an alert called VirtLauncherOverheadExceedsEstimate to trigger when the actual overhead crosses the estimated overhead.
Compressible resource considerations
Compressible resources are easier to manage than uncompressible ones. Essentially, we need a way to make sure that a fair sharing policy is in place and that pressure signals exist to flag processes that have been waiting for too long. We are going to focus on 3 areas in particular: CPU, networking bandwidth, and storage bandwidth. Again, we'll see how each applies to the 3 scopes we've been using: Node, pod and container, and VM (when applicable).
CPU considerations
A fair sharing mechanism exists for CPUs. It's controlled by the cpu.weight setting in cgroups v2, and it's set by the kubelet based on cpu.request.
As for memory, the time a process needs to wait for the CPU best captures the saturation concept. This is also known as pressure stall information (PSI). The CPU PSI can be captured with the following metrics:
- Node:
container_pressure_io_waiting_seconds_total{id="/"} - Container:
container_pressure_io_waiting_seconds_total{ container!="POD", container!=""} - QEMU process:
kubevirt_vmi_vcpu_wait_seconds_total
KubeVirt configures several alerts for monitoring the PSI information of the guest OS internally, so there's no need to configure additional items. We did, however, add alerts for NodeCPUPressureHigh, NodeCPUPressureCritical, VMvCPUDelayHigh, as seen here. We have not created similar alerts for the pod level, because they tend to become too noisy
Network bandwidth considerations
Network bandwidth is yet another compressible resource. Some considerations of note include:
- Bandwidth sharing is a problem when it comes to a physical NIC. It doesn't make sense to measure saturation of logical interfaces. As a result, we ignore the pod and the VM scope.
- A host may have several physical NICs and each may not be a factor for the analysis that we want to perform. It's important to understand NIC topology at the host level.
- Not all NICs correctly report their theoretical bandwidth (useful to understand saturation).
- Historically in Kubernetes, there is no fairsharing mechanism for network bandwidth, and the same can be said for Red Hat OpenShift and OVN-K. The OVN-K EgressQoS feature helps in this department (however, it's out of scope for this article).
Given that we cannot accurately configure and monitor fair sharing of network bandwidth, we focus on alerting at the node level. Red Hat OpenShift already has a NodeNetworkReceiveErrs alert for packet errors. If you install the network observability operator, then an additional PacketDropsByDevice_PerNodeWarning alert is available to reports on packet drops. We can add a few alerts related to bandwidth saturation: NodeNICSaturationWarning, NodeNICSaturationCritical.
Storage I/O bandwidth considerations
Red Hat OpenShift already has good monitoring with regards to node local storage. When it comes to VMs, however, storage is typically supplied by SAN or NAS. Either way, storage is remote to the cluster and presented over IP or fiber channel. We already have metrics on IP interfaces (NICs), but it might be desirable to monitor the fiber channel host bus adapters (HBA).
With storage being remote and each disk dedicated to a VM, the actual resource being shared here is the network or fiber channel bandwidth, not so much the disk I/O bandwidth (disks are not shared). Being network and fiber channel bandwidth a compressible resource, it would make sense to set up a fair share mechanism. However, this isn't really possible at the moment. Some CSI vendors allow for configuring a per-LUN maximum bandwidth, and QEMU disk I/O limit is in the feature pipeline for Red Hat OpenShift Virtualization. Both mechanisms put hard caps on I/O, as opposed to setting fairshare policies, making them non-ideal.
Storage is often multipathed. Additional configuration needs to be performed to enable fibre channel and dm-multipath storage metrics connections (potentially also for NVMe over IP, however these steps aren't documented in the article repo). All of these node exporter collectors will be enabled by default in future versions of Red Hat OpenShift.
Once the metrics can be collected, it makes sense to alert on processes waiting for storage (IOPressure), storage starvation (storage bandwidth being depleted) and multipath degradation. The following alerts have been created for this purpose: NodeIOPressureWarning, NodeIOPressureCritical, NodeFCHBASaturationWarning, NodeFCHBASaturationCritical, MultipathPathDegraded, MultipathPathCritical, MultipathDeviceSuspended.
Cluster capacity availability
How do you know when a VM can be added to a cluster? Or more generally, how many VMs of a given shape (CPU/memory) can we add to a cluster? Before we can answer that, we need to be able to know the current available capacity of the node.
First, recall the concept of "node allocatable", introduced in the previous sections about node memory management. Node allocatable is the proportion of node capacity that's allocatable to the workloads. It's calculated by subtracting the node reserved and eviction hard threshold capacity from the total capacity of the node.
We can use the following formulas to track capacity:
- cluster-total-capacity: (sum of node-allocatable) - (number-of-nodes-that-can-be-lost node allocatable). In this context, the number-of-nodes-that-can-be-lost represents the number of nodes we would be able to take offline for planned or unplanned maintenance without creating a capacity issue in the cluster.
- cluster-used-capacity: (sum of the workload request)
- cluster-available-capacity: cluster-total-capacity - cluster-used-capacity
It might be useful to further drill down on the cluster-used-capacity formula to differentiate between VM workloads and other workloads. In a cluster fully dedicated to Red Hat OpenShift Virtualization, the non-VM workloads are usually DaemonSets and operators (and possibly other components of the control plane) and represent the cost of running the cluster with the desired configuration.
- VM-used-capacity: (sum of VM workloads requests)
- non-VM-used capacity: (sum of non-VM workloads requests)
The formulas for the above expression are included in the Git repository.
Having the available capacity, we can answer the question of how many more VMs of a given shape can fit in the cluster. The formula is the following:
nVMs: min (cluster-available-capacity-memory / vm-memory * memory-overcommit, cluster-available-capacity-cpu / vm-cpu * cpu-overcommit)Figure 7 displays a dashboard for these concepts:
Cluster growth rate
In this section, we are trying to predict when we will run out of capacity given the past trend. This type of information is useful for bare metal deployments of Red Hat OpenShift in which adding a node may require a long procurement cycle and therefore it needs to be planned well in advance.
For this prediction, we need to divide the available-capacity by the slope at which available-capacity decreases, keep the result on when it's positive (ignore the result if the slope is 0 or increasing), and finally format the result to seconds. The resulting query:
days-to-exhaustion-memory: (
(
- cluster:available_capacity_memory:bytes
/ deriv(cluster:available_capacity_memory:bytes[$observation_period])
and
deriv(cluster:available_capacity_memory:bytes[$observation_period]) < 0
)
or vector(+Inf)
) / 86400
days-to-exhaustion-cpu: (
(
- cluster:available_capacity_cpu:cores
/ deriv(cluster:available_capacity_cpu:cores[$observation_period])
and
deriv(cluster:available_capacity_cpu:cores[$observation_period]) < 0
)
or vector(+Inf)
) / 86400The union of the 2 queries:
days-to-exhaustion: min(
label_replace(
(
- cluster:available_capacity_memory:bytes
/ deriv(cluster:available_capacity_memory:bytes[$observation_period])
and
deriv(cluster:available_capacity_memory:bytes[$observation_period]) < 0
)
or vector(+Inf),
"resource", "memory", "__name__", ".*"
)
or
label_replace(
(
- cluster:available_capacity_cpu:cores
/ deriv(cluster:available_capacity_cpu:cores[$observation_period])
and
deriv(cluster:available_capacity_cpu:cores[$observation_period]) < 0
)
or vector(+Inf),
"resource", "cpu", "__name__", ".*"
)
) / 86400Figure 8 displays a dashboard for the above concepts:
Cluster overcommit optimization
As it's probably intuitive, with no overcommitment, we never risk exhausting the node resources. However, at the same time, we waste some resources. It's worth posing the question: Given a certain level of acceptable risk, which overcommitment level would be possible?
Let's keep in mind that all we can do here is estimating based on past behavior and that any level of overcommitment carries a risk. For CPU, the risk is that the workload will be slowed down. For memory, the risk is that the workload will be OOM-killed and restarted somewhere else.
For this estimation, we take a statistical approach. Observing the VM for a certain period of time, we can calculate the statistical volatility, or better, standard deviation. The standard deviation and an assumption on the sample distribution gives us the probability that a VM resource usage will be below a certain threshold. Inverting the formula, we can ask the question: Assuming we are willing to take the chance that 95% of the time, the VM will not cross a resource threshold, what is that threshold? Identifying that threshold value tells us what overcommit level we can achieve.
Furthermore, because we are observing multiple VMs at the same time, we need to calculate the aggregate standard deviation, and the probability that a given threshold will be crossed.
In more formal terms:
Given D defined as the sum of domain memory:
Given M defined at the sum of the average consumption over a period of observation time:
Given S defined as the standard deviation of the sum of the samples, calculated as the root square of the sum of the variances:
Then the recommended overcommit (R) with probability p of having not having an issue:
Where z(p) is the z-score for the normal distribution. The z-score function returns “how many standard deviations from the mean” a given probability sits in the bell curve.
The approach we used above to calculate the aggregate standard deviation assumes total independence of the VMs. But for some VMs, the way the VMs’ resources move can and will be correlated. If we want to take into account the correlation, we should use this formula for S:
Finally, with the standard z-score we used, we are assuming normal distribution for the resource load. This might be fine for a web server, but it’s not true for, for example, a batch workload.
The Chebyshev/Cantelly factor:
is more conservative and accounts for any distribution or a mix of distributions. So it’s the formula we need to apply. To achieve our most conservative formula, for the recommended overcommit level, given a probability p of not having an issue is:
This approach can be used for both memory and CPU. The formulas for CPU are:
For the central limit theorem, the sum of samples that follow unknown distributions tend to align with the normal distribution. As a heuristic, one could use the threshold of 100 VMs: Below this threshold, use the Chebyshev formula. Conversively, above this threshold, use the z-score formula. It is recommended, however, to test this theory with a real cluster and a real workload to confirm the results matches the desired range.
With the above formulas, we can build an overcommit recommendation dashboard (this dashboard can be found in the article's Git repository):
Conclusion
In this article, we discussed resource management and capacity management for Red Hat OpenShift Virtualization. My hope is that these shared considerations make these practices simpler to adopt in your own organization.
We covered a lot of ground, but there are areas that weren't addressed in detail. In particular:
- Memory QoS, which will be activated in Red Hat OpenShift soon
- CLX for memory, an upcoming feature
- Memory swap
- Consideration on NVME over IPs
Perhaps these topics will be the subjects of a future article.