diff --git a/perf/scenarios/fanmeeting-apply.js b/perf/scenarios/fanmeeting-apply.js index d4e29b3..f54afeb 100644 --- a/perf/scenarios/fanmeeting-apply.js +++ b/perf/scenarios/fanmeeting-apply.js @@ -6,6 +6,9 @@ // A 오픈 뒤 몰림. MODE=open, 기본 START_OFFSET=2s. 시작 시각 >= 오픈. 전원 201이어야 한다(거절 0). // B 오픈 직전부터. MODE=open, 기본 START_OFFSET=-2s. 시작 시각 < 오픈. 오픈 전 거절(WINDOW_CLOSED)이 정상이다. // C 마감 앞뒤. MODE=close, 기본 START_OFFSET=-3s. 마감 뒤 거절이 정상이고, 마감 1초 뒤부터 보낸 요청의 201은 0이어야 한다. +// G 게릴라 오픈. MODE=open, 기본 START_OFFSET=-60s. 오픈 시각을 모르는 회원들이 상세를 새로고침하다가(POLL_MIN~POLL_MAX +// 간격) OPEN이 보이는 순간 한 번 응모한다. 회원마다 VU 하나. 판정은 A와 같고(전원 201, 거절 0), +// 상세 조회 오류 0, OPEN을 끝내 못 본 회원 0을 더 본다. 행사는 OPENS_AT_PUBLIC=false로 만든다. // SCENARIO를 비우면 MODE와 시작 시각으로 정한다: close면 C, open이면 시작 시각이 오픈 전이면 B, 아니면 A. // 기준 시각은 MODE=open이면 오픈(entryOpensAt), close면 마감(entryClosesAt)이다. import http from 'k6/http'; @@ -19,7 +22,7 @@ const BASE_URL = (__ENV.BASE_URL || 'http://localhost:8080').replace(/\/$/, ''); const MANAGEMENT_URL = (__ENV.MANAGEMENT_URL || 'http://localhost:8081').replace(/\/$/, ''); const SUMMARY_PATH = __ENV.SUMMARY_PATH || ''; const SCENARIO_ENV = (__ENV.SCENARIO || '').toUpperCase(); -if (SCENARIO_ENV && !['A', 'B', 'C'].includes(SCENARIO_ENV)) throw new Error(`SCENARIO must be A, B or C: ${__ENV.SCENARIO}`); +if (SCENARIO_ENV && !['A', 'B', 'C', 'G'].includes(SCENARIO_ENV)) throw new Error(`SCENARIO must be A, B, C or G: ${__ENV.SCENARIO}`); const MODE = __ENV.MODE || (SCENARIO_ENV === 'C' ? 'close' : 'open'); if (MODE !== 'open' && MODE !== 'close') throw new Error(`MODE must be open or close: ${MODE}`); if (SCENARIO_ENV && (SCENARIO_ENV === 'C') !== (MODE === 'close')) { @@ -60,7 +63,7 @@ function parseDuration(text) { // 기준 시각: MODE=open이면 오픈, close면 마감. 결과 구간(before, 0~1초, 1~2초, 2초 이후)도 이 시각에서 잰다. const REF_MS = MODE === 'open' ? OPENS_MS : CLOSES_MS; -const DEFAULT_OFFSET = { A: '2s', B: '-2s', C: '-3s' }[SCENARIO_ENV || (MODE === 'close' ? 'C' : 'A')]; +const DEFAULT_OFFSET = { A: '2s', B: '-2s', C: '-3s', G: '-60s' }[SCENARIO_ENV || (MODE === 'close' ? 'C' : 'A')]; const START_OFFSET = __ENV.START_OFFSET || DEFAULT_OFFSET; const START_MS = __ENV.START_AT ? Date.parse(__ENV.START_AT) : REF_MS + parseDuration(START_OFFSET); if (Number.isNaN(START_MS)) throw new Error(`bad START_AT: ${__ENV.START_AT}`); @@ -71,6 +74,14 @@ if (SCENARIO === 'A' && START_MS < OPENS_MS) { if (SCENARIO === 'B' && START_MS >= OPENS_MS) { throw new Error(`SCENARIO B must start before entryOpensAt (start ${new Date(START_MS).toISOString()}, opens ${OPENS_AT}). Use SCENARIO=A after the open.`); } +if (SCENARIO === 'G' && START_MS >= OPENS_MS) { + throw new Error(`SCENARIO G must start refreshing before entryOpensAt (start ${new Date(START_MS).toISOString()}, opens ${OPENS_AT}).`); +} +// G: 새로고침 간격(사람마다 무작위)과, 오픈 뒤 OPEN이 보일 때까지 기다리는 최대 시간. +const POLL_MIN_MS = parseDuration(__ENV.POLL_MIN || '1s'); +const POLL_MAX_MS = parseDuration(__ENV.POLL_MAX || '3s'); +const OPEN_WAIT_MS = parseDuration(__ENV.OPEN_WAIT || '120s'); +if (!(POLL_MIN_MS > 0 && POLL_MAX_MS >= POLL_MIN_MS)) throw new Error(`need 0 < POLL_MIN <= POLL_MAX: ${__ENV.POLL_MIN}, ${__ENV.POLL_MAX}`); const WAIT_MS = START_MS - Date.now(); if (WAIT_MS > 30 * 60 * 1000) throw new Error(`START_AT is ${Math.round(WAIT_MS / 60000)} minutes away. Start k6 closer to it.`); @@ -109,26 +120,37 @@ const closeThresholds = MODE === 'close' : {}; // A: 열린 뒤에만 보내므로 거절이 나오면 안 된다. 모두 거절돼도 요청 수·DB 수·기대 미응모 수는 서로 맞아서 // 다른 검사로는 잡히지 않는다. 전원 201과 WINDOW_CLOSED 0을 같이 요구한다. B·C의 정상 거절에는 걸지 않는다. -const appliedThreshold = SCENARIO === 'A' ? `count==${PARTICIPANTS}` : `count<=${PARTICIPANTS}`; -const scenarioThresholds = SCENARIO === 'A' ? { fm_window_closed: ['count==0'] } : {}; +// G도 OPEN을 본 뒤에만 보내므로 A와 같이 전원 201이어야 하고, 새로고침 중 상세 조회 오류와 OPEN을 못 본 회원도 0이어야 한다. +const ALL_MUST_APPLY = SCENARIO === 'A' || SCENARIO === 'G'; +const appliedThreshold = ALL_MUST_APPLY ? `count==${PARTICIPANTS}` : `count<=${PARTICIPANTS}`; +const scenarioThresholds = { + ...(ALL_MUST_APPLY ? { fm_window_closed: ['count==0'] } : {}), + ...(SCENARIO === 'G' ? { + fm_detail_server_error: ['count==0'], fm_detail_transport_error: ['count==0'], fm_detail_other_error: ['count==0'], + fm_never_saw_open: ['count==0'], + 'fm_detail_duration': [], 'fm_open_seen_after_ms': [], + } : {}), +}; + +// 부하 모델. A·B·C: ramping-arrival-rate. G: 회원마다 VU 하나가 한 번(새로고침을 반복하다 응모하고 끝). +const SCENARIO_DEF = SCENARIO === 'G' + ? { + executor: 'per-vu-iterations', vus: PARTICIPANTS, iterations: 1, + maxDuration: `${Math.ceil((OPENS_MS - START_MS + OPEN_WAIT_MS) / 1000) + 60}s`, + } + : { + executor: 'ramping-arrival-rate', startRate: 0, timeUnit: '1s', preAllocatedVUs: PRE_VUS, maxVUs: MAX_VUS, + stages: [ + { target: PEAK_RATE, duration: RAMP }, + { target: PEAK_RATE, duration: HOLD }, + { target: 0, duration: '5s' }, + ], + }; export const options = { // setup이 시작 시각까지 기다리므로 그만큼 늘린다. setupTimeout: `${Math.max(60, Math.ceil(WAIT_MS / 1000) + 60)}s`, - scenarios: { - fanmeeting_apply: { - executor: 'ramping-arrival-rate', - startRate: 0, - timeUnit: '1s', - preAllocatedVUs: PRE_VUS, - maxVUs: MAX_VUS, - stages: [ - { target: PEAK_RATE, duration: RAMP }, - { target: PEAK_RATE, duration: HOLD }, - { target: 0, duration: '5s' }, - ], - }, - }, + scenarios: { fanmeeting_apply: SCENARIO_DEF }, // 업무 거절(409)은 http_req_failed에 넣지 않는다. 503 BUSY, 401, 5xx, 연결 오류는 실패다. // 지연 목표 수치는 미측정이라 임계값을 두지 않는다. 아래는 정합성, 전제 조건, 오류·미완료 검사다. // BUSY·5xx·연결 오류·dropped가 하나라도 있으면 실패로 끝난다. 한계를 찾는 회차에서는 이 실패가 측정 결과다. @@ -152,7 +174,7 @@ export const options = { summaryTrendStats: ['min', 'med', 'avg', 'p(90)', 'p(95)', 'p(99)', 'max'], }; -http.setResponseCallback(http.expectedStatuses(201, 409)); +http.setResponseCallback(http.expectedStatuses(200, 201, 409)); // 실제로 보낸 응모 요청 수. 참여자 수와 같아야 모든 계정이 한 번씩 요청한 것이다. const requests = new Counter('fm_requests'); @@ -172,10 +194,18 @@ const appliedBy = Object.fromEntries(BUCKETS.map((b) => [b, new Counter(`fm_appl const closedBy = Object.fromEntries(BUCKETS.map((b) => [b, new Counter(`fm_window_closed_${b}`)])); // k6가 잰 지연. 집 네트워크 왕복이 섞인 체감값이다. 서버 지연은 관리 포트의 http.server.requests로 본다. const duration = new Trend('fm_apply_duration', true); +// G: 새로고침(상세 조회) 결과와, 오픈 시각부터 OPEN을 처음 본 때까지의 시간(Open Worker 지연 + 새로고침 간격). +const detailRequests = new Counter('fm_detail_requests'); +const detailServerError = new Counter('fm_detail_server_error'); +const detailTransportError = new Counter('fm_detail_transport_error'); +const detailOtherError = new Counter('fm_detail_other_error'); +const neverSawOpen = new Counter('fm_never_saw_open'); +const detailDuration = new Trend('fm_detail_duration', true); +const openSeenAfter = new Trend('fm_open_seen_after_ms', true); // 임계값을 건 카운터에 0을 하나씩 남긴다. 표본이 없는 지표도 임계값이 평가되게 한다. const THRESHOLD_COUNTERS = [requests, applied, windowClosed, alreadyApplied, busy, notFound, unauthorized, otherClientError, - serverError, transportError]; + serverError, transportError, detailRequests, detailServerError, detailTransportError, detailOtherError, neverSawOpen]; export function setup() { for (const c of THRESHOLD_COUNTERS) c.add(0); @@ -186,7 +216,7 @@ export function setup() { const detail = http.get(`${BASE_URL}/api/fan-meetings/${EVENT_ID}`, { tags: { name: 'setup' } }); if (detail.status !== 200) fail(`GET /api/fan-meetings/${EVENT_ID} returned ${detail.status}`); const status = detail.json('status'); - const okStatus = MODE === 'open' ? ['SCHEDULED', 'OPEN'] : ['OPEN']; + const okStatus = SCENARIO === 'G' ? ['SCHEDULED'] : MODE === 'open' ? ['SCHEDULED', 'OPEN'] : ['OPEN']; if (!okStatus.includes(status)) fail(`event ${EVENT_ID} status is ${status}, need ${okStatus}. Run fanmeeting-prepare.sh again.`); if (MODE === 'open' && Date.now() >= CLOSES_MS) fail(`entry window already closed at ${CLOSES_AT}`); @@ -194,31 +224,84 @@ export function setup() { const serverDate = Date.parse(detail.headers.Date || ''); const clockOffsetMs = Number.isNaN(serverDate) ? null : serverDate - Date.now(); + // G: 게릴라 행사는 열리기 전 상세에 오픈 시각을 주지 않는다. 주면 예고 오픈 행사라 회원이 시각을 알 수 있다. + let guerrilla = null; + if (SCENARIO === 'G') { + let opensShown = null; + try { opensShown = detail.json('entryOpensAt'); } catch (e) { /* 필드가 없으면 숨김으로 본다 */ } + guerrilla = opensShown == null; + if (!guerrilla) console.warn(`event ${EVENT_ID} shows entryOpensAt before the open: not a guerrilla event (OPENS_AT_PUBLIC=false)`); + } + const waitMs = START_MS - Date.now(); console.log(`event=${EVENT_ID} scenario=${SCENARIO} mode=${MODE} opens=${OPENS_AT} closes=${CLOSES_AT} participants=${PARTICIPANTS} ` + `offset=${USER_OFFSET} peak=${PEAK_RATE}/s start=${new Date(START_MS).toISOString()} wait=${Math.max(0, waitMs)}ms ` + `serverClockOffset~${clockOffsetMs}ms`); if (waitMs > 0) sleep(waitMs / 1000); - return { clockOffsetMs }; + return { clockOffsetMs, guerrilla }; } export default function () { + if (SCENARIO === 'G') { + guerrillaMember(); + return; + } const n = exec.scenario.iterationInTest; if (n >= users.length) { skipped.add(1); return; } - const user = users[n]; + const outcome = apply(users[n]); + check(outcome, { 'no server error': (o) => !['server_error', 'transport_error', 'busy'].includes(o) }); +} + +function apply(user) { requests.add(1); const sentAt = Date.now(); const res = http.post(`${BASE_URL}/api/fan-meetings/${EVENT_ID}/applications`, null, { headers: { Authorization: `Bearer ${user.token}` }, tags: { name: 'POST /api/fan-meetings/{eventId}/applications' }, }); - const bucket = bucketOf(sentAt - REF_MS); - const outcome = classify(res, bucket); + const outcome = classify(res, bucketOf(sentAt - REF_MS)); duration.add(res.timings.duration, { outcome }); - check(res, { 'no server error': () => !['server_error', 'transport_error', 'busy'].includes(outcome) }); + return outcome; +} + +const pollPause = () => (POLL_MIN_MS + Math.random() * (POLL_MAX_MS - POLL_MIN_MS)) / 1000; + +// G: 회원 한 명. 상세를 새로고침하다가 OPEN이 보이면 한 번 응모하고 끝낸다. 새로고침 오류는 세고 다시 시도한다. +function guerrillaMember() { + const user = users[exec.vu.idInTest - 1]; + sleep(Math.random() * POLL_MAX_MS / 1000); // 회원마다 새로고침 시점을 흩는다 + const giveUpAt = OPENS_MS + OPEN_WAIT_MS; + for (;;) { + const res = http.get(`${BASE_URL}/api/fan-meetings/${EVENT_ID}`, { + headers: { Authorization: `Bearer ${user.token}` }, + tags: { name: 'GET /api/fan-meetings/{eventId}' }, + }); + detailRequests.add(1); + detailDuration.add(res.timings.duration); + let status = ''; + if (res.status === 200) { + try { status = res.json('status'); } catch (e) { detailOtherError.add(1); } + } else if (res.status === 0) detailTransportError.add(1); + else if (res.status >= 500) detailServerError.add(1); + else detailOtherError.add(1); + if (status === 'OPEN') { + openSeenAfter.add(Date.now() - OPENS_MS); + apply(user); // OPEN을 본 즉시 보낸다 + return; + } + if (status && status !== 'SCHEDULED') { // 열리지 않고 다른 상태가 되면(취소 등) 더 기다려도 소용없다 + neverSawOpen.add(1); + return; + } + if (Date.now() >= giveUpAt) { + neverSawOpen.add(1); + return; + } + sleep(pollPause()); + } } function bucketOf(elapsedMs) { @@ -286,7 +369,15 @@ export function handleSummary(data) { ` applied ${latency(trendOf('fm_apply_duration{outcome:applied}'))}`, ` load generator http_req_connecting p95 ${fmt(trendOf('http_req_connecting')['p(95)'])} max ${fmt(trendOf('http_req_connecting').max)}` + `, http_req_blocked p95 ${fmt(trendOf('http_req_blocked')['p(95)'])} max ${fmt(trendOf('http_req_blocked').max)}`, - ` scenario ${SCENARIO}: ${SCENARIO === 'A' ? `every request must be 201 (applied ${value('fm_applied')}/${PARTICIPANTS}, window_closed ${value('fm_window_closed')})` + ...(SCENARIO === 'G' ? [ + ` guerrilla: refresh every ${__ENV.POLL_MIN || '1s'}~${__ENV.POLL_MAX || '3s'} from ${START_OFFSET} before the open, ` + + `opensAt hidden before the open: ${data.setup_data ? data.setup_data.guerrilla : '-'}`, + ` detail requests ${value('fm_detail_requests')} errors 5xx ${value('fm_detail_server_error')} ` + + `transport ${value('fm_detail_transport_error')} other ${value('fm_detail_other_error')} never saw OPEN ${value('fm_never_saw_open')}`, + ` detail latency ${latency(trendOf('fm_detail_duration'))}`, + ` OPEN first seen after the open (laptop clock) ${latency(trendOf('fm_open_seen_after_ms'))}`, + ] : []), + ` scenario ${SCENARIO}: ${ALL_MUST_APPLY ? `every request must be 201 (applied ${value('fm_applied')}/${PARTICIPANTS}, window_closed ${value('fm_window_closed')})` : SCENARIO === 'B' ? 'rejections before the open are expected' : 'rejections after the close are expected; 201 sent 1s+ after the close must be 0'}`, ` thresholds ${failedThresholds.length ? `FAILED: ${failedThresholds.join(', ')}` : 'ok'}`, ' next: perf/scenarios/fanmeeting-check.sh (invariants must be 0, applications must match fm_applied)', @@ -298,9 +389,17 @@ export function handleSummary(data) { conditions: { eventId: EVENT_ID, scenario: SCENARIO, mode: MODE, entryOpensAt: OPENS_AT, entryClosesAt: CLOSES_AT, startAt: new Date(START_MS).toISOString(), startOffset: __ENV.START_AT ? null : START_OFFSET, participants: PARTICIPANTS, userOffset: USER_OFFSET, peakRate: PEAK_RATE, ramp: RAMP, hold: HOLD, - preVUs: PRE_VUS, maxVUs: MAX_VUS, baseUrl: BASE_URL, serverClockOffsetMs: clockOffsetMs }, + preVUs: PRE_VUS, maxVUs: MAX_VUS, baseUrl: BASE_URL, serverClockOffsetMs: clockOffsetMs, + ...(SCENARIO === 'G' ? { pollMin: __ENV.POLL_MIN || '1s', pollMax: __ENV.POLL_MAX || '3s', openWait: __ENV.OPEN_WAIT || '120s', + guerrilla: data.setup_data ? data.setup_data.guerrilla : null } : {}) }, outcomes: Object.fromEntries(OUTCOME_METRICS.map((m) => [m, value(m)])), requestsTotal: value('fm_requests'), + ...(SCENARIO === 'G' ? { guerrilla: { + detailRequests: value('fm_detail_requests'), detailServerError: value('fm_detail_server_error'), + detailTransportError: value('fm_detail_transport_error'), detailOtherError: value('fm_detail_other_error'), + neverSawOpen: value('fm_never_saw_open'), detailLatency: trendOf('fm_detail_duration'), + openSeenAfterMs: trendOf('fm_open_seen_after_ms'), + } } : {}), outcomesTotal: requested, byTimeSinceReference: Object.fromEntries(BUCKET_METRICS.map((m) => [m, value(m)])), clientLatencyNote: 'k6 지연은 집 네트워크 왕복이 섞인 체감값이다. 서버 지연은 관리 포트 http.server.requests로 본다.', diff --git a/perf/scenarios/fanmeeting-metrics.sh b/perf/scenarios/fanmeeting-metrics.sh index 0e9831d..f8e85f8 100755 --- a/perf/scenarios/fanmeeting-metrics.sh +++ b/perf/scenarios/fanmeeting-metrics.sh @@ -269,6 +269,10 @@ resources = { 'hikariAcquireMaxMs': (gauge_max('hikaricp_connections_acquire_seconds_max') or 0) * 1000, 'tomcatBusyMax': gauge_max('tomcat_threads_busy_threads'), 'tomcatMaxThreads': gauge_max('tomcat_threads_config_max_threads'), + # 동시에 열려 있는 TCP 연결(유지 연결 포함)과 한도. 게릴라 오픈처럼 새로고침이 많으면 한도(기본 8,192)에 다가간다. + 'tomcatConnectionsMax': gauge_max('tomcat_connections_current_connections'), + 'tomcatKeepAliveMax': gauge_max('tomcat_connections_keepalive_current_connections'), + 'tomcatMaxConnections': gauge_max('tomcat_connections_config_max_connections'), 'processCpuMax': gauge_max('process_cpu_usage'), 'systemCpuMax': gauge_max('system_cpu_usage'), 'cpuCount': gauge_max('system_cpu_count'), @@ -280,6 +284,8 @@ lines += [ ' resources (max over snapshots)', f" hikari active {fmt(resources['hikariActiveMax'])}/{fmt(resources['hikariMax'])} pending {fmt(resources['hikariPendingMax'])}" f" timeouts {int(hikari_timeouts)} acquire max {fmt(resources['hikariAcquireMaxMs'])}ms", + f" tomcat connections {fmt(resources['tomcatConnectionsMax'])}/{fmt(resources['tomcatMaxConnections'])}" + f" (keep-alive {fmt(resources['tomcatKeepAliveMax'])})", f" tomcat busy {fmt(resources['tomcatBusyMax'])}/{fmt(resources['tomcatMaxThreads'])}" f" cpu process {pct(resources['processCpuMax'])} system {pct(resources['systemCpuMax'])} ({fmt(resources['cpuCount'])} cores)", f" heap used {fmt(resources['heapUsedMaxMb'])}MB threads {fmt(resources['liveThreadsMax'])}", diff --git a/perf/scenarios/fanmeeting-s1.sh b/perf/scenarios/fanmeeting-s1.sh index 796fa2b..bb7d12d 100755 --- a/perf/scenarios/fanmeeting-s1.sh +++ b/perf/scenarios/fanmeeting-s1.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # 팬미팅 S1 한 회: 행사 하나로 측정 흐름 전체를 명령 하나로 돈다. 사용법은 perf/scenarios/fanmeeting.md. # -# 지표 기록 시작 → 행사 생성 → 응모 몰림(A, START_OFFSET=-2s면 B) → 점검 1 +# 지표 기록 시작 → 행사 생성 → 응모 몰림(A, START_OFFSET=-2s면 B, GUERRILLA=true면 게릴라 오픈 G) → 점검 1 # → 마감 앞뒤 응모(C) → 추첨 확정 대기 → 점검 2(D) → 결과 조회 폭주 → 점검 3 → 지표 요약(단계별) # # 결과는 RUN_DIR 한 폴더에 모인다. 측정한 사람은 이 폴더를 통째로 넘기면 된다(토큰·비밀번호는 들어가지 않는다). @@ -29,6 +29,13 @@ PEAK_RATE="${PEAK_RATE:-1000}" RAMP="${RAMP:-5s}" HOLD="${HOLD:-}" # 비우면 참여자 수와 도착률로 계산 START_OFFSET="${START_OFFSET:-2s}" # A: 2s(Open Worker 뒤), B: -2s(오픈 직전부터) +# G 게릴라 오픈: 오픈 시각을 숨긴 행사(OPENS_AT_PUBLIC=false). 참여자 전원이 오픈 PREOPEN 전부터 상세를 +# POLL_MIN~POLL_MAX 간격으로 새로고침하다가 OPEN이 보이면 응모한다. 이때 PEAK_RATE·RAMP·HOLD는 쓰지 않는다. +GUERRILLA="${GUERRILLA:-false}" +PREOPEN="${PREOPEN:-60s}" +POLL_MIN="${POLL_MIN:-1s}" +POLL_MAX="${POLL_MAX:-3s}" +OPEN_WAIT="${OPEN_WAIT:-120s}" CLOSE_PARTICIPANTS="${CLOSE_PARTICIPANTS:-500}" # C. 0이면 건너뜀 CLOSE_RATE="${CLOSE_RATE:-}" # 비우면 마감 3초 전부터 약 6초에 걸쳐 보내도록 자동 RESULT="${RESULT:-true}" # 결과 조회 폭주. false면 건너뜀 @@ -44,6 +51,10 @@ K6_DASHBOARD_PORT="${K6_DASHBOARD_PORT:-5665}" INVARIANTS_SQL="${INVARIANTS_SQL:-$REPO/backend/src/test/resources/harness/fanmeeting-invariants.sql}" RUN_DIR="${RUN_DIR:-$REPO/.ai-output/perf/s1-$(date -u +%m%d-%H%M)-p${PARTICIPANTS}-r${PEAK_RATE}}" [[ "$K6_DASHBOARD" == "true" || "$K6_DASHBOARD" == "false" ]] || die "K6_DASHBOARD must be true or false: $K6_DASHBOARD" +[[ "$GUERRILLA" == "true" || "$GUERRILLA" == "false" ]] || die "GUERRILLA must be true or false: $GUERRILLA" +for v in PREOPEN POLL_MIN POLL_MAX OPEN_WAIT; do + [[ "${!v}" =~ ^[0-9]+(ms|s|m)?$ ]] || die "$v must look like 60s, 1500ms or 2m: ${!v}" +done for n in PARTICIPANTS PEAK_RATE CLOSE_PARTICIPANTS RESULT_RATE DRAW_TIMEOUT METRICS_INTERVAL K6_DASHBOARD_PORT; do [[ "${!n}" =~ ^[0-9]+$ ]] || die "$n must be a whole number: ${!n}" done @@ -110,6 +121,7 @@ participants=$PARTICIPANTS peak_rate=$PEAK_RATE ramp=$RAMP hold=$HOLD start_offs close_participants=$CLOSE_PARTICIPANTS close_rate=$CLOSE_RATE result=$RESULT result_rate=$RESULT_RATE result_hold=$RESULT_HOLD winner_limit=${WINNER_LIMIT:-300} reserve_limit=${RESERVE_LIMIT:-100} fee_amount=${FEE_AMOUNT:-50000} open_in=${OPEN_IN:-3m} +guerrilla=$GUERRILLA$( [[ "$GUERRILLA" == "true" ]] && echo " preopen=$PREOPEN poll=$POLL_MIN~$POLL_MAX open_wait=$OPEN_WAIT (peak_rate, ramp, hold unused for apply)") db_check=$DB_CHECK metrics_interval=${METRICS_INTERVAL}s users_available=$available k6_dashboard=$K6_DASHBOARD EOF say "run dir $RUN_DIR" @@ -203,19 +215,29 @@ step() { # step : 실패해도 흐름은 계속 가고 끝 # ---------------------------------------------------------------- 1. 행사 생성 begin prepare +# 게릴라 오픈이면 오픈 시각을 숨긴 행사를 만든다. +[[ "$GUERRILLA" == "true" ]] && export OPENS_AT_PUBLIC=false "$ROOT/fanmeeting-prepare.sh" || { finish prepare $?; die "prepare failed"; } finish prepare 0 # shellcheck disable=SC1090 source "$EVENT_FILE" -# ---------------------------------------------------------------- 2. 응모 몰림 (A, 또는 START_OFFSET<0이면 B) -# 시나리오를 k6에 명시한다. A는 전원 201이어야 하고, B는 오픈 전 거절이 정상이다(판정이 다르다). -apply_scenario=A; [[ "$START_OFFSET" == -* ]] && apply_scenario=B -apply_phase="apply-$apply_scenario" -say "k6 waits until $FM_ENTRY_OPENS_AT ${START_OFFSET} (participants $PARTICIPANTS, ${PEAK_RATE}/s, ramp $RAMP, hold $HOLD)" -step "$apply_phase" run_k6 "$apply_phase" fanmeeting-apply.js SCENARIO="$apply_scenario" MODE=open START_OFFSET="$START_OFFSET" \ - PARTICIPANTS="$PARTICIPANTS" USER_OFFSET=0 PEAK_RATE="$PEAK_RATE" RAMP="$RAMP" HOLD="$HOLD" \ - ${PRE_VUS:+PRE_VUS=$PRE_VUS} ${MAX_VUS:+MAX_VUS=$MAX_VUS} +# ---------------------------------------------------------------- 2. 응모 몰림 (A, START_OFFSET<0이면 B, GUERRILLA=true면 G) +# 시나리오를 k6에 명시한다. A·G는 전원 201이어야 하고, B는 오픈 전 거절이 정상이다(판정이 다르다). +if [[ "$GUERRILLA" == "true" ]]; then + apply_scenario=G + apply_phase="apply-G" + say "k6 waits until $FM_ENTRY_OPENS_AT -$PREOPEN, then $PARTICIPANTS members refresh every $POLL_MIN~$POLL_MAX and apply when OPEN shows" + step "$apply_phase" run_k6 "$apply_phase" fanmeeting-apply.js SCENARIO=G MODE=open START_OFFSET="-$PREOPEN" \ + PARTICIPANTS="$PARTICIPANTS" USER_OFFSET=0 POLL_MIN="$POLL_MIN" POLL_MAX="$POLL_MAX" OPEN_WAIT="$OPEN_WAIT" +else + apply_scenario=A; [[ "$START_OFFSET" == -* ]] && apply_scenario=B + apply_phase="apply-$apply_scenario" + say "k6 waits until $FM_ENTRY_OPENS_AT ${START_OFFSET} (participants $PARTICIPANTS, ${PEAK_RATE}/s, ramp $RAMP, hold $HOLD)" + step "$apply_phase" run_k6 "$apply_phase" fanmeeting-apply.js SCENARIO="$apply_scenario" MODE=open START_OFFSET="$START_OFFSET" \ + PARTICIPANTS="$PARTICIPANTS" USER_OFFSET=0 PEAK_RATE="$PEAK_RATE" RAMP="$RAMP" HOLD="$HOLD" \ + ${PRE_VUS:+PRE_VUS=$PRE_VUS} ${MAX_VUS:+MAX_VUS=$MAX_VUS} +fi step check-1-apply run_check check-1-apply "$RUN_DIR/$apply_phase.json" # 결과 조회에서 NOT_APPLIED가 나와야 하는 인원 = A(B) 참여자 중 응모가 안 된 사람. @@ -314,7 +336,7 @@ print('\nphases (UTC)') for line in list(open(os.path.join(d, 'timeline.tsv')))[1:]: p, s, e, c, sf, su = (line.rstrip('\n').split('\t') + ['-', '-'])[:6] print(f" {p:16} {s} → {e} exit {c} snapshots {sf} → {su}") -for name in ('apply-A', 'apply-B', 'apply-C'): +for name in ('apply-A', 'apply-B', 'apply-G', 'apply-C'): s = load(f'{name}.json') if not s: continue @@ -324,6 +346,13 @@ for name in ('apply-A', 'apply-B', 'apply-C'): f"requests sent {s['requestsTotal']}/{s['conditions']['participants']}") print(' applied by time ' + ' '.join(f"{k[11:]} {v}" for k, v in b.items() if k.startswith('fm_applied_'))) print(' closed by time ' + ' '.join(f"{k[17:]} {v}" for k, v in b.items() if k.startswith('fm_window_closed_'))) + g = s.get('guerrilla') + if g: + lat = lambda t: '-' if not t else f"med {t.get('med', 0):.0f} p95 {t.get('p(95)', 0):.0f} max {t.get('max', 0):.0f} ms" + print(f" guerrilla: opensAt hidden {s['conditions'].get('guerrilla')}, refresh {s['conditions'].get('pollMin')}~{s['conditions'].get('pollMax')}, " + f"detail requests {g['detailRequests']} (5xx {g['detailServerError']}, transport {g['detailTransportError']}, " + f"other {g['detailOtherError']}), never saw OPEN {g['neverSawOpen']}") + print(f" detail latency {lat(g['detailLatency'])}; OPEN first seen after the open {lat(g['openSeenAfterMs'])}") if s['failedThresholds']: print(' thresholds FAILED: ' + ', '.join(s['failedThresholds'])) r = load('result.json') @@ -341,7 +370,7 @@ if r: if r['failedThresholds']: print(' thresholds FAILED: ' + ', '.join(r['failedThresholds'])) pct = lambda v: '-' if v is None else f'{v * 100:.0f}%' -for name in ('apply-A', 'apply-B', 'apply-C', 'result'): +for name in ('apply-A', 'apply-B', 'apply-G', 'apply-C', 'result'): m = load(f'metrics-{name}.json') if not m: continue @@ -358,6 +387,8 @@ for name in ('apply-A', 'apply-B', 'apply-C', 'result'): f"peak {fmt(e['successPeakRate'])}/s), " f"p95 {fmt(e['p95Ms'])}ms, p99 {fmt(e['p99Ms'])}ms, max {fmt(e['maxMs'])}ms") res = m['resources'] + print(f" tomcat connections max {res.get('tomcatConnectionsMax')}/{res.get('tomcatMaxConnections')} " + f"(keep-alive {res.get('tomcatKeepAliveMax')}), busy threads max {res.get('tomcatBusyMax')}/{res.get('tomcatMaxThreads')}") print(f" hikari active max {res['hikariActiveMax']}/{res['hikariMax']}, pending max {res['hikariPendingMax']}, " f"timeouts {res['hikariTimeouts']}; cpu process max {pct(res['processCpuMax'])}, system max {pct(res['systemCpuMax'])}") for name in ('check-1-apply', 'check-2-draw', 'check-3-result'): diff --git a/perf/scenarios/fanmeeting.md b/perf/scenarios/fanmeeting.md index 623a68d..907615a 100644 --- a/perf/scenarios/fanmeeting.md +++ b/perf/scenarios/fanmeeting.md @@ -16,7 +16,7 @@ ```text 지표 기록 시작 (fanmeeting-metrics.sh, 백그라운드) → 행사 생성 (fanmeeting-prepare.sh) -→ 응모 몰림 A: 오픈 + START_OFFSET부터 PARTICIPANTS명, PEAK_RATE/s (START_OFFSET=-2s면 B) +→ 응모 몰림 A: 오픈 + START_OFFSET부터 PARTICIPANTS명, PEAK_RATE/s (START_OFFSET=-2s면 B, GUERRILLA=true면 게릴라 오픈 G) → 점검 1: 불변식, 회원당 1건, k6 201 = APPLIED → 마감 앞뒤 C: 마감 3초 전부터 안 쓴 계정 CLOSE_PARTICIPANTS명 → 추첨 확정 대기 → 점검 2: 추첨 시간(D), 당첨·예비·주문 수 @@ -72,6 +72,7 @@ EC2에서 빌려 쓸 때는 [perf/ec2](../ec2/README.md) 순서를 따른다. |---|---|---| | `PARTICIPANTS`, `PEAK_RATE`, `RAMP`, `HOLD` | 1000, 1000, 5s, 자동 | A의 참여자와 도착률. `HOLD`를 비우면 모든 참여자가 보낼 만큼 자동으로 잡는다 | | `START_OFFSET` | `2s` | A는 `2s`, B는 `-2s`. 음수면 B(`SCENARIO=B`, 단계 이름 `apply-B`), 0 이상이면 A(`SCENARIO=A`)로 k6에 넘긴다 | +| `GUERRILLA`, `PREOPEN`, `POLL_MIN`, `POLL_MAX`, `OPEN_WAIT` | `false`, 60s, 1s, 3s, 120s | `true`면 A·B 대신 게릴라 오픈 G(단계 이름 `apply-G`). 오픈 시각을 숨긴 행사(`OPENS_AT_PUBLIC=false`)를 만들고, 참여자 전원이 오픈 `PREOPEN` 전부터 상세를 `POLL_MIN`~`POLL_MAX` 간격으로 새로고침하다가 OPEN이 보이면 응모한다. `PEAK_RATE`·`RAMP`·`HOLD`는 쓰지 않는다. 오픈 전 새로고침 부하 ≈ 참여자 ÷ 평균 간격(초당) | | `CLOSE_PARTICIPANTS`, `CLOSE_RATE` | 500, 자동 | C. A가 쓰지 않은 계정(`USER_OFFSET=PARTICIPANTS`)을 쓴다. 계정이 모자라면 남는 만큼만, 0이면 건너뛴다. 도착률을 비우면 마감 3초 전부터 약 6초에 걸쳐 보내도록(참여자/6) 정한다 | | `RESULT`, `RESULT_RATE`, `RESULT_HOLD` | `true`, `PEAK_RATE`, 자동 | 결과 조회 폭주. A 참여자만 조회한다. C가 있으면 DB의 당첨·예비·주문 수에는 C 응모자도 들어가므로 첫 바퀴 수가 DB보다 작다 | | `DRAW_TIMEOUT` | 600 | 마감 뒤 추첨 확정을 기다리는 최대 초. 넘으면 조회를 건너뛴다 | @@ -106,6 +107,7 @@ EC2에서 빌려 쓸 때는 [perf/ec2](../ec2/README.md) 순서를 따른다. | 4 | `PARTICIPANTS=10000 PEAK_RATE=2000` | 〃 (3에서 이미 무너졌으면 생략) | | 5 | `PARTICIPANTS=100000 PEAK_RATE=<한계의 70~80%> CLOSE_PARTICIPANTS=0` | 10만 응모, 추첨(D), 조회. 계정을 A가 다 쓰므로 C는 없음 | | 6 | `PARTICIPANTS=10000 PEAK_RATE=1000 START_OFFSET=-2s` | B: 오픈 직후 거절 수 | +| G | `GUERRILLA=true PARTICIPANTS= POLL_MIN= POLL_MAX=` | 게릴라 오픈: 새로고침이 몰린 서버에 응모가 얹힐 때. N·간격은 한계 TPS를 본 뒤 오픈 전 새로고침이 한계의 50~70%가 되게 정한다 | - 회차 사이에는 다른 측정과 겹치지 않게 한다. 한 회 안에서 행사는 하나만 연다. - 노트북이 먼저 막혔는지 `summary.txt`의 `dropped`와 k6 요약의 `http_req_connecting`으로 확인한다([기준](../README.md#부하-발생기를-ec2로-옮기는-기준)). @@ -159,6 +161,7 @@ FROM_SNAPSHOT=<처음 ms> UNTIL_SNAPSHOT=<나중 ms> perf/scenarios/fanmeeting-m | `success (<코드>)` `avg`, `peak` (/s) | **성공 처리량.** 응모(POST)는 201만, 조회(GET)는 200만 센다. 응모의 성공 TPS, 조회의 성공 RPS다 | | `p50`, `p95`, `p99`, `max` | 서버 처리 시간(히스토그램 구간 보간). 네트워크 왕복이 없는 값이다 | | hikari `active/max`, `pending`, `timeouts`, `acquire max` | 연결 풀. active가 max에 붙고 pending이 쌓이면 연결 풀이 병목이다 | +| tomcat `connections` (keep-alive) | 동시에 열린 TCP 연결과 한도(기본 8,192). 넘치면 연결 단계에서 거절된다 | | tomcat `busy`, cpu `process`/`system`, heap | 요청 스레드, CPU, 메모리 | | fanmeeting workers | Worker 실행 수, 오류, 평균·최대 시간. 열기·마감 지연을 볼 때 `run`(열기·마감)을 본다 | @@ -178,6 +181,7 @@ FROM_SNAPSHOT=<처음 ms> UNTIL_SNAPSHOT=<나중 ms> perf/scenarios/fanmeeting-m | A | 오픈 순간 몰림. **전원 201**(거절 0), `APPLICATION_BUSY` 0, 불변식 0 | `SCENARIO=A` (기본 `START_OFFSET=2s`) | | B | 오픈 직전부터 보낼 때 Open Worker 지연. 오픈 뒤 몇 초 동안 `APPLICATION_WINDOW_CLOSED`가 나는지 | `SCENARIO=B` (기본 `START_OFFSET=-2s`) | | C | 마감 앞뒤 요청. 마감 1초 뒤부터 보낸 요청의 201이 0인지 | `SCENARIO=C` (`MODE=close`, 기본 `START_OFFSET=-3s`) | +| G | 게릴라 오픈. 오픈 시각을 모르는 회원들이 상세를 새로고침하다가 OPEN을 본 순간 응모. 전원 201, 상세 조회 오류 0, OPEN을 끝내 못 본 회원 0. OPEN이 처음 보인 시각(Open Worker 지연 + 새로고침 간격)과 동시 연결 수를 본다 | `SCENARIO=G` (기본 `START_OFFSET=-60s`, `POLL_MIN`·`POLL_MAX`·`OPEN_WAIT`), 행사는 `OPENS_AT_PUBLIC=false` | | D | 마감 뒤 추첨 시간. `started_at → completed_at`, `attempt_count`, `candidate_count` | 마감 뒤 `fanmeeting-check.sh` | - 응모 기간은 10분 고정이다([정책 3절](../../docs/domains/fanmeeting/policy.md)). 행사 하나로 A나 B를 한 번, 같은 행사 마감에 C를 한 번 돌릴 수 있다. 측정마다 새 행사를 만든다. @@ -241,12 +245,13 @@ perf/scenarios/fanmeeting-check.sh |---|---|---| | `BASE_URL`, `MANAGEMENT_URL`, `PERF_ALLOWED_APP_HOSTS`, `SEED_OUT` | 드롭과 같음 | 드롭 절 참고 | | `EVENT_FILE` | 없음 | prepare가 만든 파일. 또는 `EVENT_ID`, `ENTRY_OPENS_AT`, `ENTRY_CLOSES_AT`를 직접 준다 | -| `SCENARIO` | `MODE`와 시작 시각으로 정함 | `A`, `B`, `C`. 비우면 `MODE=close`는 C, `MODE=open`은 시작 시각이 오픈 전이면 B, 아니면 A. A는 시작이 오픈 이후, B는 오픈 전이어야 하고 C는 `MODE=close`여야 한다(아니면 시작하지 않는다) | +| `SCENARIO` | `MODE`와 시작 시각으로 정함 | `A`, `B`, `C`, `G`. G는 명시해야 한다. 비우면 `MODE=close`는 C, `MODE=open`은 시작 시각이 오픈 전이면 B, 아니면 A. A는 시작이 오픈 이후, B는 오픈 전이어야 하고 C는 `MODE=close`여야 한다(아니면 시작하지 않는다) | | `MODE` | `SCENARIO`가 C면 `close`, 아니면 `open` | `open`이면 기준 시각이 오픈(A·B), `close`면 마감(C) | | `START_OFFSET` | A `2s`, B `-2s`, C `-3s` | 기준 시각에서 부하 시작까지. `-2s`, `500ms`, `2s` | | `START_AT` | 기준 시각 + `START_OFFSET` | 시작 시각을 ISO-8601로 직접 줄 때 | | `PARTICIPANTS`, `USER_OFFSET` | 1000, 0 | `users.csv`의 USER 행 중 `USER_OFFSET` 다음부터 쓰는 계정 수. C는 같은 행사에 응모하지 않은 계정을 쓰도록 `USER_OFFSET`을 준다 | -| `PEAK_RATE`, `RAMP`, `HOLD` | 1000, 5s, 20s | 최고 도착률(초당 반복), 오르는 시간, 유지 시간 | +| `PEAK_RATE`, `RAMP`, `HOLD` | 1000, 5s, 20s | 최고 도착률(초당 반복), 오르는 시간, 유지 시간 (G는 쓰지 않음) | +| `POLL_MIN`, `POLL_MAX`, `OPEN_WAIT` | 1s, 3s, 120s | G만. 회원마다 무작위 새로고침 간격, 오픈 뒤 OPEN이 보일 때까지 기다리는 최대 시간 | | `PRE_VUS`, `MAX_VUS` | 500, 3000 | 미리 만들 VU, 최대 VU | | `SUMMARY_PATH` | 없음 | JSON 요약 경로 |