Files

8.6 KiB

ChocoMae 모니터링 스크립트 업데이트 가이드

문제점 및 해결 방법

발견된 문제

  1. Apache CPU = 0 → 프로세스 감지 방식이 정확하지 않음
  2. PHP CPU = 0 → PHP-FPM이 설치되어 있지 않음 (정상)
  3. System CPU 불안정 → top 명령 파싱 오류

수정 사항

✅ Apache CPU - pgrep으로 정확한 프로세스 감지
✅ System CPU - top 명령 형식에 맞게 파싱 수정
✅ PHP-FPM - 없어도 안전하게 처리
✅ MONITOR_DIR - 경로를 파라미터로 설정 가능


업데이트 적용 (3단계)

Step 1: 현재 스크립트 중지

# 실행 중인 모니터링 프로세스 확인
ps aux | grep chocomae-24h-monitoring

# 프로세스 종료 (PID는 실제 번호로 교체)
kill <PID>
# 또는 강제 종료
killall -9 bash

# 확인
ps aux | grep chocomae-24h-monitoring

Step 2: 새 스크립트 배포

# 로컬에서 서버로 수정된 스크립트 복사
scp chocomae-24h-monitoring-fixed.sh ubuntu@<your-ec2>:/home/ubuntu/script/monitoring/

# 또는 서버에서 직접 편집
ssh ubuntu@<your-ec2>

# 기존 파일 백업
cp /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh \
   /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh.backup

# 새 파일 적용
cp /home/ubuntu/script/monitoring/chocomae-24h-monitoring-fixed.sh \
   /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh

# 실행 권한 설정
chmod +x /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh

Step 3: 스크립트 재시작

# 방법 1: 백그라운드 실행
/home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh /home/ubuntu/script/monitoring/chocomae-monitoring &

# 방법 2: nohup으로 실행 (로그아웃해도 유지)
nohup /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh /home/ubuntu/script/monitoring/chocomae-monitoring > /home/ubuntu/script/monitoring/monitor.log 2>&1 &

# 실행 확인
ps aux | grep chocomae-24h-monitoring

검증 (수정 확인)

1. 로그 파일 확인

cd /home/ubuntu/script/monitoring/chocomae-monitoring

# 최신 로그 확인
tail -5 chocomae-$(date +%Y%m%d).log

# 예상되는 정상 출력:
# 2026-09-21 22:40:30,2.5,185,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,7,4,6,2721500,15.2,24.3,2.85,1
#                     ^^^                                                           ^^^^
#              Apache CPU가 이제 0이 아님                              System CPU가 정상 값

2. 각 메트릭 확인

# Apache CPU 필드 (두 번째) 확인
tail -1 chocomae-$(date +%Y%m%d).log | cut -d',' -f2
# 예: 2.5 (0이 아닌 실제 값)

# System CPU 필드 (21번째) 확인
tail -1 chocomae-$(date +%Y%m%d).log | cut -d',' -f21
# 예: 15.2 (불안정한 값 아님)

# MariaDB 필드들 확인
tail -1 chocomae-$(date +%Y%m%d).log | cut -d',' -f9-12
# 예: 0.8,308,27,18

3. 실시간 모니터링

# 1초마다 최신 값 보기
watch -n 1 'tail -1 /home/ubuntu/script/monitoring/chocomae-monitoring/chocomae-$(date +%Y%m%d).log | tr "," "\n" | nl'

# 또는 간단히
tail -f chocomae-$(date +%Y%m%d).log

개선 사항 요약

이전 (문제)

2026-09-21 22:30:24,0,177,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,7,4,6,2719305,100,24.3,2.84,1
                     ^Apache CPU=0      ^PHP CPU=0                                    ^^System CPU=100 (불안정)

이후 (수정)

2026-09-21 22:40:30,2.5,185,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,7,4,6,2721500,15.2,24.3,2.85,1
                     ^^^Apache CPU=2.5% (정상)                                     ^^^^System CPU=15.2% (정상)

주요 개선 사항 상세 설명

1. Apache CPU 수집 개선

이전:

local apache_cpu=$(ps aux | grep -E "[a]pache|[h]ttpd" | awk '{sum+=$3} END {print (NR>1 ? sum/(NR-1) : 0)}')

개선:

local apache_cpu=0
if command -v pgrep &> /dev/null; then
    apache_cpu=$(pgrep -f "apache2|httpd" | xargs ps -o %cpu= 2>/dev/null | awk '{sum+=$1} END {printf "%.2f", sum}')
fi
apache_cpu=${apache_cpu:-0}

차이점:

  • pgrep -f "apache2|httpd" - 정확한 프로세스명으로 검색
  • /usr/sbin/apache2 정확하게 감지
  • 에러 처리 추가 (command not found 방지)

2. System CPU 파싱 개선

이전:

local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print 100-$8}')

개선:

