Java – Capture CPU,Memory,Network info on Ubuntu No.79

In this blog, how to capture CPU, Memory, Disk, Network information by Java is shown.it would be helpful if you need narrow down the issue about connection failure to Database to find a root cause.

▼1. How to know CPU, Memory, Network status on Ubuntu

We can know CPU, Memory, Network, Disk usage on Ubuntu to run the following commands.

  • top -b -n 1 : show CPU, Memory etc each processes.
  • free -m : show Memory usage
  • df -lh : Show Disk usage
  • lsof -i:port number : show process with using port
  • netstat -anp : show processes and used port of them

▼2. Prerequisite

2-1. Install JDK

Install Java 8 openjdk x64 of zulu

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

Set environment variables

Run vi command (vi ~/.bashrc) and update ~/.bashrc file as below.

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

Check $JAVA_HOME

echo $JAVA_HOME

2-2. Install Visual Studio Code

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

sudo snap install --classic code

2-3. Install Maven

Apache Kafka Word Count – Java No.44 “2-3. Installing Apache Maven”


▼3. Deploy Java application to capture CPU, Memory, Network, Disk status on ubuntu and save a file locally.

3-1. Create an Apache Maven project

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

3-2. Remove the default created App.java and AppTest.java files

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

3-3. Start Visual Studio Code

cd ./perfcheck
$code .

3-4. Add below into pom.xml file

  <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. Develop 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. Check the output file “perf.log”

perf.log shows like below.

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. Reference

That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *