Java – CPU, Memory, Disk, Network などの情報採取 on Ubuntu No.79

自己投資としてチャレンジしている内容を Blog で公開しています。

今回はマシン (Ubuntu) の CPU, Memory, Network, Disk 空き状況などのログを取得する Java コードを紹介したいと思います。DB への接続失敗などで原因の切り分けのためサーバの負荷を確認する際などに、役に立つと思います。(In English Java – Capture CPU, Memory, Disk, Network information on Ubuntu No.79)

▼1. Ubuntu の CPU, Memory, Network, ディスクの状況などを知る

Linux で実行可能な以下のコマンドを Java で実行し、Ubuntu の CPU, Memory, Network, ディスクの空き状況などを確認します。

  • top -b -n 1 : top コマンドでプロセスごとの cpu, memory など確認
  • free -m : メモリの利用状況を確認
  • df -lh : ディスクの使用状況を確認
  • lsof -i:ポート番号 : ポートを使っているプロセスを確認
  • netstat -anp : 使用中の接続ポートとそのプロセスを確認

▼2. 事前準備

2-1. JDK のインストール

zulu の Java 8 openjdk x64 をインストールします。

mkdir  -p /usr/lib/jvm/
cd /usr/lib/jvm/
sudo wget https://cdn.azul.com/zulu/bin/zulu8.66.0.15-ca-jdk8.0.352-linux_x64.tar.gz
sudo tar -xzvf zulu8.66.0.15-ca-jdk8.0.352-linux_x64.tar.gz
sudo mv zulu8.66.0.15-ca-jdk8.0.352-linux_x64 java-8-openjdk-linux_x64

環境変数を設定します。

Vi などのエディター (vi ~/.bashrc) で ~/.bashrc の末尾に以下を記載します。

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-x64/

JAVA_HOME の環境変数がが正しく設定されたか確認します。

echo $JAVA_HOME

2-2. Visual Studio Code のインストール

https://code.visualstudio.com/docs/setup/linux

sudo snap install --classic code

2-3. Maven のインストール

Apache Kafka Word Count 実装 – Java No.442-3. Apache Maven のインストール” を参照


▼3. Ubuntu の CPU, Memory, Network, ディスクの状況を取得後ファイルに保存する Java コード

3-1. Apache Maven によるプロジェクトを作成します。

mvn archetype:generate -DinteractiveMode=false -DgroupId=org.example.perflog -DartifactId=perfcheck -DarchetypeArtifactId=maven-archetype-quickstart

3-2. デフォルトで作成された App.java および AppTest.java を削除します。

rm ./perfcheck/src/main/java/org/example/sqlsrv/App.java
rm ./perfcheck/src/test/java/org/example/sqlsrv/AppTest.java

3-3. Visual Studio Code を起動します。

cd ./perfcheck
$code .

3-4. pom.xml に以下を追記し保存 (Ctrl+S) します。

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

3-5. perfch.java を作成します。

package org.example.perflog;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class perfch {
    public static void main(String[] args) {
        String filename = "/home/ubuntu20/temp/perf.log";
        try {
            java.io.PrintWriter output = new java.io.PrintWriter(filename);

            System.out.println("Start to write to file: " + filename);
            System.out.println("top -b -n 1");
            output.println("top -b -n 1");
            try {
                Process p = Runtime.getRuntime().exec("top -b -n 1");
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                int i = 0;
                while ((line = br.readLine()) != null && i < 15) {
                    output.println(line);
                    i++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.println("========================================");
            output.println("========================================");
            output.println("========================================");
            output.println("free -m");
            System.out.println("free -m");
            try {
                Process p = Runtime.getRuntime().exec("free -m");
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    output.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.println("========================================");
            output.println("========================================");
            output.println("========================================");
            output.println("df -lh");
            System.out.println("df -lh");

            try {
                Process p = Runtime.getRuntime().exec("df -lh");
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    output.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.println("========================================");
            output.println("========================================");
            output.println("========================================");
            output.println("lsof -i:443");
            System.out.println("lsof -i:443");
            try {
                Process p = Runtime.getRuntime().exec("lsof -i:443");
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    output.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.println("========================================");
            output.println("========================================");
            output.println("========================================");
            output.println("netstat -anp");
            System.out.println("netstat -anp");
            try {
                Process p = Runtime.getRuntime().exec("netstat -anp");
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    output.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }
} 

3-6. 実行後 perf.log ファイルが生成されます。

perf.log の中身の抜粋は以下となります。

top -b -n 1
top - 11:33:32 up  2:13,  1 user,  load average: 0.51, 0.78, 0.69
Tasks: 197 total,   1 running, 196 sleeping,   0 stopped,   0 zombie
%Cpu(s): 68.4 us, 10.5 sy,  0.0 ni, 21.1 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :  10160.3 total,   5578.3 free,   2318.8 used,   2263.1 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   7443.1 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
   7703 ubuntu20  20   0   32.4g 174228 119844 S  27.8   1.7   3:17.55 code
   7676 ubuntu20  20   0   54.6g 342444 176388 S  16.7   3.3   6:03.32 code
   1144 ubuntu20  20   0 3792564 406712 140360 S  11.1   3.9   4:03.32 gnome-s+
    925 root      20   0  315588 127276  67560 S   5.6   1.2   2:17.87 Xorg
   7610 ubuntu20  20   0   36.9g 177148 129584 S   5.6   1.7   0:32.31 code
  35733 ubuntu20  20   0 4635584  34792  25396 S   5.6   0.3   0:00.07 java
      1 root      20   0  167556  11536   8372 S   0.0   0.1   0:00.95 systemd
      2 root      20   0       0      0      0 S   0.0   0.0   0:00.00 kthreadd
========================================
========================================
========================================
free -m
              total        used        free      shared  buff/cache   available
Mem:          10160        2318        5578         126        2263        7443
Swap:          2047           0        2047
========================================
========================================
========================================
df -lh
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           393M  1.5M  392M   1% /run
/dev/sda5        49G   23G   24G  48% /
tmpfs           2.0G   97M  1.9G   5% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
xxx
========================================
========================================
========================================
lsof -i:443
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
code    7717 ubuntu20   89u  IPv4 170306      0t0  TCP ubuntu20.mshome.net:36414->20.112.192.30:https (ESTABLISHED)
java    7817 ubuntu20  182u  IPv6 190646      0t0  TCP ubuntu20.mshome.net:44710->xxx.com:https (ESTABLISHED)
========================================
========================================
========================================
netstat -anp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -         
xxx
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name     Path
unix  2      [ ACC ]     STREAM     LISTENING     25818    -                    /run/containerd/containerd.sock.ttrpc
unix  2      [ ACC ]     STREAM     LISTENING     25820    -                    /run/containerd/containerd.sock
xxx

▼4. 参考情報

VS Code のインストール https://code.visualstudio.com/docs/setup/linux

以上です。参考になりましたら幸いです。



コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です