Skip to content

[FIX#348] Makefile run-issuetracker — chrome 실제 포트 dynamic discovery - #349

Merged
juhy0987 merged 3 commits into
mainfrom
fix/#348/chrome-dynamic-port-discovery
May 11, 2026
Merged

juhy0987 merged 3 commits into
mainfrom
fix/#348/chrome-dynamic-port-discovery

Conversation

@juhy0987

@juhy0987 juhy0987 commented May 11, 2026

Copy link
Copy Markdown
Member

연관 이슈

Closes #348

배경

compose chrome 서비스의 `ports: "${FETCHER_CHROMEDP_HOST_PORT_RANGE:-9222-9229}:9222"` 가 Docker engine 의 internal counter drift 로 9222/9223 이 아닌 9226/9227 등에 할당. 그러나 앱의 `FETCHER_CHROMEDP_REMOTE_URLS` 는 정적 → 라이브 boot 시 chrome 연결 불가.

라이브 매번 `FETCHER_CHROMEDP_REMOTE_URLS=ws://localhost:9226,9227 ./bin/issuetracker` 식 env override 필요했음.

구현 — option C (dynamic env discovery)

이슈 #348 의 4가지 옵션 (A 단일 포트 고정 / B Docker counter reset / C 동적 env 생성 / D 호스트 매핑 제거) 중 호스트 binary 실행 모드를 유지하면서 가장 깨끗한 option C.

chrome-remote-urls target 신설

```make
chrome-remote-urls:
@$(CHROME_COMPOSE) ps --status running --format '{{.Ports}}' chrome 2>/dev/null \
| grep -oE '0\.0\.0\.0:[0-9]+->9222/tcp' \
| grep -oE '^0\.0\.0\.0:[0-9]+' \
| grep -oE '[0-9]+$$' \
| sort -n \
| head -n $(CHROME_WORKER_COUNT) \
| sed 's|^|ws://localhost:|' \
| paste -sd,
```

  • compose ps 출력에서 `HOST_PORT->9222/tcp` 패턴 파싱
  • `CHROME_WORKER_COUNT` 만큼만 선택 (정렬 후 head)
  • `ws://localhost:9226,ws://localhost:9227` 형식 콤마 구분 URL 출력
  • inspection / 재사용 가능한 단일 책임 target

run-issuetracker 통합

  • build 후 chrome-remote-urls 결과를 export 한 채 entrypoint 실행
  • URLs 가 빈 문자열 (chrome 컨테이너 부재) 이면 .env 의 정적 값으로 fallback — 기존 동작 보존
  • 발견된 URL 을 로그에 표시 — 운영자가 매핑 가시화

검증

chrome 이 9226/9227 에 할당된 상태에서:
```bash
$ make run-issuetracker
...
Discovered chrome remote URLs: ws://localhost:9226,ws://localhost:9227
Running issuetracker (crawler + processor)...
{"level":"info",...,"message":"starting IssueTracker"}
{"level":"info","source":"inven",...,"message":"crawler registered from db"}
... (모든 crawler 등록 + scheduler tick 정상)
```

CI / 머지 게이트 점검

  • Makefile 단독 변경 — go build/test 영향 없음
  • 라이브 환경에서 chrome-remote-urls + run-issuetracker 정상 동작 확인

변경 영향 범위 + 위험도

  • 영향: make run-issuetracker 가 자동으로 실제 chrome 포트 매핑 — 매번 env override 불필요
  • 위험도: 낮음
    • chrome 컨테이너 부재 시 .env fallback — 기존 동작 보존
    • 파싱은 IPv4 (0.0.0.0:) 만 인식 — IPv6 only 환경에서는 fallback 필요
    • paste -sd, 가 콤마 구분 single line 보장
    • WORKER_COUNT > 실제 running 개수면 found 만큼만 export

롤백 계획

  1. git revert — Makefile 단일 파일 변경
  2. 운영자 매번 env override 패턴으로 환원

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Improved application startup process with automatic service discovery. The system now intelligently detects and configures available services during initialization, completely eliminating the need for manual setup steps. If required services are unavailable, the application gracefully falls back to existing environment configuration, ensuring flexibility and improved reliability across different deployment environments.

Review Change Stack

…348)

문제:
- compose chrome 서비스의 host_port_range (9222-9229) 가 Docker engine 의 internal
  counter drift 로 9226/9227 등에 할당됨
