|
| 1 | +#!/bin/sh |
| 2 | +set -e |
| 3 | + |
| 4 | +# This is a simulation of a cache warming process. |
| 5 | +# It fetches the frontend info, stores it in the cache under the job pod |
| 6 | +# hostname and reads it back to verify the round-trip. |
| 7 | +# |
| 8 | +# Log lines mimic the Log4j 2 default PatternLayout: |
| 9 | +# %d{yyyy-MM-dd HH:mm:ss,SSS} [%thread] %-5level %logger{36} - %msg |
| 10 | + |
| 11 | +LOGGER="com.stefanprodan.podinfo.WarmCache" |
| 12 | +THREAD="main" |
| 13 | + |
| 14 | +log() { |
| 15 | + level="$1" |
| 16 | + shift |
| 17 | + # millisecond precision timestamp; fall back gracefully if %N is unsupported |
| 18 | + ts="$(date '+%Y-%m-%d %H:%M:%S,%N' 2>/dev/null)" |
| 19 | + case "$ts" in |
| 20 | + *%N|*,) ts="$(date '+%Y-%m-%d %H:%M:%S'),000" ;; |
| 21 | + *) ts="$(echo "$ts" | cut -c1-23)" ;; |
| 22 | + esac |
| 23 | + printf '%s [%s] %-5s %s - %s\n' "$ts" "$THREAD" "$level" "$LOGGER" "$*" |
| 24 | +} |
| 25 | + |
| 26 | +FRONTEND="${FRONTEND_URL:-http://frontend}" |
| 27 | +KEY="$(hostname)" |
| 28 | +START="$(date +%s)" |
| 29 | + |
| 30 | +log INFO "Fetching info from ${FRONTEND}/api/info" |
| 31 | +# Compact the (pretty-printed) JSON onto a single line so each log event |
| 32 | +# stays on one line, as Log4j renders them. |
| 33 | +INFO="$(curl -fsS "${FRONTEND}/api/info" | tr -d '\n' | sed 's/ */ /g')" |
| 34 | +log INFO "Info: ${INFO}" |
| 35 | + |
| 36 | +# Log each field of the info response on its own line. The /api/info payload |
| 37 | +# is a flat JSON object of string values, so we can split it without jq. |
| 38 | +echo "$INFO" | sed 's/^{//; s/}$//' | tr ',' '\n' | while IFS= read -r field; do |
| 39 | + field="$(echo "$field" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//; s/"//g')" |
| 40 | + if [ -n "$field" ]; then |
| 41 | + log DEBUG "info ${field}" |
| 42 | + fi |
| 43 | +done |
| 44 | + |
| 45 | +log INFO "Writing info to cache key ${KEY}" |
| 46 | +curl -fsS -X POST -H "Content-Type: application/json" -d "${INFO}" "${FRONTEND}/cache/${KEY}" |
| 47 | + |
| 48 | +# Verify the cached value for 1 minute, polling every 10 seconds. |
| 49 | +attempt=1 |
| 50 | +while [ "$attempt" -le 6 ]; do |
| 51 | + log INFO "Reading cache key ${KEY} (attempt ${attempt}/6)" |
| 52 | + CACHED="$(curl -fsS "${FRONTEND}/cache/${KEY}")" |
| 53 | + |
| 54 | + if [ "${INFO}" = "${CACHED}" ]; then |
| 55 | + log INFO "Cache warm verified: cached value matches info" |
| 56 | + else |
| 57 | + log ERROR "Cache warm failed: cached value does not match info" |
| 58 | + log ERROR "Expected: ${INFO}" |
| 59 | + log ERROR "Got: ${CACHED}" |
| 60 | + exit 1 |
| 61 | + fi |
| 62 | + |
| 63 | + attempt=$((attempt + 1)) |
| 64 | + if [ "$attempt" -le 6 ]; then |
| 65 | + sleep 10 |
| 66 | + fi |
| 67 | +done |
| 68 | + |
| 69 | +log INFO "Cache warm finished in $(( $(date +%s) - START ))s" |
0 commit comments