ImageUs-메모리 모니터링

codakcodak·2023년 3월 3일
0

ImageUs

목록 보기
13/17

문제상황

  • ImageUs서비스와 같이 사진을 다루거나 큰 파일을 다루는 서버들은 메모리 관리가 매우 중요하다.aws의 ec2나 개인의 데스크탑에서 서버를 운영할 때 보통은 우분투를 쓰는데 기존의 top,free,vmstat 등의 명령어를 통해 메모리를 모니터링 할 수 있지만 특정 시간 구간의 메모리 사용 변화를 관찰하거나 기록을 하는데는 한계가 있다.

해결방법

  • python의 psutil패키지를 이용하여 메모리의 사용량 변화를 기록하고 구간을 모니터링 하는 파일을 만든다.
  • argparse패키지를 이용하여 사용자에게 여러 인자 옵션을 제공한다.

적용과정

  • memory_monitor.py
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import os
from datetime import datetime
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='settings for monitoring memory')

    parser.add_argument('--load', '-l', i', type=int, default=100, help='ms for monitoring interval')
    parser.add_argument('--time', '-t', type=int, default=300, help='sec for monitoring time')

    input_args = parser.parse_args()
type=str, help='load for npy file,if load was given it will show you just loaded plot')
    parser.add_argument('--interval', '-
    print(input_args)

    np_file_dir=os.path.dirname(os.path.realpath(__file__))+'/memory_history'

    if hasattr(input_args,'load') and input_args.load != None:
        file_path=np_file_dir+'/'+input_args.load
        print(file_path)
        if os.path.exists(file_path):
            temp=np.load(file_path)
            plt.plot(temp,'r',label="real-time Memory usage")
            plt.show() 
    else:
        if not os.path.exists(np_file_dir):
            os.mkdir(np_file_dir)
        save_file_path=''
        y=[]
        
        def animate_memory(i):
            global y
            global save_file_path
            
            if len(y)==0:
                now = datetime.now()
                date_time = now.strftime("%Y_%m_%d_%H_%M_%S")
                save_file_path=np_file_dir+'/'+date_time+'.npy'
                print(save_file_path)
                
                
            if len(y)>=(input_args.time*round(1000/input_args.interval)):
                np.save(save_file_path,y)
                y=[]
                
                return
            
            memory_use_percent=psutil.virtual_memory().percent
            
            y.append(memory_use_percent)


            plt.cla()
            plt.plot(y,'r',label="real-time Memory usage")
                    
            plt.tight_layout()
        
        ani=FuncAnimation(plt.gcf(),animate_memory,interval=input_args.interval)
        plt.show() 
  • 사용자에게 기존의 파일을 로드하여 기록을 보여주는 load,모니터링 하려는 구간의 시간time,모니터링 하려는 시간 간격 interval옵션 설정

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='settings for monitoring memory')

    parser.add_argument('--load', '-l', i', type=int, default=100, help='ms for monitoring interval')
    parser.add_argument('--time', '-t', type=int, default=300, help='sec for monitoring time')

    input_args = parser.parse_args()
type=str, help='load for npy file,if load was given it will show you just loaded plot')
    parser.add_argument('--interval', '-
    print(input_args)

*load를 옵션으로 준다면 기존의 파일을 그래프로 보려는 것이기 때문에 모니터링 기능은 안하도록 구현

  • 사용자가 load옵션을 줬을 때 실제 존새하는 파일인지 먼저 확인하고 그래프 표현
 if hasattr(input_args,'load') and input_args.load != None:
        file_path=np_file_dir+'/'+input_args.load
        print(file_path)
        if os.path.exists(file_path):
            temp=np.load(file_path)
            plt.plot(temp,'r',label="real-time Memory usage")
            plt.show() 
  • load옵션을 주지 않았을 경우 먼저 npy파일들을 저장하는 dir를 생성
 else:
        if not os.path.exists(np_file_dir):
            os.mkdir(np_file_dir)
        save_file_path=''
        y=[]
  • 보여줄 데이터가 없을 경우 현재의 시간을 미리 찍고 사용자가 설정한 모니터링 시간 끝에 파일을 저장하고 다시 초기화 하도록 구현
        def animate_memory(i):
            global y
            global save_file_path
            
            if len(y)==0:
                now = datetime.now()
                date_time = now.strftime("%Y_%m_%d_%H_%M_%S")
                save_file_path=np_file_dir+'/'+date_time+'.npy'
                print(save_file_path)
                
                
            if len(y)>=(input_args.time*round(1000/input_args.interval)):
                np.save(save_file_path,y)
                y=[]
                
                return
            
            memory_use_percent=psutil.virtual_memory().percent
            
            y.append(memory_use_percent)


            plt.cla()
            plt.plot(y,'r',label="real-time Memory usage")
                    
            plt.tight_layout()
  • 사용자가 설정한 interval간격으로 애니메이션을 생성
        ani=FuncAnimation(plt.gcf(),animate_memory,interval=input_args.interval)
        plt.show() 

결과

  • 인자 옵션 설정

*모니터링 시간은 60초,모니터링 간격은 0.1초

  • 모니터링

  • 사용자가 처음에 설정한 모니터링 시간(60초)간격으로 파일 저장

*년분_초.npy형식으로 저장

  • 이미 기록된 데이터를 그래프 표현

profile
숲을 보는 코더

0개의 댓글