- 그러나 deployments/docker/.env 의 FETCHER_CHROMEDP_REMOTE_URLS=ws://localhost:9222,9223
  는 정적 → 앱이 chrome 에 연결 불가
- 라이브 기동 시마다 매번 env override 필요

수정:
1. chrome-remote-urls target 신설 — compose ps 출력 파싱으로 host 포트 추출 후 ws:// URL
   목록 (콤마 구분) stdout 출력. 단일 책임으로 분리하여 inspection / 재사용 가능.
2. run-issuetracker 가 build 후 chrome-remote-urls 결과를 export 한 채 entrypoint 실행.
   chrome 컨테이너가 없으면 (URLs 빈 문자열) .env 의 FETCHER_CHROMEDP_REMOTE_URLS 로 fallback —
   기존 동작 보존.

검증:
- chrome 이 9226/9227 에 할당된 상태에서 make run-issuetracker 실행 시
  'Discovered chrome remote URLs: ws://localhost:9226,ws://localhost:9227' 출력 후
  앱이 정상 boot — 모든 crawler 등록 + scheduler tick 정상.

scope 외: docker engine port counter 자체는 그대로 — 컨테이너가 9226/9227 에 떠도 앱이 정합.
Copilot AI review requested due to automatic review settings May 11, 2026 11:39
@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@juhy0987 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 29 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: da157ccb-92af-41e5-8574-c82d6a42a3c2

📥 Commits

Reviewing files that changed from the base of the PR and between d56d12b and 632a1f3.

📒 Files selected for processing (1)
  • Makefile
📝 Walkthrough

Walkthrough

The Makefile is enhanced to dynamically discover Chrome container websocket ports from active Docker Compose containers and automatically wire them into the application via environment variables, eliminating the manual port-range drift problem that occurs when containers are repeatedly started and stopped.

Changes

Chrome Discovery and Dynamic Wiring

Layer / File(s) Summary
Phony Target Declaration
Makefile
Extended .PHONY list to include chrome-ensure and kafka-ensure targets.
Chrome URL Discovery Tool
Makefile
New chrome-remote-urls target extracts actual host ports from docker compose ps for Chrome containers (port mapping 9222), selects up to CHROME_WORKER_COUNT entries, formats as ws://localhost:<port> list, and outputs comma-separated results.
Dynamic Environment Wiring
Makefile
run-issuetracker target now calls chrome-remote-urls to retrieve actual endpoints; if available, passes FETCHER_CHROMEDP_REMOTE_URLS to scripts/entrypoint.sh; if none found, logs .env fallback and runs without override.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related issues

Possibly related PRs

Suggested labels

bug

Poem

🐰 A rabbit hops through port ranges wide,
Where Chrome containers roam and hide—
Dynamic discovery, no more static drift,
Websockets find their destined shift!
Nine-two-two-two, now you'll always find,
The ports that Docker left behind. 🔗

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main change: dynamic port discovery for Chrome in the Makefile's run-issuetracker target, directly addressing the port mapping issue in #348.
Linked Issues check ✅ Passed The changes implement the core requirement from #348: dynamically discovering Chrome's actual host ports and syncing them with FETCHER_CHROMEDP_REMOTE_URLS, with proper fallback to .env values when Chrome is unavailable.
Out of Scope Changes check ✅ Passed All changes are scoped to the Makefile and directly address #348's requirement for dynamic port discovery; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/#348/chrome-dynamic-port-discovery

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 and usage tips.

@juhy0987 juhy0987 added the bug Something isn't working label May 11, 2026

Copilot AI 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.

Pull request overview

이 PR은 docker compose의 Chrome 서비스가 포트 range에서 실제로 할당받은 host port(예: 9226/9227)를 동적으로 발견해서, make run-issuetracker 실행 시 FETCHER_CHROMEDP_REMOTE_URLS를 자동으로 맞춰 주기 위한 수정입니다(이슈 #348 대응). 호스트에서 바이너리를 직접 실행하는 운영 모드를 유지하면서 Chrome 포트 drift로 인한 부팅 실패를 줄이는 데 목적이 있습니다.

Changes:

  • chrome-remote-urls Make target 추가: 실행 중인 chrome compose 컨테이너의 HOST_PORT->9222/tcp 매핑을 파싱해 ws://localhost:<port>,... 형태로 출력
  • run-issuetracker에 동적 discovery를 통합: 발견된 URL이 있으면 FETCHER_CHROMEDP_REMOTE_URLS를 override한 채로 엔트리포인트 실행
  • .PHONY에 신규 target 등록

Comment thread Makefile Outdated
Comment thread Makefile Outdated

@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

🤖 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 `@Makefile`:
- Around line 120-123: The current grep pipeline that parses "$(CHROME_COMPOSE)
ps --format '{{.Ports}}' $(CHROME_COMPOSE_SERVICE)" assumes IPv4
"0.0.0.0:<port>->9222/tcp" and misses IPv6/addressed bindings; replace the
three-stage grep chain with a single address-agnostic extraction that first
matches any ":[0-9]+->9222/tcp" (allowing leading "0.0.0.0", ":::", or "[addr]")
and then captures the port number, keeping the use of CHROME_COMPOSE and
CHROME_COMPOSE_SERVICE; update the Makefile pipeline so it extracts the digits
before "->9222/tcp" regardless of IP format (e.g., match ":[0-9]+->9222/tcp"
then output the numeric port).
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 61075098-6de8-4d61-bbea-433d2e4a5e90

📥 Commits

Reviewing files that changed from the base of the PR and between 8ba2481 and d56d12b.

📒 Files selected for processing (1)
  • Makefile

Comment thread Makefile Outdated

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request updates the Makefile to dynamically discover Chrome remote debugging URLs for the issuetracker service. It introduces a new chrome-remote-urls target that extracts host ports from running Docker containers and sets the FETCHER_CHROMEDP_REMOTE_URLS environment variable. Feedback was provided to improve the robustness of the port discovery logic by supporting various network interfaces, such as IPv6 and localhost, and ensuring precise container matching using anchors.

Comment thread Makefile Outdated
juhy0987 added 2 commits May 11, 2026 20:47
Copilot 2건 반영:

1. URL 개수 vs WORKER_COUNT 정합 (Copilot #1):
   - pkg/config.LoadFetcherChromedpPool 가 RemoteURLs 개수 != WorkerCount 시 fail-fast
   - 기존: REMOTE_URLS 만 override → WORKER_COUNT 와 mismatch 시 app boot fail
   - 변경: 발견된 URL 개수 (NF count) 와 WORKER_COUNT 비교 후 분기
     * 일치: REMOTE_URLS 만 override (정상 mode)
     * 불일치: WARNING 로그 + REMOTE_URLS + WORKER_COUNT 둘 다 override (degraded mode)
     * URL 0개: .env fallback (기존 동작 보존)

2. compose 실패와 0 found 구분 (Copilot #2):
   - 기존: 2>/dev/null 로 stderr 버림 → docker daemon down / compose 오류도 'no found' 로 처리
   - 변경: chrome-remote-urls 가 compose ps 의 exit code 보존
     * 0 + 비어있는 output: 정상 (no chrome) — caller 가 fallback
     * 0 + URL 출력: 정상 — caller 가 export
     * non-zero: stderr 보존 + 동일 exit code 로 종료 → run-issuetracker 가 ERROR 로그 + 즉시 exit

추가:
- exec ./scripts/entrypoint.sh 로 shell PID inheritance — signal 전달 깔끔
- 발견된 URL 개수 (found) 를 메시지에 명시 — 운영 가시성

검증:
- chrome-remote-urls 단독 호출: 'ws://localhost:9226,ws://localhost:9227', rc=0
- run-issuetracker: 'Discovered chrome remote URLs (2): ws://localhost:9226,ws://localhost:9227'
  → 정상 boot, 모든 crawler 등록 + scheduler tick 진행 확인
CodeRabbit Major + gemini Medium (동일 의도) 반영:
- 기존: 'grep 0\.0\.0\.0:[0-9]+->9222/tcp' — IPv4 전용
  → IPv6 (::) / 127.0.0.1 등 다른 bind address 미인식
- 변경: 'sed -nE s/.*:([0-9]+)->9222\/tcp/\1/p' 단일 추출 +
  'tr , \n' 으로 ports 컬럼 항목 분리 + 'sort -un' 으로 unique + 정렬

compose ps 출력의 'docker-chrome-1: 9223/tcp, 0.0.0.0:9226->9222/tcp, [::]:9226->9222/tcp'
같은 IPv4+IPv6 dual listing 도 sort -u 로 dedup. 검증: 동일 결과 (9226,9227).
@juhy0987 juhy0987 self-assigned this May 11, 2026
@juhy0987
juhy0987 merged commit 515e536 into main May 11, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FIX] docker compose chrome host_port_range counter drift — 9222/9223 미사용 + 앱 env 매핑 불일치

2 participants