Bash Shell 질을 해보자. Linux 서버 CPU, Memory 기록하기

0

linux_shell

목록 보기
3/3

Lilux 서버의 CPU, Memory 사용량 기록하기

linux서버에 kubernetes 클러스터를 올렸을 때, 특정 pod들이 가지고 있는 부하나, 부하 테스트를 하고싶다면 해당 서버의 CPU와 Memory를 테스트해볼 필요가 있다. 그러기 위해서 다음의 스크립트를 만들어 CPU와 Memory를 기록해보고자 한다.

먼저, CPU와 Memory를 가져와 보자.

memory_usage=$(free -m | awk 'NR==2{printf "%.2f",$3*100/$2 }')
cpu_usage=$(top -bn1 | grep load | awk '{printf "%.2f\n", $(NF-2)}')
mem=$(free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }')
cpu=$(top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}') 

top 명령어를 사용하면 CPU usage와 Memory usage를 가져올 수 있다. CPU 사용량을 얻기위해 top을 사용하였고, Memory는 더 쉽게 얻기위해서 free를 사용하였다.

이제 다음의 CPU, Memory usage를 파일에 기록해보자

OUTPUT_DIR_PATH="$(dirname $0)"
OUTPUT_FILE_NAME="cpu-mem.csv"
OUTPUT_FILE_PATH="$OUTPUT_DIR_PATH/$OUTPUT_FILE_NAME"

function write_output_file(){
    echo $1 >> $OUTPUT_FILE_PATH
}

recording_data_in_output $cpu_usage $memory_usage

OUTPUT_FILE_PATH에 함수 인자로 들어온 파라미터들을 기록하는 함수인 write_output_file을 만들었다. 인자들은 위에서 구한 CPU, Memory usage가 된다.

이제 일정 시간(interval) 동안 계속해서 CPU, Memory usage를 기록하도록 하자.

RECORDING_INTERVAL=3

function get_cpu_memory_usage(){
    while true;
    do
        memory_usage=$(free -m | awk 'NR==2{printf "%.2f",$3*100/$2 }')
        cpu_usage=$(top -bn1 | grep load | awk '{printf "%.2f\n", $(NF-2)}')
        mem=$(free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }')
        cpu=$(top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}') 
        LOG "$mem"
        LOG "$cpu"
        recording_data_in_output $cpu_usage $memory_usage
        sleep $RECORDING_INTERVAL;
    done;
}

기록한 다음 RECORDING_INTERVAL동안 sleep을 하도록 만들었다.

가장 기본적인 것은 되었고, 다음으로 옵션을 설정할 수 있도록 하자. 옵션으로는 -o를 받아 원하는 파일 위치에 정보를 기록하도록 하게하고, -i로 파일에 기록하는 interval을 설정하도록 하자.

function arg_command(){
    while getopts "o:i:h:" opt
    do
        case "$opt" in
            o ) OUTPUT_FILE_PATH="$OPTARG" ;;
            i ) RECORDING_INTERVAL="$OPTARG" ;;
            ? ) help_command ;; # Print helpFunction in case parameter is non-existent
        esac
    done
}

whilegetopts를 사용하면 쉽게 옵션을 얻어낼 수 있다. argument를 받아내는 arg_command에는 반드시 입력값이 필요하다. 그래서 다음과 같이 사용해야 한다.

arg_command "$@"

"#@"으로 입력으로 받아내는 옵션들을 얻을 수 있다.

이제 전체 프로그램을 만들어보자.

#!/bin/bash

PROGRAM_NAME="cpu-memory-recorder.sh"
OUTPUT_DIR_PATH="$(dirname $0)"
OUTPUT_FILE_NAME="cpu-mem.csv"
OUTPUT_FILE_PATH="$OUTPUT_DIR_PATH/$OUTPUT_FILE_NAME"
RECORDING_INTERVAL=3

function help_command(){
   echo ""
   echo "Usage: $0 -o ./cpu-mem.csv | -i 10"
   echo -e "\t-o Output file path.                   ex) -o ./cpu-mem.csv"
   echo -e "\t-i Recording interval time(second).    ex) -i 10"
   echo -e "Output Data format is csv please check below
------------------------------------------------
DATE           | CPU USAGE     | MEMORY USAGE  |
11:03:14:59:10 , 1.07          , 38.91         |
------------------------------------------------
"
   exit 1 # Exit script after printing help
}

function arg_command(){
    while getopts "o:i:h:" opt
    do
        case "$opt" in
            o ) OUTPUT_FILE_PATH="$OPTARG" ;;
            i ) RECORDING_INTERVAL="$OPTARG" ;;
            ? ) help_command ;; # Print helpFunction in case parameter is non-existent
        esac
    done
}

function LOG(){
    echo "[$PROGRAM_NAME]:$@" 
}

function show_config(){
    LOG "Output path       : $OUTPUT_FILE_PATH"
    LOG "Recording interval: $RECORDING_INTERVAL"
}

function remove_output_file(){
    if [ -f "$OUTPUT_FILE_PATH" ]; then
        LOG "Remove $OUTPUT_FILE_PATH"
        rm $OUTPUT_FILE_PATH
    fi
}

function write_output_file(){
    echo $1 >> $OUTPUT_FILE_PATH
}

function recording_data_in_output(){
    local today=$(date +%m:%d:%H:%M:%S)
    local result_line="$today,"
    if [  $# -eq 0 ]; then
        LOG "Error There is no cpu or memory usage"
        exit 1
    fi
    for var in "$@"
    do
        result_line+=$var
        result_line+=","
    done
    result_line="${result_line::-1}"
    write_output_file "$result_line"
}

function get_cpu_memory_usage(){
    while true;
    do
        memory_usage=$(free -m | awk 'NR==2{printf "%.2f",$3*100/$2 }')
        cpu_usage=$(top -bn1 | grep load | awk '{printf "%.2f\n", $(NF-2)}')
        mem=$(free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }')
        cpu=$(top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}') 
        LOG "$mem"
        LOG "$cpu"
        recording_data_in_output $cpu_usage $memory_usage
        sleep $RECORDING_INTERVAL;
    done;
}

function start_recording() {
    arg_command "$@"
    show_config
    remove_output_file
    get_cpu_memory_usage
}

start_recording "$@"

실행하면 다음과 같은 결과를 얻는다.

11:03:14:59:10

csv형태이고, date,CPU-usage,Memory-usage 순서이다.

0개의 댓글