#!/usr/bin/env python3 """ ChocoMae 모니터링 데이터 분석 스크립트 Usage: python3 analyze_monitoring.py [data_dir] Example: python3 analyze_monitoring.py /home/ubuntu/chocomae-monitoring """ import os import sys import glob import pandas as pd import numpy as np from datetime import datetime, timedelta import json class MonitoringAnalyzer: def __init__(self, data_dir): self.data_dir = data_dir self.df = None self.load_data() def load_data(self): """모든 CSV 파일 로드 및 통합""" csv_files = sorted(glob.glob(os.path.join(self.data_dir, 'chocomae-*.log'))) if not csv_files: print(f"❌ Error: No monitoring data found in {self.data_dir}") sys.exit(1) dfs = [] for csv_file in csv_files: try: df = pd.read_csv(csv_file) df['timestamp'] = pd.to_datetime(df['timestamp']) dfs.append(df) print(f"✓ Loaded: {os.path.basename(csv_file)} ({len(df)} records)") except Exception as e: print(f"⚠ Warning: Failed to load {csv_file}: {e}") if dfs: self.df = pd.concat(dfs, ignore_index=True) self.df = self.df.sort_values('timestamp').reset_index(drop=True) print(f"\n✓ Total records: {len(self.df)}") print(f"✓ Date range: {self.df['timestamp'].min()} ~ {self.df['timestamp'].max()}") else: print("❌ No valid data to process") sys.exit(1) def extract_numeric(self, series): """시리즈에서 수치값 추출 (NA 처리)""" return pd.to_numeric(series, errors='coerce') # ======================================================================== # 1. 시스템 전체 분석 # ======================================================================== def system_summary(self): """시스템 전체 요약 통계""" print("\n" + "="*70) print("1. 시스템 전체 분석") print("="*70) metrics = { '시스템 CPU': 'system_cpu_usage_percent', '시스템 메모리': 'system_mem_usage_percent', '메모리 여유': 'system_mem_free_gb', 'Apache CPU': 'apache_cpu', 'Apache 메모리': 'apache_mem', 'PHP CPU': 'php_cpu', 'PHP 메모리': 'php_mem', 'MariaDB CPU': 'mariadb_cpu', 'MariaDB 메모리': 'mariadb_mem', '디스크 사용률': 'disk_root_usage_percent', '디스크 IO 읽기': 'disk_io_read_mb_s', '디스크 IO 쓰기': 'disk_io_write_mb_s', } for label, col in metrics.items(): if col in self.df.columns: data = self.extract_numeric(self.df[col]) print(f"\n{label}:") print(f" 평균: {data.mean():.2f}") print(f" 최대: {data.max():.2f}") print(f" 최소: {data.min():.2f}") print(f" 표준편차: {data.std():.2f}") # ======================================================================== # 2. 시간대별 분석 (피크 타임 파악) # ======================================================================== def hourly_analysis(self): """시간대별 분석""" print("\n" + "="*70) print("2. 시간대별 분석 (피크 타임 파악)") print("="*70) self.df['hour'] = self.df['timestamp'].dt.hour hourly_metrics = { '시스템 CPU (%)': 'system_cpu_usage_percent', '시스템 메모리 (%)': 'system_mem_usage_percent', 'Apache Busy Workers': 'apache_busy_workers', 'MariaDB 연결': 'mariadb_conn_current', 'Total Accesses': 'apache_total_accesses', } for label, col in hourly_metrics.items(): if col in self.df.columns: hourly = self.df.groupby('hour')[col].agg(['mean', 'max', 'min']) hourly.columns = ['평균', '최대', '최소'] print(f"\n{label}:") print(hourly.to_string()) # ======================================================================== # 3. 요일별 분석 # ======================================================================== def daily_analysis(self): """요일별 분석""" print("\n" + "="*70) print("3. 요일별 분석") print("="*70) self.df['date'] = self.df['timestamp'].dt.date daily_metrics = { '시스템 CPU (%)': 'system_cpu_usage_percent', '시스템 메모리 (%)': 'system_mem_usage_percent', 'Apache Busy Workers': 'apache_busy_workers', 'MariaDB 연결': 'mariadb_conn_current', 'Total Accesses': 'apache_total_accesses', } for label, col in daily_metrics.items(): if col in self.df.columns: daily = self.df.groupby('date')[col].agg(['mean', 'max', 'min']) daily.columns = ['평균', '최대', '최소'] print(f"\n{label}:") print(daily.to_string()) # ======================================================================== # 4. Apache 분석 # ======================================================================== def apache_analysis(self): """Apache 성능 분석""" print("\n" + "="*70) print("4. Apache 성능 분석") print("="*70) print("\n[Worker 상태]") print(f" Busy Workers - 평균: {self.extract_numeric(self.df['apache_busy_workers']).mean():.1f}, 최대: {self.extract_numeric(self.df['apache_busy_workers']).max():.0f}") print(f" Idle Workers - 평균: {self.extract_numeric(self.df['apache_idle_workers']).mean():.1f}, 최대: {self.extract_numeric(self.df['apache_idle_workers']).max():.0f}") print("\n[연결 상태]") print(f" Keep-Alive 연결 - 평균: {self.extract_numeric(self.df['apache_ka_connections']).mean():.1f}, 최대: {self.extract_numeric(self.df['apache_ka_connections']).max():.0f}") print("\n[처리량]") total_accesses = self.extract_numeric(self.df['apache_total_accesses']) accesses_delta = total_accesses.diff() print(f" 초당 요청 수 - 평균: {accesses_delta.mean():.1f}, 최대: {accesses_delta.max():.0f}") print(f" 누적 요청 수: {total_accesses.iloc[-1]:.0f}") print("\n[CPU/메모리 사용]") print(f" CPU - 평균: {self.extract_numeric(self.df['apache_cpu']).mean():.2f}%, 최대: {self.extract_numeric(self.df['apache_cpu']).max():.2f}%") print(f" 메모리 - 평균: {self.extract_numeric(self.df['apache_mem']).mean():.0f}MB, 최대: {self.extract_numeric(self.df['apache_mem']).max():.0f}MB") # ======================================================================== # 5. MariaDB 분석 # ======================================================================== def mariadb_analysis(self): """MariaDB 성능 분석""" print("\n" + "="*70) print("5. MariaDB 성능 분석") print("="*70) print("\n[연결 풀 상태]") print(f" 현재 연결 - 평균: {self.extract_numeric(self.df['mariadb_conn_current']).mean():.1f}, 최대: {self.extract_numeric(self.df['mariadb_conn_current']).max():.0f}") print(f" 최대 사용 연결 - 값: {self.extract_numeric(self.df['mariadb_conn_max']).max():.0f}") print("\n[스레드 상태]") print(f" 실행 중인 스레드 - 평균: {self.extract_numeric(self.df['mariadb_threads_running']).mean():.1f}, 최대: {self.extract_numeric(self.df['mariadb_threads_running']).max():.0f}") print("\n[Slow Queries]") slow_queries = self.extract_numeric(self.df['mariadb_slow_queries']) slow_delta = slow_queries.diff() print(f" 누적 Slow Queries: {slow_queries.iloc[-1]:.0f}") print(f" 기간 동안 추가된 Slow Queries: {slow_delta.sum():.0f}") print("\n[CPU/메모리 사용]") print(f" CPU - 평균: {self.extract_numeric(self.df['mariadb_cpu']).mean():.2f}%, 최대: {self.extract_numeric(self.df['mariadb_cpu']).max():.2f}%") print(f" 메모리 - 평균: {self.extract_numeric(self.df['mariadb_mem']).mean():.0f}MB, 최대: {self.extract_numeric(self.df['mariadb_mem']).max():.0f}MB") # ======================================================================== # 6. PHP 분석 # ======================================================================== def php_analysis(self): """PHP-FPM 성능 분석""" print("\n" + "="*70) print("6. PHP-FPM 성능 분석") print("="*70) print("\n[프로세스 상태]") print(f" 프로세스 개수 - 평균: {self.extract_numeric(self.df['php_conn_count']).mean():.1f}, 최대: {self.extract_numeric(self.df['php_conn_count']).max():.0f}") print("\n[CPU/메모리 사용]") print(f" CPU - 평균: {self.extract_numeric(self.df['php_cpu']).mean():.2f}%, 최대: {self.extract_numeric(self.df['php_cpu']).max():.2f}%") print(f" 메모리 - 평균: {self.extract_numeric(self.df['php_mem']).mean():.0f}MB, 최대: {self.extract_numeric(self.df['php_mem']).max():.0f}MB") # ======================================================================== # 7. 디스크 분석 # ======================================================================== def disk_analysis(self): """디스크 성능 분석""" print("\n" + "="*70) print("7. 디스크 분석") print("="*70) print("\n[디스크 용량]") print(f" 사용률 - 평균: {self.extract_numeric(self.df['disk_root_usage_percent']).mean():.1f}%, 최대: {self.extract_numeric(self.df['disk_root_usage_percent']).max():.1f}%") print(f" 여유 공간 - 최소: {self.extract_numeric(self.df['disk_root_free_gb']).min():.1f}GB, 평균: {self.extract_numeric(self.df['disk_root_free_gb']).mean():.1f}GB") print("\n[디스크 IO]") print(f" 읽기 - 평균: {self.extract_numeric(self.df['disk_io_read_mb_s']).mean():.2f}MB/s, 최대: {self.extract_numeric(self.df['disk_io_read_mb_s']).max():.2f}MB/s") print(f" 쓰기 - 평균: {self.extract_numeric(self.df['disk_io_write_mb_s']).mean():.2f}MB/s, 최대: {self.extract_numeric(self.df['disk_io_write_mb_s']).max():.2f}MB/s") # ======================================================================== # 8. Serverless 마이그레이션 권고사항 # ======================================================================== def serverless_recommendations(self): """Serverless 마이그레이션 권고사항""" print("\n" + "="*70) print("8. Serverless 마이그레이션 권고사항") print("="*70) # 피크 시간대 파악 self.df['hour'] = self.df['timestamp'].dt.hour peak_hour = self.df.groupby('hour')['system_cpu_usage_percent'].mean().idxmax() peak_cpu = self.df.groupby('hour')['system_cpu_usage_percent'].mean().max() # 동시 연결 수 분석 max_connections = self.extract_numeric(self.df['mariadb_conn_current']).max() avg_connections = self.extract_numeric(self.df['mariadb_conn_current']).mean() # 메모리 요구사항 total_mem_peak = ( self.extract_numeric(self.df['apache_mem']).max() + self.extract_numeric(self.df['php_mem']).max() + self.extract_numeric(self.df['mariadb_mem']).max() ) # 처리량 분석 accesses = self.extract_numeric(self.df['apache_total_accesses']) total_time_minutes = len(self.df) rps = accesses.diff().mean() if len(accesses) > 1 else 0 print(f"\n📊 주요 지표 요약:") print(f" • 피크 시간대: {peak_hour}:00 (CPU: {peak_cpu:.1f}%)") print(f" • 동시 연결 수: 평균 {avg_connections:.0f}, 최대 {max_connections:.0f}") print(f" • 피크 메모리 요구: 약 {total_mem_peak:.0f}MB") print(f" • 처리량: 약 {rps:.1f} 요청/초") print(f"\n💡 권고사항:") # 1. 동시 연결 분석 if max_connections > 100: print(f" 1. RDS Aurora / Serverless Aurora 사용 권고") print(f" - 현재 최대 {max_connections:.0f}개 동시 연결 처리 필요") print(f" - Connection Pooling (RDS Proxy) 권장") else: print(f" 1. ✓ 데이터베이스 연결 규모는 Serverless 적합") # 2. 처리량 분석 if rps > 10: print(f" 2. AWS Lambda 함수 메모리/타임아웃 최적화") print(f" - 초당 {rps:.1f}개 요청 처리 필요") print(f" - 동시 실행 한계 설정 권장") else: print(f" 2. ✓ 처리량 규모는 Lambda 기본 설정으로 충분") # 3. 메모리 분석 print(f" 3. Lambda 메모리 할당 제안: {min(3008, max(512, int(total_mem_peak * 1.5)))}MB") print(f" - 피크 메모리: {total_mem_peak:.0f}MB") # 4. API Gateway + ALB 검토 print(f" 4. API Gateway 스로틀링 설정") print(f" - 예상 피크 요청 속도: {rps * 5:.0f} 요청/초 (여유도 포함)") # 5. 데이터베이스 최적화 slow_queries = self.extract_numeric(self.df['mariadb_slow_queries']) if len(slow_queries) > 1: slow_delta = slow_queries.diff().sum() if slow_delta > 0: print(f" 5. ⚠️ Slow Query 최적화 필수") print(f" - 기간 동안 {slow_delta:.0f}개 Slow Query 발생") else: print(f" 5. ✓ Slow Query 이슈 없음") # 6. 아키텍처 제안 print(f"\n🏗️ 추천 아키텍처:") print(f" • API Gateway → Lambda (PHP/Node.js runtime)") print(f" • RDS Aurora Serverless (또는 RDS Proxy + MariaDB)") print(f" • CloudWatch Logs 및 X-Ray 통합") print(f" • S3 (정적 자산) + CloudFront (CDN)") print(f" • Auto Scaling: Lambda concurrency {min(1000, int(max_connections * 10))}") # ======================================================================== # 9. 이상 탐지 (Anomaly Detection) # ======================================================================== def anomaly_detection(self): """이상 탐지""" print("\n" + "="*70) print("9. 이상 탐지") print("="*70) # CPU 이상치 cpu_data = self.extract_numeric(self.df['system_cpu_usage_percent']) cpu_mean = cpu_data.mean() cpu_std = cpu_data.std() cpu_threshold = cpu_mean + 2 * cpu_std cpu_anomalies = self.df[self.extract_numeric(self.df['system_cpu_usage_percent']) > cpu_threshold] if len(cpu_anomalies) > 0: print(f"\n⚠️ CPU 이상치 감지:") print(f" • 기준값: {cpu_threshold:.1f}% (평균 + 2σ)") print(f" • 이상치 발생 횟수: {len(cpu_anomalies)}") print(f" • 최대값: {cpu_data.max():.1f}%") # 메모리 이상치 mem_data = self.extract_numeric(self.df['system_mem_usage_percent']) mem_anomalies = self.df[mem_data > 90] if len(mem_anomalies) > 0: print(f"\n⚠️ 메모리 부족 감지:") print(f" • 90% 이상 사용 횟수: {len(mem_anomalies)}") # 연결 누수 (MariaDB) conn_data = self.extract_numeric(self.df['mariadb_conn_current']) conn_increase = conn_data.diff() sustained_increase = len(conn_increase[conn_increase > 5]) if sustained_increase > 10: print(f"\n⚠️ 데이터베이스 연결 증가 추세 감지:") print(f" • 급격한 증가 횟수: {sustained_increase}") print(f" • 최대값: {conn_data.max():.0f}") # Slow Query 증가 slow_data = self.extract_numeric(self.df['mariadb_slow_queries']) if len(slow_data) > 1: slow_delta = slow_data.diff().sum() if slow_delta > 10: print(f"\n⚠️ Slow Query 발생 증가:") print(f" • 기간 동안 발생: {slow_delta:.0f}개") if len(cpu_anomalies) == 0 and len(mem_anomalies) == 0 and sustained_increase <= 10: print("\n✓ 이상 탐지 결과: 정상 범위 내") # ======================================================================== # 메인 분석 실행 # ======================================================================== def run_all(self): """전체 분석 실행""" self.system_summary() self.hourly_analysis() self.daily_analysis() self.apache_analysis() self.mariadb_analysis() self.php_analysis() self.disk_analysis() self.anomaly_detection() self.serverless_recommendations() print("\n" + "="*70) print("분석 완료") print("="*70 + "\n") def main(): if len(sys.argv) > 1: data_dir = sys.argv[1] else: data_dir = '/home/ubuntu/chocomae-monitoring' if not os.path.isdir(data_dir): print(f"❌ Error: Directory not found: {data_dir}") sys.exit(1) analyzer = MonitoringAnalyzer(data_dir) analyzer.run_all() if __name__ == '__main__': main()