Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

self-hosting: supporter images through openpanel upgrade --supporter

Carl-Gerhard Lindesvärde96a6a5d5f2e
diff --git a/apps/public/content/docs/self-hosting/supporter-access-latest-docker-images.mdx b/apps/public/content/docs/self-hosting/supporter-access-latest-docker-images.mdx
index 10b8d772e..6dbf5f7bd 100644
--- a/apps/public/content/docs/self-hosting/supporter-access-latest-docker-images.mdx
+++ b/apps/public/content/docs/self-hosting/supporter-access-latest-docker-images.mdx
@@ -55,62 +55,35 @@ Replace `your_api_key` with the actual API key provided to you.
Make sure to keep your API key secure and never commit it to version control!
</Callout>
-### Step 4: Update to latest images
-
-We've created a convenient script to make updating your images effortless. Navigate to your self-hosting folder and run:
+### Step 4: Switch to the latest images
```bash
-./get_latest_images apply
+openpanel upgrade --supporter
```
-This script will:
-- Check that you're authenticated with our Docker registry
-- Fetch the latest Git tags from our repository
-- Update your `docker-compose.yml` with the new image tags pointing to the latest builds
-
-<Callout type="info">
-The script will automatically check if you're logged in. If not, it will provide you with instructions to authenticate first.
-</Callout>
+This checks that you're logged in to `docker.openpanel.dev`, finds the newest build (every push to our main branch gets a version such as `3.1.9`), points your install at it, and restarts. It shows every change and asks before writing anything.
-You can also check what tags are available without applying them:
-
-```bash
-./get_latest_images # Show latest tags
-./get_latest_images --list # List all available tags
-```
+Don't have the CLI yet? See [Get started with self-hosting](/docs/self-hosting/self-hosting#quickstart).
-### Step 5: Restart your services
+## Staying up to date
-After updating `docker-compose.yml`, recreate your services so they use the new images:
+Once your install uses the supporter images, a plain upgrade keeps it there and moves it to the newest build:
```bash
-docker compose up -d
+openpanel upgrade
```
-That's it! Your OpenPanel instance is now running the latest and greatest version.
-
-## Quick update workflow
-
-Once you're set up, updating to the latest version is as simple as:
+To go back to the public release images from Docker Hub:
```bash
-cd /path/to/self-hosting
-./get_latest_images apply
-docker compose up -d
+openpanel upgrade --public
```
-This entire process takes less than a minute, giving you instant access to new features and fixes.
-
-The `get_latest_images` script will:
-1. Verify you're logged into the Docker registry
-2. Fetch the latest tags from GitHub
-3. Update your `docker-compose.yml` with images pointing to the latest commit SHAs
-4. Create a backup of your docker-compose file before making changes
-
## Important notes
- **Stability**: While these images are tested, they may occasionally contain bugs that haven't been discovered yet. We recommend having a backup strategy.
- **Breaking changes**: We strive to maintain backwards compatibility, but occasionally breaking changes may occur. Always check the [changelog](/docs/self-hosting/changelog) before updating.
+- **Configuration changes**: `openpanel upgrade` updates your `docker-compose.yml` and `.env` for what its own release knows about. Builds newer than your CLI rarely need more; when they do, the next CLI release (installed automatically by `openpanel upgrade`) brings it.
- **Support**: As a supporter, you have priority access to support. If you encounter any issues, reach out to us on Discord or via email.
## Need help?
diff --git a/self-hosting/cli/src/commands/upgrade.ts b/self-hosting/cli/src/commands/upgrade.ts
index 03b8a1f3d..9de242f14 100644
--- a/self-hosting/cli/src/commands/upgrade.ts
+++ b/self-hosting/cli/src/commands/upgrade.ts
@@ -1,9 +1,19 @@
import { cancel, log as clackLog, confirm, isCancel } from '@clack/prompts';
-import { applyFixes, type Finding, runDoctor } from '../doctor';
+import { applyFixes, type Finding, type Install, runDoctor } from '../doctor';
import { checkHost } from '../host';
import { isInstallDir, loadInstall, writeInstall } from '../install';
import { run } from '../run';
import { type Fetcher, isCompiledBinary, selfUpdate } from '../self-update';
+import {
+ type Channel,
+ channelOf,
+ isLoggedIn,
+ LOGIN_HINT,
+ latestBuildVersion,
+ pointAt,
+ publicVersion,
+ SUPPORTER_REGISTRY,
+} from '../supporter';
import { bold, dim, SEVERITY_LABEL } from '../ui';
import { VERSION } from '../version';
import { compose } from './compose';
@@ -19,6 +29,8 @@ export interface UpgradeFlags {
yes: boolean;
queueDrained: boolean;
noSelfUpdate: boolean;
+ supporter: boolean;
+ public: boolean;
}
const ask = async (message: string, yes: boolean): Promise<boolean> => {
@@ -102,6 +114,17 @@ const confirmQueueDrained = async (flags: UpgradeFlags): Promise<boolean> => {
return ask('Has the old event queue drained?', false);
};
+// An explicit flag switches channel; otherwise the install stays where it is.
+const resolveChannel = (flags: UpgradeFlags, install: Install): Channel => {
+ if (flags.supporter) {
+ return 'supporter';
+ }
+ if (flags.public) {
+ return 'public';
+ }
+ return channelOf(install);
+};
+
export const upgrade = async (flags: UpgradeFlags): Promise<number> => {
if (!flags.noSelfUpdate && isCompiledBinary()) {
const outcome = await updateSelf();
@@ -138,6 +161,29 @@ export const upgrade = async (flags: UpgradeFlags): Promise<number> => {
}
const install = loadInstall(flags.dir);
+ // --supporter / --public switch channels; otherwise an install stays on the
+ // one it is on, so a supporter's plain `upgrade` keeps getting the newest build.
+ if (flags.supporter && flags.public) {
+ clackLog.error('Choose one of --supporter and --public.');
+ return 1;
+ }
+ const channel = resolveChannel(flags, install);
+ if (channel === 'supporter' && !isLoggedIn()) {
+ clackLog.error(
+ `Supporter images need a login to ${SUPPORTER_REGISTRY}.\n${LOGIN_HINT}`
+ );
+ return 1;
+ }
+ const version =
+ channel === 'supporter'
+ ? await latestBuildVersion(fetchWithTimeout)
+ : publicVersion();
+ clackLog.info(
+ channel === 'supporter'
+ ? `Supporter images from ${SUPPORTER_REGISTRY}, newest build: ${version}`
+ : `Public release images: ${version}`
+ );
+
const findings = runDoctor(install);
const needsDrain = findings.some(
@@ -148,17 +194,24 @@ export const upgrade = async (flags: UpgradeFlags): Promise<number> => {
return 1;
}
+ // Everything is applied in memory first, so the list below is exactly what
+ // gets written, and declining leaves the files untouched.
const fixable = findings.filter((finding) => finding.fix);
- if (fixable.length > 0) {
+ applyFixes(install);
+ const imageChanges = pointAt(install, channel, version);
+ const changeCount = fixable.length + imageChanges.length;
+ if (changeCount > 0) {
listFindings(fixable);
+ for (const change of imageChanges) {
+ clackLog.message(`image ${change}`);
+ }
const approved = await ask(
- `Apply ${fixable.length} change(s)? Originals are kept as <name>.bak`,
+ `Apply ${changeCount} change(s)? Originals are kept as <name>.bak`,
flags.yes
);
if (!approved) {
return 1;
}
- applyFixes(install);
const written = await writeInstall(flags.dir, install);
clackLog.success(`Updated ${written.join(', ')}`);
}
diff --git a/self-hosting/cli/src/main.ts b/self-hosting/cli/src/main.ts
index a7d37ef6c..630027340 100644
--- a/self-hosting/cli/src/main.ts
+++ b/self-hosting/cli/src/main.ts
@@ -23,6 +23,8 @@ Usage: openpanel <command> [options]
Commands:
init Interactive setup (--yes --domain <url> to skip prompts)
upgrade [--yes] Update the CLI, repair the install, pull images, restart
+ --supporter Use the newest build from docker.openpanel.dev (supporters)
+ --public Switch back to the public release images
export [--out <dir>] Dump ClickHouse data as JSONL (e.g. to move to Cloud)
reset [--yes] Delete this install's data volumes (asks first)
doctor [--fix] [--check] Check the host and your install; --fix repairs it
@@ -94,6 +96,8 @@ const parseFlags = () =>
force: { type: 'boolean', default: false },
'no-self-update': { type: 'boolean', default: false },
'queue-drained': { type: 'boolean', default: false },
+ supporter: { type: 'boolean', default: false },
+ public: { type: 'boolean', default: false },
container: { type: 'string' },
out: { type: 'string' },
'project-id': { type: 'string' },
@@ -193,6 +197,8 @@ const route = async (
dir: await requireInstall(values.dir),
yes: values.yes,
queueDrained: values['queue-drained'],
+ supporter: values.supporter,
+ public: values.public,
noSelfUpdate: values['no-self-update'],
});
}
diff --git a/self-hosting/cli/src/supporter.ts b/self-hosting/cli/src/supporter.ts
new file mode 100644
index 000000000..b165373a2
--- /dev/null
+++ b/self-hosting/cli/src/supporter.ts
@@ -0,0 +1,115 @@
+import { readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import type { Install } from './doctor/types';
+import { type Fetcher, isNewer } from './self-update';
+import { STACK_IMAGE_TAG } from './templates';
+
+// Supporters pull every internal build (each push to main) from this registry,
+// which mirrors ghcr.io/openpanel-dev; the public release images are on Docker Hub.
+export const SUPPORTER_REGISTRY = 'docker.openpanel.dev';
+const SUPPORTER_NAMESPACE = `${SUPPORTER_REGISTRY}/openpanel-dev`;
+const PUBLIC_NAMESPACE = 'lindesvard/openpanel-';
+const TAGS_API =
+ process.env.OPENPANEL_TAGS_API ??
+ 'https://api.github.com/repos/Openpanel-dev/openpanel/tags?per_page=100';
+const VERSION_TAG = /^v(\d+\.\d+\.\d+)$/;
+
+// The worker runs the api image, so it follows the api's repository.
+const SERVICE_APP = {
+ 'op-api': 'api',
+ 'op-worker': 'api',
+ 'op-dashboard': 'dashboard',
+} as const;
+
+export type Channel = 'public' | 'supporter';
+
+export const supporterImage = (app: string, version: string) =>
+ `${SUPPORTER_NAMESPACE}/${app}:${version}`;
+export const publicImage = (app: string, version: string) =>
+ `${PUBLIC_NAMESPACE}${app}:${version}`;
+
+export const channelOf = (install: Install): Channel => {
+ const image = install.compose.getIn(['services', 'op-api', 'image']);
+ return typeof image === 'string' && image.startsWith(`${SUPPORTER_REGISTRY}/`)
+ ? 'supporter'
+ : 'public';
+};
+
+// Points every OpenPanel service at the channel's images; returns what changed.
+export const pointAt = (
+ install: Install,
+ channel: Channel,
+ version: string
+): string[] => {
+ const changes: string[] = [];
+ for (const [service, app] of Object.entries(SERVICE_APP)) {
+ if (!install.compose.hasIn(['services', service])) {
+ continue;
+ }
+ const current = String(
+ install.compose.getIn(['services', service, 'image']) ?? ''
+ );
+ const next =
+ channel === 'supporter'
+ ? supporterImage(app, version)
+ : publicImage(app, version);
+ if (current !== next) {
+ install.compose.setIn(['services', service, 'image'], next);
+ changes.push(`${service}: ${current} → ${next}`);
+ }
+ }
+ return changes;
+};
+
+export const publicVersion = (): string => STACK_IMAGE_TAG;
+
+// Every push to main is tagged vX.Y.Z; the highest one is the newest build.
+export const latestBuildVersion = async (fetcher: Fetcher): Promise<string> => {
+ const response = await fetcher(TAGS_API);
+ if (!response.ok) {
+ throw new Error(`Could not list versions (HTTP ${response.status})`);
+ }
+ const tags = (await response.json()) as { name: string }[];
+ const versions = tags.flatMap(
+ ({ name }) => VERSION_TAG.exec(name)?.[1] ?? []
+ );
+ const latest = versions.reduce<string | null>(
+ (highest, version) =>
+ highest === null || isNewer(version, highest) ? version : highest,
+ null
+ );
+ if (!latest) {
+ throw new Error('No versioned builds found');
+ }
+ return latest;
+};
+
+interface DockerConfig {
+ auths?: Record<string, unknown>;
+ credHelpers?: Record<string, unknown>;
+}
+
+// `docker login` records the registry in config.json (under auths, or
+// credHelpers with a credential helper), whichever store holds the secret.
+export const isLoggedIn = (
+ registry: string = SUPPORTER_REGISTRY,
+ configDir: string = process.env.DOCKER_CONFIG ?? join(homedir(), '.docker')
+): boolean => {
+ try {
+ const config = JSON.parse(
+ readFileSync(join(configDir, 'config.json'), 'utf8')
+ ) as DockerConfig;
+ const keys = [
+ ...Object.keys(config.auths ?? {}),
+ ...Object.keys(config.credHelpers ?? {}),
+ ];
+ return keys.some(
+ (key) => key.replace(/^https?:\/\//, '').replace(/\/.*$/, '') === registry
+ );
+ } catch {
+ return false;
+ }
+};
+
+export const LOGIN_HINT = `Log in with your supporter key first:\n echo "<your key>" | docker login ${SUPPORTER_REGISTRY} -u user --password-stdin\nBecome a supporter at https://openpanel.dev/supporter`;
diff --git a/self-hosting/cli/test/supporter.test.ts b/self-hosting/cli/test/supporter.test.ts
new file mode 100644
index 000000000..c0b9a4b08
--- /dev/null
+++ b/self-hosting/cli/test/supporter.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseDocument } from 'yaml';
+import type { Install } from '../src/doctor/types';
+import { EnvFile } from '../src/env-file';
+import type { Fetcher } from '../src/self-update';
+import {
+ channelOf,
+ isLoggedIn,
+ latestBuildVersion,
+ pointAt,
+ SUPPORTER_REGISTRY,
+} from '../src/supporter';
+import { templates } from '../src/templates';
+
+const tempDirs: string[] = [];
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const install = (): Install => ({
+ compose: parseDocument(templates.compose),
+ env: new EnvFile(''),
+ caddyfile: null,
+ files: new Map(),
+ fileKind: () => 'file',
+});
+
+const image = (target: Install, service: string) =>
+ target.compose.getIn(['services', service, 'image']);
+
+const tagsFeed =
+ (names: string[], ok = true): Fetcher =>
+ async () =>
+ ok
+ ? Response.json(names.map((name) => ({ name })))
+ : new Response('rate limited', { status: 403 });
+
+const dockerConfig = (config: unknown) => {
+ const dir = mkdtempSync(join(tmpdir(), 'op-docker-'));
+ tempDirs.push(dir);
+ writeFileSync(join(dir, 'config.json'), JSON.stringify(config));
+ return dir;
+};
+
+describe('channels', () => {
+ test('a fresh install is on the public channel', () => {
+ expect(channelOf(install())).toBe('public');
+ });
+
+ test('switching to supporter points api and worker at the api image, dashboard at its own', () => {
+ const target = install();
+ const changes = pointAt(target, 'supporter', '3.1.9');
+
+ expect(image(target, 'op-api')).toBe(
+ `${SUPPORTER_REGISTRY}/openpanel-dev/api:3.1.9`
+ );
+ expect(image(target, 'op-worker')).toBe(
+ `${SUPPORTER_REGISTRY}/openpanel-dev/api:3.1.9`
+ );
+ expect(image(target, 'op-dashboard')).toBe(
+ `${SUPPORTER_REGISTRY}/openpanel-dev/dashboard:3.1.9`
+ );
+ expect(changes).toHaveLength(3);
+ expect(channelOf(target)).toBe('supporter');
+ });
+
+ test('switching back to public restores the Docker Hub images', () => {
+ const target = install();
+ pointAt(target, 'supporter', '3.1.9');
+ pointAt(target, 'public', '3.1.4');
+ expect(image(target, 'op-api')).toBe('lindesvard/openpanel-api:3.1.4');
+ expect(image(target, 'op-dashboard')).toBe(
+ 'lindesvard/openpanel-dashboard:3.1.4'
+ );
+ expect(channelOf(target)).toBe('public');
+ });
+
+ test('nothing changes when the images are already right', () => {
+ const target = install();
+ pointAt(target, 'supporter', '3.1.9');
+ expect(pointAt(target, 'supporter', '3.1.9')).toEqual([]);
+ });
+});
+
+describe('latestBuildVersion', () => {
+ test('picks the highest version numerically, ignoring other tags', async () => {
+ const feed = tagsFeed([
+ 'self-hosting',
+ 'v3.1.10',
+ 'v3.1.9',
+ 'v3.2.0-rc',
+ 'api',
+ 'v2.3.0',
+ ]);
+ expect(await latestBuildVersion(feed)).toBe('3.1.10');
+ });
+
+ test('fails clearly without versions or without access', async () => {
+ await expect(
+ latestBuildVersion(tagsFeed(['self-hosting']))
+ ).rejects.toThrow('No versioned builds');
+ await expect(latestBuildVersion(tagsFeed([], false))).rejects.toThrow(
+ 'HTTP 403'
+ );
+ });
+});
+
+describe('isLoggedIn', () => {
+ test.each([
+ ['auths', { auths: { 'docker.openpanel.dev': {} } }],
+ [
+ 'auths with a URL key',
+ { auths: { 'https://docker.openpanel.dev/v1/': {} } },
+ ],
+ [
+ 'a credential helper',
+ { credHelpers: { 'docker.openpanel.dev': 'desktop' } },
+ ],
+ ])('recognises %s', (_label, config) => {
+ expect(isLoggedIn(SUPPORTER_REGISTRY, dockerConfig(config))).toBe(true);
+ });
+
+ test('other registries or no config mean not logged in', () => {
+ expect(
+ isLoggedIn(SUPPORTER_REGISTRY, dockerConfig({ auths: { 'ghcr.io': {} } }))
+ ).toBe(false);
+ expect(
+ isLoggedIn(SUPPORTER_REGISTRY, join(tmpdir(), 'no-such-docker-config'))
+ ).toBe(false);
+ });
+});
diff --git a/self-hosting/get_latest_images b/self-hosting/get_latest_images
deleted file mode 100755
index 27b7f43ca..000000000
--- a/self-hosting/get_latest_images
+++ /dev/null
@@ -1,320 +0,0 @@
-#!/bin/bash
-
-# GitHub repository (update if needed)
-REPO="${GITHUB_REPO:-Openpanel-dev/openpanel}"
-
-# Components to find tags for. No "worker": v3.0.0 deleted the separate worker
-# image - op-worker runs the api image with ROLE=worker, so the "api" pass
-# below rewrites both service lines.
-COMPONENTS=("api" "dashboard")
-
-# Docker compose file path
-DOCKER_COMPOSE_FILE="${DOCKER_COMPOSE_FILE:-./docker-compose.yml}"
-
-# Color codes for output
-GREEN='\033[0;32m'
-BLUE='\033[0;34m'
-YELLOW='\033[1;33m'
-RED='\033[0;31m'
-GRAY='\033[0;90m'
-CYAN='\033[0;36m'
-NC='\033[0m' # No Color
-
-# Show usage
-show_usage() {
- echo "Usage: $0 [COMMAND] [OPTIONS]"
- echo ""
- echo "Fetches the latest Git tags for the api and dashboard components"
- echo ""
- echo "Commands:"
- echo " apply Apply the latest tags to docker-compose.yml"
- echo " (none) Show the latest tags (default)"
- echo ""
- echo "Options:"
- echo " --list, -l List all available tags"
- echo " --repo REPO Specify GitHub repository (default: $REPO)"
- echo " --file FILE Specify docker-compose file (default: $DOCKER_COMPOSE_FILE)"
- echo " --help, -h Show this help message"
- echo ""
- echo "Environment variables:"
- echo " GITHUB_REPO Set the GitHub repository"
- echo " DOCKER_COMPOSE_FILE Set the docker-compose file path"
- echo ""
- echo "Examples:"
- echo " $0 # Show latest tags"
- echo " $0 apply # Update docker-compose.yml with latest tags"
- echo " $0 --list # List all available tags"
- echo ""
- exit 0
-}
-
-# Parse arguments
-LIST_ALL=false
-APPLY_MODE=false
-while [[ $# -gt 0 ]]; do
- case $1 in
- apply)
- APPLY_MODE=true
- shift
- ;;
- --list|-l)
- LIST_ALL=true
- shift
- ;;
- --repo)
- REPO="$2"
- shift 2
- ;;
- --file)
- DOCKER_COMPOSE_FILE="$2"
- shift 2
- ;;
- --help|-h)
- show_usage
- ;;
- *)
- echo -e "${RED}Unknown option: $1${NC}"
- show_usage
- ;;
- esac
-done
-
-# Check if jq is installed (required for JSON parsing)
-if ! command -v jq &> /dev/null; then
- echo -e "${YELLOW}jq is required but not installed${NC}\n"
- echo -e "${CYAN}jq is a lightweight JSON processor needed to parse GitHub API responses.${NC}\n"
-
- # Detect OS and suggest installation
- if [[ -f /etc/os-release ]]; then
- . /etc/os-release
- OS_ID=$ID
- elif [[ "$OSTYPE" == "darwin"* ]]; then
- OS_ID="macos"
- else
- OS_ID="unknown"
- fi
-
- # Determine installation command
- case $OS_ID in
- ubuntu|debian)
- INSTALL_CMD="sudo apt-get update && sudo apt-get install -y jq"
- ;;
- rhel|centos|fedora)
- INSTALL_CMD="sudo yum install -y jq"
- ;;
- alpine)
- INSTALL_CMD="sudo apk add --no-cache jq"
- ;;
- macos)
- INSTALL_CMD="brew install jq"
- ;;
- *)
- echo -e "${RED}Could not detect your OS.${NC}"
- echo -e "${YELLOW}Please install jq manually:${NC}"
- echo -e " ${GREEN}Ubuntu/Debian:${NC} sudo apt-get update && sudo apt-get install -y jq"
- echo -e " ${GREEN}RHEL/CentOS:${NC} sudo yum install -y jq"
- echo -e " ${GREEN}Alpine:${NC} sudo apk add --no-cache jq"
- echo -e " ${GREEN}macOS:${NC} brew install jq"
- echo ""
- exit 1
- ;;
- esac
-
- # Ask user if they want to install
- read -p "$(echo -e ${GREEN}Would you like to install jq now? [Y/n]:${NC} )" -n 1 -r
- echo
- if [[ $REPLY =~ ^[Nn]$ ]]; then
- echo -e "${RED}jq is required to continue. Please install it manually.${NC}"
- exit 1
- fi
-
- # Install jq
- echo -e "${BLUE}Installing jq...${NC}\n"
- if eval "$INSTALL_CMD"; then
- echo -e "\n${GREEN}✓ jq installed successfully!${NC}\n"
- else
- echo -e "\n${RED}✗ Failed to install jq. Please install it manually.${NC}"
- exit 1
- fi
-fi
-
-# Check if user needs to be logged in (for apply mode)
-if [ "$APPLY_MODE" = true ]; then
- # Check if Docker is available
- if ! command -v docker &> /dev/null; then
- echo -e "${RED}Error: Docker is not installed or not in PATH${NC}"
- exit 1
- fi
-
- # Check if logged into docker.openpanel.dev
- echo -e "${BLUE}Checking Docker registry authentication...${NC}\n"
-
- if ! docker info 2>/dev/null | grep -q "docker.openpanel.dev" && ! grep -q "docker.openpanel.dev" ~/.docker/config.json 2>/dev/null; then
- echo -e "${YELLOW}⚠ You need to login to the OpenPanel Docker registry first!${NC}\n"
- echo -e "${CYAN}To access the latest Docker images, you need:${NC}"
- echo -e " 1. Be a supporter (starts at \$20/month)"
- echo -e " 2. Get your API key from your supporter dashboard"
- echo -e " 3. Login to the registry with:\n"
- echo -e "${GREEN} echo \"your_api_key\" | docker login docker.openpanel.dev -u user --password-stdin${NC}\n"
- echo -e "${GRAY}For more info: https://openpanel.dev/docs/self-hosting/supporter-access-latest-docker-images${NC}\n"
-
- read -p "$(echo -e ${YELLOW}Have you already logged in? [y/N]:${NC} )" -n 1 -r
- echo
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
- echo -e "${RED}Please login first and try again.${NC}"
- exit 1
- fi
- else
- echo -e "${GREEN}✓ Docker registry authentication OK${NC}\n"
- fi
-fi
-
-echo -e "${BLUE}Fetching tags from ${REPO}...${NC}\n"
-
-# Fetch all tags from GitHub API
-TAGS_JSON=$(curl -s "https://api.github.com/repos/${REPO}/tags")
-
-# Check if we got valid JSON response
-if [ -z "$TAGS_JSON" ]; then
- echo -e "${RED}Failed to fetch tags from GitHub API${NC}"
- exit 1
-fi
-
-# Check if repository has any tags
-TAGS_CLEAN=$(echo "$TAGS_JSON" | tr -d '[:space:]')
-if [ "$TAGS_CLEAN" == "[]" ]; then
- echo -e "${RED}No tags found in repository${NC}"
- echo -e "${YELLOW}Create tags using: git tag <tag-name> && git push origin <tag-name>${NC}"
- echo ""
- echo -e "${GRAY}Example tag naming patterns:${NC}"
- echo -e " ${GRAY}- api-v1.0.0${NC}"
- echo -e " ${GRAY}- dashboard-v1.0.0${NC}"
- exit 1
-fi
-
-# List all tags if requested
-if [ "$LIST_ALL" = true ]; then
- echo -e "${GREEN}All available tags:${NC}\n"
- echo "$TAGS_JSON" | jq -r '.[] | " \(.name) (\(.commit.sha[0:7]))"'
- echo ""
- exit 0
-fi
-
-# Function to find latest tag matching a component
-get_latest_tag() {
- local component=$1
- local output_var_tag=$2
- local output_var_sha=$3
-
- # Use jq for JSON parsing
- local tag=$(echo "$TAGS_JSON" | jq -r "[.[] | select(.name | contains(\"${component}\"))] | .[0] | .name" 2>/dev/null)
- local sha=$(echo "$TAGS_JSON" | jq -r "[.[] | select(.name | contains(\"${component}\"))] | .[0] | .commit.sha" 2>/dev/null)
-
- if [ -z "$tag" ] || [ "$tag" == "null" ]; then
- echo -e "${RED}✗${NC} ${component}: No matching tag found"
- echo
- return 1
- fi
-
- echo -e "${GREEN}✓${NC} ${component}:"
- echo -e " Tag: ${YELLOW}${tag}${NC}"
- echo -e " SHA: ${sha}"
- echo
-
- # Return values via eval (for compatibility with older bash)
- if [ -n "$output_var_tag" ]; then
- eval "$output_var_tag='$tag'"
- fi
- if [ -n "$output_var_sha" ]; then
- eval "$output_var_sha='$sha'"
- fi
-
- return 0
-}
-
-# Function to apply tags to docker-compose.yml
-apply_tags() {
- echo -e "${CYAN}Applying tags to ${DOCKER_COMPOSE_FILE}...${NC}\n"
-
- # Check if docker-compose file exists
- if [ ! -f "$DOCKER_COMPOSE_FILE" ]; then
- echo -e "${RED}Error: Docker compose file not found: ${DOCKER_COMPOSE_FILE}${NC}"
- exit 1
- fi
-
- # Create a backup
- local backup_file="${DOCKER_COMPOSE_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
- cp "$DOCKER_COMPOSE_FILE" "$backup_file"
- echo -e "${GRAY}Created backup: ${backup_file}${NC}\n"
-
- local updated=0
- local failed=0
-
- for component in "${COMPONENTS[@]}"; do
- # Get tag and SHA for this component
- local component_tag=""
- local component_sha=""
- get_latest_tag "$component" component_tag component_sha >/dev/null 2>&1
-
- if [ -z "$component_sha" ] || [ "$component_sha" == "null" ]; then
- echo -e "${RED}✗${NC} ${component}: Skipping (no tag found)"
- ((failed++))
- continue
- fi
-
- # Get first 4 characters of SHA
- local short_sha="${component_sha:0:4}"
-
- # New image tag format
- local new_image="docker.openpanel.dev/openpanel-dev/${component}:main-${short_sha}"
-
- # Find and replace the image line in docker-compose.yml
- # Look for lines like: image: something{component}something
- if grep -q "image:.*${component}" "$DOCKER_COMPOSE_FILE"; then
- # Use sed to replace the entire image line
- if [[ "$OSTYPE" == "darwin"* ]]; then
- # macOS sed syntax
- sed -i '' "s|image:.*${component}.*|image: ${new_image}|g" "$DOCKER_COMPOSE_FILE"
- else
- # Linux sed syntax
- sed -i "s|image:.*${component}.*|image: ${new_image}|g" "$DOCKER_COMPOSE_FILE"
- fi
- echo -e "${GREEN}✓${NC} Updated ${component}: ${CYAN}${new_image}${NC}"
- ((updated++))
- else
- echo -e "${YELLOW}⚠${NC} ${component}: No matching image line found in docker-compose.yml"
- ((failed++))
- fi
- done
-
- echo ""
- echo -e "${BLUE}Summary:${NC}"
- echo -e " Updated: ${GREEN}${updated}${NC}"
- echo -e " Failed: ${RED}${failed}${NC}"
- echo -e " Backup: ${GRAY}${backup_file}${NC}"
- echo ""
-
- if [ $updated -gt 0 ]; then
- echo -e "${GREEN}Successfully updated docker-compose.yml!${NC}"
- fi
-}
-
-# Main execution
-if [ "$APPLY_MODE" = true ]; then
- # Apply mode: update docker-compose.yml
- # First, show all tags
- for component in "${COMPONENTS[@]}"; do
- get_latest_tag "$component"
- done
-
- # Then apply them
- apply_tags
-else
- # Default mode: just show the tags
- for component in "${COMPONENTS[@]}"; do
- get_latest_tag "$component"
- done
-
- echo -e "${GRAY}Tip: Use --list to see all available tags, or 'apply' to update docker-compose.yml${NC}"
- echo -e "${BLUE}Done!${NC}"
-fi