Skip to content

hotfix: DB EC2 MySQL 초기화 OOM 방지#59

Merged
Hexeong merged 1 commit into
mainfrom
hotfix/db-ec2-allocation-swap-memory
Jul 10, 2026
Merged

hotfix: DB EC2 MySQL 초기화 OOM 방지#59
Hexeong merged 1 commit into
mainfrom
hotfix/db-ec2-allocation-swap-memory

Conversation

@Hexeong

@Hexeong Hexeong commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

관련 이슈

작업 내용

  • DB EC2 bootstrap 과정에서 MySQL 컨테이너 실행 전에 /swapfile 2GiB를 생성하고 활성화하도록 수정했습니다.
  • 이미 swap이 활성화되어 있거나 /swapfile이 존재하는 경우 중복 생성하지 않도록 처리했습니다.
  • 재부팅 후에도 swap이 유지되도록 /etc/fstab에 등록합니다.

특이 사항

  • prod DB EC2에서 mysql:8.4.8 초기화 중 mysqld가 OOM으로 종료되며 컨테이너가 정상 기동하지 못하는 문제가 확인되어 반영한 hotfix입니다.
  • swap은 root volume 내부 파일로 생성되며, 별도 EBS 리소스를 추가하지 않습니다.
  • 현재 마이그레이션 전 깨진 DB EC2/data volume은 수동 삭제 및 Terraform state 정리가 완료되어, apply 시 새 DB EC2와 새 data volume이 생성되는 plan을 확인했습니다.

리뷰 요구사항 (선택)

  • t4g.nano 환경에서 MySQL 8.4.8 초기화 안정성을 위해 2GiB swap을 두는 방향이 적절한지 확인 부탁드립니다.
  • 검증: bash -n modules/app_stack/scripts/mysql_setup.sh.tftpl, git diff --check, prod terraform plan 확인 완료 (Plan: 3 to add, 0 to change, 0 to destroy).

Summary by CodeRabbit

  • 개선 사항
    • Docker 시작 전에 스왑 파일을 자동으로 확인하고 활성화하도록 개선했습니다.
    • 스왑 파일이 없으면 자동으로 생성하고, 시스템 재부팅 후에도 유지되도록 설정합니다.
    • 스왑 관련 명령을 사전 점검하여 초기화 과정의 안정성을 높였습니다.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

MySQL 설정 스크립트가 Docker 시작 전에 /swapfile을 준비합니다. 스왑 관련 명령을 확인하고 파일을 생성·포맷·활성화하며 /etc/fstab에 지속 설정을 추가합니다.

Changes

스왑 초기화

Layer / File(s) Summary
스왑 설정 및 시작 흐름
modules/app_stack/scripts/mysql_setup.sh.tftpl
스왑 명령 사전 점검과 /swapfile 생성, 포맷, 활성화 및 /etc/fstab 등록을 추가하고, Docker 서비스 활성화 직후 ensure_swap을 호출합니다.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 제목이 MySQL 초기화 OOM 방지라는 핵심 변경을 간결하게 요약합니다.
Description check ✅ Passed 필수 섹션을 모두 포함하며 작업 내용·특이 사항·리뷰 요구사항도 잘 정리되어 있습니다. 관련 이슈 번호만 채우면 더 좋습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hotfix/db-ec2-allocation-swap-memory

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

Terraform Plan: stage

No changes. Your infrastructure matches the configuration.

전체 plan 결과는 보안을 위해 댓글에 포함되지 않습니다. 워크플로우 실행 아티팩트를 확인하세요.

@github-actions

Copy link
Copy Markdown

Terraform Plan: prod

Plan: 3 to add, 0 to change, 0 to destroy.

전체 plan 결과는 보안을 위해 댓글에 포함되지 않습니다. 워크플로우 실행 아티팩트를 확인하세요.

@lsy1307 lsy1307 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

meow

