求助:HDFS用户空间利用率邮件自动化中GB排序异常问题
解决HDFS人类可读格式排序问题
你遇到的问题很典型——当用-h参数让hdfs dfs -du输出人类可读的大小(比如GB、MB)时,直接用sort -r是按字符串字典序排序,而不是按实际存储大小排序,所以会出现100M排在5G前面的情况(因为"1"的ASCII码比"5"小)。而字节单位的输出是纯数字,sort -nr能正确按数值排序。
下面给你两种可行的解决方案:
方案1:使用GNU Sort的-h参数(推荐)
GNU的sort工具支持-h参数,专门用来对人类可读的大小格式进行数值排序。直接修改你的Diskuse变量定义即可:
# 替换原来的Diskuse行,使用sort -hr来正确排序人类可读格式的大小 Diskuse=$(hdfs dfs -du -h /user | sort -hr | head -10)
注意:这个参数需要GNU sort(大部分Linux发行版默认都是),如果是BSD系统的sort可能不支持,这时可以用方案2。
方案2:先按字节排序,再转成人类可读格式
如果你的环境不支持sort -h,可以先获取字节数排序,再通过hdfs dfs -du -h或者自己转换格式来输出:
# 先按字节排序取前10,再逐个转成人类可读格式 Diskuse=$(hdfs dfs -du /user | sort -nr | head -10 | while read size path; do hdfs dfs -du -h "$path" | awk '{print $1, $3}' done)
这个方法先拿到纯字节数的排序结果,再对每个路径单独调用-h参数获取可读格式,确保排序是准确的。
额外的脚本小修复
另外注意你脚本里的一个小错误:hdfs dfs -df -h/这里-h和/之间少了空格,应该改成:
CURRENT=$(hdfs dfs -df -h / | grep / | awk '{ print $8}' | sed 's/%//g')
修改后的完整脚本
#!/bin/bash #getting the current hdfs percentage in numeric value CURRENT=$(hdfs dfs -df -h / | grep / | awk '{ print $8}' | sed 's/%//g') #current hdfs space utilisation DiskFile=$(hdfs dfs -df -h) HdfsReport=$(hdfs dfsadmin -report) # 使用方案1的排序方式,正确按人类可读大小排序前10 Diskuse=$(hdfs dfs -du -h /user | sort -hr | head -10) THRESHOLD=70 Critical=90 if [ "$CURRENT" -gt "$THRESHOLD" ] ; then mail -s 'HDFS Usage Housekeeping required' @abc.com, @abc.com << EOF HDFS usage in Cluster is above the threshold please run the clean-up scripts asap. Used: $CURRENT% Current disk utilization report is: $DiskFile Please find the top ten users consuming the most cluster storage: $Diskuse EOF fi if [ "$CURRENT" -gt "$Critical" ] ; then mail -s 'HDFS Admin Report' yy@abc.com, yyy@abc.com << EOF HDFS usage in Cluster is above critical storage, please Find the Cluster report below: $HdfsReport EOF fi
我还调整了邮件内容的格式,让输出更易读,比如添加了换行和标题。
内容的提问来源于stack exchange,提问作者Jibinjks
相关产品推荐
相关产品推荐

