面试题答案
一键面试#!/bin/bash
# 日志文件路径
LOG_FILE="pod_resource_monitor.log"
# 存储已调整Pod的数组
ADJUSTED_PODS=()
# 函数:检查Pod是否已调整
function is_pod_adjusted {
local pod_name=$1
for adjusted_pod in "${ADJUSTED_PODS[@]}"; do
if [ "$adjusted_pod" == "$pod_name" ]; then
return 0
fi
done
return 1
}
# 函数:记录日志
function log_message {
local message=$1
echo "$(date +'%Y-%m-%d %H:%M:%S') - $message" >> $LOG_FILE
}
while true; do
# 获取所有Pod的资源使用情况
pod_resources=$(kubectl top pods)
while IFS= read -r line; do
if [[ $line != "NAME CPU(cores) MEMORY(bytes)" ]]; then
# 解析Pod名称、CPU使用率和内存使用率
pod_name=$(echo $line | awk '{print $1}')
cpu_usage=$(echo $line | awk '{print $2}' | sed 's/%//')
mem_usage=$(echo $line | awk '{print $3}' | sed 's/%//')
# 检查CPU使用率
if (( $(echo "$cpu_usage >= 80" | bc -l) )); then
if is_pod_adjusted $pod_name; then
# 开始计时
start_time=$(date +%s)
while true; do
current_cpu_usage=$(kubectl top pods $pod_name | awk 'NR==2 {print $2}' | sed 's/%//')
if (( $(echo "$current_cpu_usage >= 80" | bc -l) )); then
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
if ((elapsed_time >= 300)); then
# 调整资源
kubectl patch pod $pod_name -p '{"spec": {"resources": {"requests": {"cpu": "200m", "memory": "512Mi"}, "limits": {"cpu": "400m", "memory": "1024Mi"}}}}'
log_message "Adjusted resources for Pod $pod_name due to high CPU usage"
ADJUSTED_PODS+=("$pod_name")
break
fi
else
break
fi
sleep 1
done
fi
fi
# 检查内存使用率
if (( $(echo "$mem_usage >= 90" | bc -l) )); then
if is_pod_adjusted $pod_name; then
# 开始计时
start_time=$(date +%s)
while true; do
current_mem_usage=$(kubectl top pods $pod_name | awk 'NR==2 {print $3}' | sed 's/%//')
if (( $(echo "$current_mem_usage >= 90" | bc -l) )); then
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
if ((elapsed_time >= 300)); then
# 调整资源
kubectl patch pod $pod_name -p '{"spec": {"resources": {"requests": {"cpu": "200m", "memory": "512Mi"}, "limits": {"cpu": "400m", "memory": "1024Mi"}}}}'
log_message "Adjusted resources for Pod $pod_name due to high memory usage"
ADJUSTED_PODS+=("$pod_name")
break
fi
else
break
fi
sleep 1
done
fi
fi
fi
done <<< "$pod_resources"
sleep 1
done
上述脚本实现了以下功能:
- 实时监控:通过
kubectl top pods
实时获取所有Pod的CPU和内存使用率。 - 资源调整:当某个Pod的CPU使用率连续5分钟超过80%或者内存使用率连续5分钟超过90%时,使用
kubectl patch
调整该Pod的CPU和内存配额。 - 避免重复调整:通过数组
ADJUSTED_PODS
记录已调整的Pod,避免重复调整。 - 日志记录:将所有操作记录到
pod_resource_monitor.log
文件中。
请根据实际需求调整资源调整的具体参数(如requests
和limits
)。同时,确保运行脚本的用户具有足够的Kubernetes权限来执行kubectl top pods
和kubectl patch
操作。