@Hexeong Hexeong merged commit 6db3dc2 into main Jul 10, 2026
7 checks passed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
modules/app_stack/scripts/mysql_setup.sh.tftpl (1)

21-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

command -v 검사가 결과를 사용하지 않습니다.

swapon/mkswap 존재 여부를 확인하지만 실패 시 아무 동작도 하지 않아 사실상 dead code입니다. 명령이 없는 경우 이후 단계에서 더 불분명한 에러가 발생합니다. 제거하거나 실패 시 exit/경고 처리를 추가하는 것을 고려해 보세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modules/app_stack/scripts/mysql_setup.sh.tftpl` around lines 21 - 22, Remove
the unused command -v checks for swapon and mkswap, or make them enforce
prerequisites by emitting a clear error and terminating before swap setup
proceeds when either command is unavailable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modules/app_stack/scripts/mysql_setup.sh.tftpl`:
- Around line 40-41: In the fstab guard, the regex in the swap-entry check
incorrectly consumes the first character of the swap path, so duplicate entries
are appended. Update the grep pattern used by the fstab registration block to
match optional leading whitespace followed by the full $swap_file path, while
still excluding commented lines and matching the existing none/swap fields.

---

Nitpick comments:
In `@modules/app_stack/scripts/mysql_setup.sh.tftpl`:
- Around line 21-22: Remove the unused command -v checks for swapon and mkswap,
or make them enforce prerequisites by emitting a clear error and terminating
before swap setup proceeds when either command is unavailable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9a8c249b-caba-4258-a916-878c0a80d87a

📥 Commits

Reviewing files that changed from the base of the PR and between 8bba772 and 68dd771.

📒 Files selected for processing (1)
  • modules/app_stack/scripts/mysql_setup.sh.tftpl

Comment on lines +40 to +41
if ! grep -Eq "^[^#][[:space:]]*$swap_file[[:space:]]+none[[:space:]]+swap[[:space:]]" /etc/fstab; then
printf '%s none swap sw 0 0\n' "$swap_file" >> /etc/fstab

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

fstab 중복 등록 버그 — regex가 의도한 대로 매칭되지 않습니다.

[^#]/swapfile의 첫 글자 /를 소비한 뒤, 패턴의 리터럴 /swapfile는 잔여 텍스트 swapfile ...와 매칭을 시도하므로 항상 실패합니다. 결과적으로 swap이 이미 활성화된 상태에서도(라인 27 가드 바깥에 있음) 매 실행 시마다 /etc/fstab에 중복 엔트리가 추가됩니다.

🐛 Proposed fix
-  if ! grep -Eq "^[^#][[:space:]]*$swap_file[[:space:]]+none[[:space:]]+swap[[:space:]]" /etc/fstab; then
+  if ! grep -Eq "^[[:space:]]*${swap_file}[[:space:]]+none[[:space:]]+swap" /etc/fstab; then
     printf '%s none swap sw 0 0\n' "$swap_file" >> /etc/fstab
   fi

/swapfile/로 시작하므로 # 주석 라인과 자연히 구분되며, ^[[:space:]]*로 선행 공백도 허용합니다.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ! grep -Eq "^[^#][[:space:]]*$swap_file[[:space:]]+none[[:space:]]+swap[[:space:]]" /etc/fstab; then
printf '%s none swap sw 0 0\n' "$swap_file" >> /etc/fstab
if ! grep -Eq "^[[:space:]]*${swap_file}[[:space:]]+none[[:space:]]+swap" /etc/fstab; then
printf '%s none swap sw 0 0\n' "$swap_file" >> /etc/fstab
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modules/app_stack/scripts/mysql_setup.sh.tftpl` around lines 40 - 41, In the
fstab guard, the regex in the swap-entry check incorrectly consumes the first
character of the swap path, so duplicate entries are appended. Update the grep
pattern used by the fstab registration block to match optional leading
whitespace followed by the full $swap_file path, while still excluding commented
lines and matching the existing none/swap fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants