0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Linuxサーバーの使用メモリ量が全体の80%に達した時に特定のコマンドを実行する

Posted at

はじめに

cronでLinuxサーバーの使用メモリ量が全体の80%に達した時に特定のコマンドを実行するための動作確認とcron設定を行った際のメモです。

参考記事

コマンド

コマンド例
[[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && command

動作確認

動作確認
[root@linux userA]# free
              total        used        free      shared  buff/cache   available
Mem:        8166304     2272464     5094276         452      799564     5645496
Swap:             0           0           0
[root@linux userA]#
[root@linux userA]# [[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && echo $?
[root@linux userA]# [[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.2 ]] && echo $?
0
[root@linux userA]#

全体のメモリ量が 8166304。
現在の使用量が 2272464。
ですので現在の使用量割合は0.27で27%。

確認その1
[root@linux userA]# [[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && echo $?

このコマンドを実行した結果、次の行に何も表示されないのは"echo $?"が実行されていないからです。
これは判定が

判定その1
0.27 > 0.8

のようになり判定結果がfalseになったからです。
次に、

確認その2
[root@linux userA]# [[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.2 ]] && echo $?
0

このコマンドを実行した結果、次の行に"0"が表示されたのは"echo $?"が実行されたからです。
これは判定が

判定その2
0.27 > 0.2

のようになり判定結果がtrueになったからです。

$?にはコマンドの実行結果(0や1)が入る。
echo $?の表示結果が0なのに、何故echo $?が実行されたの???
0 && echo $? となりecho $?は実行されないはずでは???

と思われた方は先頭で記載している参考記事をご確認ください。

応用

最終的に私がやりたかったことでもあります。

使用量が80%を超えたらrebootを実行してサーバーを再起動したり、

[[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && reboot

そのサーバーで稼働している主要サービスが1個だけなら、

[[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && systemctl restart xxx.service

などでもよいと思います。

そしてcronでは

cron
* */1 * * * [[ $(free | head -2 | tail -n 1 | awk '{print $3/$2}') > 0.8 ]] && reboot

とします。

参考コマンド

今回は全体のメモリ量から使用量がどうなったかで判断していますが、freeコマンドは使用可能量/空き容量も取得できますので、使用可能量/空き容量がいくらまで減ったかで判断することも可能だと思います。
さらに使用量の算出方法の以下のようなやり方がありますので、参考までに記載しておきます。

実行中のプロセス全部をカウントして使用量を求める

ps aux | awk '{sum += $6}END{print sum}'

特定のプロセスだけに限定して求める

top -b -c -n 1 | grep PROCESSNAME | grep -v grep | awk '{print $10}' | cut -d. -f1

最後に

管理するLinuxサーバーの台数が多い場合はZabbixとか監視サービスなどを利用するのも手かと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?