From 96bf92eddd280002dd2dcd4a402e39f0c0eeb041 Mon Sep 17 00:00:00 2001 From: Szabolcs Horvath Date: Fri, 3 Jan 2025 11:08:53 +0100 Subject: [PATCH] Add user-data script for installing service on a cloud provider VM The script will: 1. Install necessary dependencies 2. Create the DB file 3. Run the migrations 4. Initialize the DB with the seed data 5. Move the systemd unit file to the correct location 6. Enable the systemd service The script will NOT: - Create the `.env` file - Start the server (the systemd service will start the server on reboot tho) --- Makefile | 7 +++++++ prod/nutrition-tracker.service | 19 +++++++++++++++++++ prod/user-data.sh | 20 ++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 prod/nutrition-tracker.service create mode 100644 prod/user-data.sh diff --git a/Makefile b/Makefile index f7c985e..2c2a4cf 100644 --- a/Makefile +++ b/Makefile @@ -12,6 +12,13 @@ HTMX_VERSION ?= 2.0.3 BOOTSTRAP_VERSION ?= 5.3.3 BOOTSTRAP_ICONS_VERSION ?= 1.11.3 +install: install-go-deps init-db build + mv -u prod/nutrition-tracker.service /etc/systemd/system/nutrition-tracker.service + systemctl enable nutrition-tracker.service + +start: + systemctl start nutrition-tracker.service + install-go-deps: go install -v github.com/sqlc-dev/sqlc/cmd/sqlc@$(SQLC_VERSION) go install -v -tags 'sqlite3' github.com/golang-migrate/migrate/v4/cmd/migrate@$(GOLANG_MIGRATE_VERSION) diff --git a/prod/nutrition-tracker.service b/prod/nutrition-tracker.service new file mode 100644 index 0000000..9d5e6c0 --- /dev/null +++ b/prod/nutrition-tracker.service @@ -0,0 +1,19 @@ +[Unit] +Description=Nutrition Tracker server +ConditionFileNotEmpty=~/nutriton-tracker/.env +ConditionPathExists=~/nutriton-tracker/sqlite/nutrition-tracker.db +After=multi-user.target +Wants=multi-user.target +StartLimitIntervalSec=600 +StartLimitBurst=5 + +[Service] +Type=simple +ExecStartPre=/bin/bash -c 'echo "$(date +"%%F-%%T") starting" >> /var/log/nutrition-tracker-starts.log' +ExecStart=/bin/bash -c '~/nutriton-tracker/out/nutrition-tracker ~/nutriton-tracker/.env 2>&1 | tee /var/log/nutrition-tracker.log && exit ${PIPESTATUS[0]}' +ExecStartPost=/bin/bash -c 'echo "$(date +"%%F-%%T") started" >> /var/log/nutrition-tracker-starts.log' +Restart=on-failure +TimeoutSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/prod/user-data.sh b/prod/user-data.sh new file mode 100644 index 0000000..ae6a1cb --- /dev/null +++ b/prod/user-data.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# logging +exec >> /var/log/user-data.log +exec 2>&1 + +set -ex -o pipefail + +main() { + if [[ ! -d ~/nutrition-tracker ]]; then + cd ~ + git clone https://github.com/szabolcs-horvath/nutrition-tracker.git + cd nutrition-tracker + make install + else + echo "Nutrition Tracker already installed." + fi +} + +main "$@"