Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,12 @@ services:
result:
build: ./result
# use nodemon rather than node for local dev
entrypoint: nodemon --inspect=0.0.0.0 server.js
command: ["node", "server.js"]
depends_on:
db:
condition: service_healthy
volumes:
- ./result:/usr/local/app
condition: service_healthy
ports:
- "8081:80"
- "127.0.0.1:9229:9229"
networks:
- front-tier
- back-tier
Expand Down
5 changes: 5 additions & 0 deletions result/.dockerignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
node_modules/
npm-debug.log*
.env
.env.*
.git/
coverage/
25 changes: 16 additions & 9 deletions result/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
FROM node:18-slim
FROM node:18-slim@sha256:f9ab18e354e6855ae56ef2b290dd225c1e51a564f87584b9bd21dd651838830e

# add curl for healthcheck
# Install runtime utilities
RUN apt-get update && \
apt-get install -y --no-install-recommends curl tini && \
rm -rf /var/lib/apt/lists/*

WORKDIR /usr/local/app

# have nodemon available for local dev use (file watching)
RUN npm install -g nodemon

# Install production dependencies
COPY package*.json ./
RUN npm ci --omit=dev && \
npm cache clean --force && \
mv /usr/local/app/node_modules /node_modules

RUN npm ci && \
npm cache clean --force && \
mv /usr/local/app/node_modules /node_modules

# Copy application files
COPY . .

# Create a dedicated non-root user and set file ownership
RUN groupadd --system appuser && \
useradd --system --gid appuser --home-dir /home/appuser \
--create-home appuser && \
chown -R appuser:appuser /usr/local/app

ENV PORT=80
EXPOSE 80

# Run as non-root
USER appuser

ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["node", "server.js"]
40 changes: 30 additions & 10 deletions result/tests/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
FROM node:8.9-slim

RUN apt-get update -qq && apt-get install -qy \
ca-certificates \
bzip2 \
curl \
libfontconfig \
--no-install-recommends
RUN yarn global add phantomjs-prebuilt
ADD . /app

FROM node:18-slim@sha256:f9ab18e354e6855ae56ef2b290dd225c1e51a564f87584b9bd21dd651838830e

# Install utilities required by the test script
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ca-certificates \
bash \
curl \
bzip2 \
libfontconfig1 \
tini && \
rm -rf /var/lib/apt/lists/*

# Install PhantomJS for browser-based testing
RUN npm install --global phantomjs-prebuilt

WORKDIR /app

# Copy the test files
COPY tests.sh render.js ./

# Create a non-root user and set file ownership
RUN groupadd --system appuser && \
useradd --system --gid appuser --create-home appuser && \
chown -R appuser:appuser /app && \
chmod +x /app/tests.sh

USER appuser

ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/app/tests.sh"]
28 changes: 18 additions & 10 deletions result/tests/tests.sh
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
#!/bin/sh
set -eu

# Wait until the voting service is reachable
while ! timeout 1 bash -c "echo > /dev/tcp/vote/80"; do
sleep 1
done

curl -sS -X POST --data "vote=b" http://vote > /dev/null
# Read the rendered vote count before submitting a vote
before=$(phantomjs render.js http://result | grep -oE '[0-9]+ votes?' | head -n 1 | grep -oE '^[0-9]+' || echo 0)

# Submit one vote
curl -fsS -X POST --data "vote=b" http://vote > /dev/null

# Allow time for the vote to be processed
sleep 10

if phantomjs render.js http://result | grep -q '1 vote'; then
echo -e "\\e[42m------------"
echo -e "\\e[92mTests passed"
echo -e "\\e[42m------------"
exit 0
# Read the rendered vote count again
after=$(phantomjs render.js http://result | grep -oE '[0-9]+ votes?' | head -n 1 | grep -oE '^[0-9]+' || echo 0)

# Confirm that the vote count increased
if [ "$after" -gt "$before" ]; then
echo "Tests passed: vote count increased from $before to $after."
exit 0
else
echo -e "\\e[41m------------"
echo -e "\\e[91mTests failed"
echo -e "\\e[41m------------"
exit 1
echo "Tests failed: vote count did not increase. Before: $before; after: $after."
exit 1
fi
9 changes: 9 additions & 0 deletions vote/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
__pycache__/
*.py[cod]
*.log
.venv/
venv/
.env
.env.*
.git/
.pytest_cache/
39 changes: 26 additions & 13 deletions vote/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,32 +1,45 @@
# base defines a base stage that uses the official python runtime base image
FROM python:3.11-slim AS base

# Add curl for healthcheck
# Base image for the voting application

FROM python:3.11-slim@sha256:b7a9e5f6a93d6d4a31f129bbd4bdee69efccb6ded0fb230d78aafaf37af98377 AS base

# Install curl for the Compose health check
RUN apt-get update && \
apt-get install -y --no-install-recommends curl && \
rm -rf /var/lib/apt/lists/*

# Set the application directory
WORKDIR /usr/local/app

# Install our requirements.txt
# Install Python dependencies
COPY requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# dev defines a stage for development, where it'll watch for filesystem changes
# Development stage: preserve existing local workflow
FROM base AS dev
RUN pip install watchdog
RUN pip install --no-cache-dir watchdog

# Create an unprivileged application user
RUN useradd --create-home --uid 10001 appuser

WORKDIR /usr/local/app
COPY --chown=appuser:appuser . .

USER appuser

ENV FLASK_ENV=development
CMD ["python", "app.py"]

# final defines the stage that will bundle the application for production
# Production stage
FROM base AS final

# Copy our code from the current folder to the working directory inside the container
COPY . .
# Create an unprivileged application user
RUN useradd --create-home --uid 10001 appuser

COPY --chown=appuser:appuser . .

USER appuser

# Make port 80 available for links and/or publish
EXPOSE 80
EXPOSE 8080

# Define our command to be run when launching the container
CMD ["gunicorn", "app:app", "-b", "0.0.0.0:80", "--log-file", "-", "--access-logfile", "-", "--workers", "4", "--keep-alive", "0"]
CMD ["gunicorn", "app:app", "-b", "0.0.0.0:8080", "--log-file", "-", "--access-logfile", "-", "--workers", "4", "--keep-alive", "0"]
7 changes: 7 additions & 0 deletions worker/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
bin/
obj/
*.user
*.suo
.env
.env.*
.git/
19 changes: 16 additions & 3 deletions worker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# docker buildx build --platform "linux/arm64/v8" .

# build compiles the program for the builder's local platform
FROM --platform=${BUILDPLATFORM} mcr.microsoft.com/dotnet/sdk:7.0 AS build
FROM --platform=${BUILDPLATFORM} mcr.microsoft.com/dotnet/sdk:10.0@sha256:9c7b6b263d9d4c2e4718e16dae6d75cd8f4b5ccf206f1e7d48a98eb429981b03 AS build
ARG TARGETPLATFORM
ARG TARGETARCH
ARG BUILDPLATFORM
Expand All @@ -20,9 +20,22 @@ RUN dotnet restore -a $TARGETARCH

COPY . .
RUN dotnet publish -c release -o /app -a $TARGETARCH --self-contained false --no-restore

# app image
FROM mcr.microsoft.com/dotnet/runtime:7.0
FROM mcr.microsoft.com/dotnet/runtime:10.0@sha256:de1261f1b137a580e6620fa3f20323efa7bb131a2aeb103cab95077d3445122d

# Install the Kerberos runtime library
USER root
RUN apt-get update \
&& apt-get install -y --no-install-recommends libgssapi-krb5-2 \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=build /app .

# Create a dedicated non-root user
RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin appuser

# Run the application without root privileges
USER 10001:10001

ENTRYPOINT ["dotnet", "Worker.dll"]
66 changes: 39 additions & 27 deletions worker/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,38 +20,47 @@ public static int Main(string[] args)
var redisConn = OpenRedisConnection("redis");
var redis = redisConn.GetDatabase();

// Keep alive is not implemented in Npgsql yet. This workaround was recommended:
// https://github.com/npgsql/npgsql/issues/1214#issuecomment-235828359
// Keep the database connection alive.
var keepAliveCommand = pgsql.CreateCommand();
keepAliveCommand.CommandText = "SELECT 1";

var definition = new { vote = "", voter_id = "" };

while (true)
{
// Slow down to prevent CPU spike, only query each 100ms
Thread.Sleep(100);

// Reconnect redis if down
if (redisConn == null || !redisConn.IsConnected) {
// Reconnect Redis if disconnected.
if (redisConn == null || !redisConn.IsConnected)
{
Console.WriteLine("Reconnecting Redis");
redisConn = OpenRedisConnection("redis");
redis = redisConn.GetDatabase();
}

string json = redis.ListLeftPopAsync("votes").Result;

if (json != null)
{
var vote = JsonConvert.DeserializeAnonymousType(json, definition);
Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'");
// Reconnect DB if down

Console.WriteLine(
$"Processing vote for '{vote.vote}' by '{vote.voter_id}'"
);

// Reconnect DB if disconnected.
if (!pgsql.State.Equals(System.Data.ConnectionState.Open))
{
Console.WriteLine("Reconnecting DB");
pgsql = OpenDbConnection("Server=db;Username=postgres;Password=postgres;");
}
else
{ // Normal +1 vote requested
UpdateVote(pgsql, vote.voter_id, vote.vote);
pgsql = OpenDbConnection(
"Server=db;Username=postgres;Password=postgres;"
);

keepAliveCommand = pgsql.CreateCommand();
keepAliveCommand.CommandText = "SELECT 1";
}

UpdateVote(pgsql, vote.voter_id, vote.vote);
}
else
{
Expand Down Expand Up @@ -93,19 +102,22 @@ private static NpgsqlConnection OpenDbConnection(string connectionString)
Console.Error.WriteLine("Connected to db");

var command = connection.CreateCommand();

command.CommandText = @"CREATE TABLE IF NOT EXISTS votes (
id VARCHAR(255) NOT NULL UNIQUE,
vote VARCHAR(255) NOT NULL
)";

command.ExecuteNonQuery();

return connection;
}

private static ConnectionMultiplexer OpenRedisConnection(string hostname)
{
// Use IP address to workaround https://github.com/StackExchange/StackExchange.Redis/issues/410
// Resolve Redis hostname to an IP address.
var ipAddress = GetIp(hostname);

Console.WriteLine($"Found redis at {ipAddress}");

while (true)
Expand All @@ -130,25 +142,25 @@ private static string GetIp(string hostname)
.First(a => a.AddressFamily == AddressFamily.InterNetwork)
.ToString();

private static void UpdateVote(NpgsqlConnection connection, string voterId, string vote)
private static void UpdateVote(
NpgsqlConnection connection,
string voterId,
string vote)
{
var command = connection.CreateCommand();
try
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO votes (id, vote) VALUES (@id, @vote)";
command.CommandText = @"
INSERT INTO votes (id, vote)
VALUES (@id, @vote)
ON CONFLICT (id)
DO UPDATE SET vote = EXCLUDED.vote;
";

command.Parameters.AddWithValue("@id", voterId);
command.Parameters.AddWithValue("@vote", vote);

command.ExecuteNonQuery();
}
catch (DbException)
{
command.CommandText = "UPDATE votes SET vote = @vote WHERE id = @id";
command.ExecuteNonQuery();
}
finally
{
command.Dispose();
}
}
}
}
}
Loading