local cpu_usage=$(top -bn1 2>/dev/null | grep "Cpu(s)" | awk -F'id' '{print $1}' | awk '{print $NF}' | tr -d ',')
cpu_usage=${cpu_usage:-0}

# CPU idle 값에서 사용률 계산하는 대체 방법
if (( $(echo "$cpu_usage == 0" | bc -l) )); then
    cpu_usage=$(top -bn1 2>/dev/null | grep "Cpu(s)" | awk -F',' '{print $4}' | awk '{print 100-$1}')
    cpu_usage=${cpu_usage:-0}
fi

차이점:

  • Ubuntu 24.04의 top 형식 대응: %Cpu(s): 0.0 us, 4.8 sy, 0.0 ni, 95.2 id, ...
  • 다양한 형식에 대응하는 대체 방법 추가
  • 에러 처리 강화

3. Apache/MariaDB 메모리 수집 개선

이전:

local apache_mem=$(ps aux | grep -E "[a]pache|[h]ttpd" | awk '{sum+=$6} END {printf "%.0f", (sum>0 ? sum/1024 : 0)}')

개선:

local apache_mem=$(ps aux | grep -E "(/usr/sbin/apache2|/usr/sbin/httpd)" | grep -v grep | awk '{sum+=$6} END {printf "%.0f", (sum>0 ? sum/1024 : 0)}')

차이점:

  • 전체 경로 명시로 정확도 향상
  • grep -v grep 추가로 grep 명령 자신이 포함되는 것 방지

4. MONITOR_DIR 파라미터화

이전:

MONITOR_DIR="/home/ubuntu/chocomae-monitoring"  # 고정값

개선:

MONITOR_DIR="${1:-/home/ubuntu/script/monitoring/chocomae-monitoring}"  # 첫 번째 인자 또는 기본값

사용 방법:

# 기본 경로 사용
./chocomae-24h-monitoring.sh

# 커스텀 경로 사용
./chocomae-24h-monitoring.sh /custom/path/to/monitoring

Systemd 서비스로 자동 관리 (선택사항)

# 서비스 파일 생성
sudo tee /etc/systemd/system/chocomae-monitoring.service > /dev/null <<EOF
[Unit]
Description=ChocoMae 24/7 Monitoring
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/script/monitoring
ExecStart=/home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh /home/ubuntu/script/monitoring/chocomae-monitoring
Restart=always
RestartSec=10
StandardOutput=append:/home/ubuntu/script/monitoring/monitor.log
StandardError=append:/home/ubuntu/script/monitoring/monitor.log

[Install]
WantedBy=multi-user.target
EOF

# 서비스 등록 및 시작
sudo systemctl daemon-reload
sudo systemctl enable chocomae-monitoring.service
sudo systemctl start chocomae-monitoring.service

# 상태 확인
sudo systemctl status chocomae-monitoring.service

# 로그 확인
journalctl -u chocomae-monitoring.service -f

롤백 방법 (문제 발생 시)

# 이전 버전으로 복구
cp /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh.backup \
   /home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh

# 스크립트 재시작
killall bash
/home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh /home/ubuntu/script/monitoring/chocomae-monitoring &

예상 결과

업데이트 후 로그 샘플:

timestamp,apache_cpu,apache_mem,...,system_cpu_usage_percent,...
2026-09-21 22:40:00,2.5,185,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,7,4,6,2721500,15.2,24.3,2.85,1
2026-09-21 22:41:00,3.2,190,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,8,3,5,2721520,18.5,24.3,2.85,1
2026-09-21 22:42:00,2.1,188,1,0,0,0,0.8,308,27,18,1,86,1.3,0.00,0.00,7,4,6,2721540,12.3,24.2,2.85,1

✅ Apache CPU: 2.5%, 3.2%, 2.1% (정상값)
✅ System CPU: 15.2%, 18.5%, 12.3% (안정적)
✅ MariaDB: 모든 필드 정상 수집


문제 발생 시 디버깅

# 각 메트릭 개별 테스트
/home/ubuntu/script/monitoring/chocomae-24h-monitoring.sh &

# Apache 프로세스 확인
pgrep -f "apache2|httpd"

# System CPU 값 확인
top -bn1 | grep "Cpu(s)"

# MariaDB 연결 확인
sudo mariadb -e "SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected','Max_used_connections','Threads_running','Slow_queries')"

# 실시간 로그 확인
tail -f /home/ubuntu/script/monitoring/chocomae-monitoring/chocomae-$(date +%Y%m%d).log

완료 확인 체크리스트

  • 기존 모니터링 프로세스 종료
  • 새 스크립트 배포
  • 스크립트 재시작
  • 로그 파일에서 Apache CPU 값이 0이 아님 확인
  • System CPU 값이 안정적임 확인
  • MariaDB 모든 필드가 수집됨 확인

완료되면 Python 분석 스크립트로 자동 분석 계속 가능합니다!