diff --git a/Dockerfile b/Dockerfile index fc7838b..8a44c06 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,6 +27,7 @@ ENV PATH="/opt/venv/bin:$PATH" \ RUN groupadd --system --gid 10001 simulator \ && useradd --system --uid 10001 --gid simulator --home-dir /app --no-create-home simulator COPY --from=builder /opt/venv /opt/venv +COPY VERSION /app/VERSION COPY contracts/e61a893e996d05d376579226e7dfbedbcfce8b71787adacffbc557e6e35901c1/snapshot.json /app/contracts/pve-9.2.3.json COPY evidence/ /app/evidence/ WORKDIR /app diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..01b6511 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,203 @@ +// Proxmox API Simulator — CI/CD: multi-arch push (Harbor + Docker Hub) + deploy +// +// Один файл: Build (DinD) → Deploy (kubectl set image в релиз simulators). +// Первый install lab — через DevOpsTools/K3S: make addon-simulators +// (Ingress https://proxmox.devops.org.ru уже из addon values). +// +// Версия образа = VERSION из коммита. Локальный bump: make bump-patch / make push. +// Теги: :{VERSION} и :latest (без sha). +// +// Credentials (Global): +// harbor-devops-tools-push-pull-access — Harbor devops-tools (robot) +// docker-hub — Docker Hub (inecs) +// k3s-kubeconfig — kubeconfig к K3S +// ssh-gitea-key — SCM checkout Gitea (в job) + +pipeline { + agent none + + options { + buildDiscarder(logRotator(numToKeepStr: '20')) + disableConcurrentBuilds() + timeout(time: 60, unit: 'MINUTES') + timestamps() + } + + environment { + HARBOR_REGISTRY = 'hub.antropoff.ru' + HARBOR_IMAGE = 'hub.antropoff.ru/devops-tools/proxmox-api-simulator' + DOCKERHUB_IMAGE = 'inecs/proxmox-api-simulator' + BUILDX_BUILDER = "jenkins-proxmox-api-simulator-${env.BUILD_NUMBER}" + HELM_NAMESPACE = 'simulators' + DEPLOYMENT_NAME = 'simulators-proxmox' + INGRESS_HOST = 'proxmox.devops.org.ru' + TZ = 'Europe/Moscow' + } + + stages { + stage('Build & push') { + when { + anyOf { + branch 'main' + branch 'master' + } + } + agent { label 'docker' } + stages { + stage('Checkout') { + steps { + checkout scm + } + } + + stage('Version') { + steps { + script { + env.IMAGE_VERSION = readFile('VERSION').trim() + if (!env.IMAGE_VERSION) { + error('VERSION file is empty') + } + echo "IMAGE_VERSION from VERSION → ${env.IMAGE_VERSION}" + } + } + } + + stage('Buildx push') { + steps { + withCredentials([ + usernamePassword( + credentialsId: 'harbor-devops-tools-push-pull-access', + usernameVariable: 'HARBOR_USER', + passwordVariable: 'HARBOR_PASS' + ), + usernamePassword( + credentialsId: 'docker-hub', + usernameVariable: 'DOCKERHUB_USER', + passwordVariable: 'DOCKERHUB_PASS' + ) + ]) { + container('docker') { + sh ''' + set -eux + + test -n "${IMAGE_VERSION}" + echo "Building tags: ${IMAGE_VERSION}, latest (amd64+arm64)" + + echo "$HARBOR_PASS" | docker login "$HARBOR_REGISTRY" -u "$HARBOR_USER" --password-stdin + echo "$DOCKERHUB_PASS" | docker login -u "$DOCKERHUB_USER" --password-stdin + + docker buildx rm "$BUILDX_BUILDER" 2>/dev/null || true + docker buildx create --name "$BUILDX_BUILDER" --driver docker-container --use + docker buildx inspect --bootstrap >/dev/null + + docker buildx build \ + --platform linux/amd64,linux/arm64 \ + --target runtime \ + --build-arg "APP_VERSION=${IMAGE_VERSION}" \ + --provenance=false --sbom=false --push \ + -t "${HARBOR_IMAGE}:${IMAGE_VERSION}" \ + -t "${HARBOR_IMAGE}:latest" \ + -t "${DOCKERHUB_IMAGE}:${IMAGE_VERSION}" \ + -t "${DOCKERHUB_IMAGE}:latest" \ + -f Dockerfile . + + echo "--- Harbor ---" + docker buildx imagetools inspect "${HARBOR_IMAGE}:${IMAGE_VERSION}" | sed -n '1,40p' + echo "--- Docker Hub ---" + docker buildx imagetools inspect "${DOCKERHUB_IMAGE}:${IMAGE_VERSION}" | sed -n '1,40p' + + docker buildx rm "$BUILDX_BUILDER" || true + ''' + } + } + } + } + + stage('Deploy') { + steps { + withCredentials([ + file(credentialsId: 'k3s-kubeconfig', variable: 'KUBECONFIG') + ]) { + container('docker') { + sh ''' + set -eux + + if ! command -v kubectl >/dev/null 2>&1; then + apk add --no-cache curl >/dev/null + ARCH="$(uname -m)" + case "$ARCH" in + x86_64) ARCH=amd64 ;; + aarch64|arm64) ARCH=arm64 ;; + esac + KVER="$(curl -fsSL https://dl.k8s.io/release/stable.txt)" + curl -fsSLo /usr/local/bin/kubectl \ + "https://dl.k8s.io/release/${KVER}/bin/linux/${ARCH}/kubectl" + chmod +x /usr/local/bin/kubectl + fi + + kubectl version --client --short || kubectl version --client + + if ! kubectl -n "$HELM_NAMESPACE" get deploy "$DEPLOYMENT_NAME" >/dev/null 2>&1; then + echo "Deployment ${HELM_NAMESPACE}/${DEPLOYMENT_NAME} not found." >&2 + echo "Сначала: make addon-simulators (Ingress ${INGRESS_HOST})." >&2 + exit 1 + fi + + echo "Rolling ${DOCKERHUB_IMAGE}:${IMAGE_VERSION} → ${HELM_NAMESPACE}/${DEPLOYMENT_NAME}" + echo "Public URL: https://${INGRESS_HOST}/" + + # Main container always; migrate initContainer when present. + kubectl -n "$HELM_NAMESPACE" set image \ + "deployment/${DEPLOYMENT_NAME}" \ + "simulator=${DOCKERHUB_IMAGE}:${IMAGE_VERSION}" + if kubectl -n "$HELM_NAMESPACE" get deploy "$DEPLOYMENT_NAME" \ + -o jsonpath='{.spec.template.spec.initContainers[*].name}' \ + | tr ' ' '\n' | grep -qx migrate; then + kubectl -n "$HELM_NAMESPACE" set image \ + "deployment/${DEPLOYMENT_NAME}" \ + "migrate=${DOCKERHUB_IMAGE}:${IMAGE_VERSION}" + fi + + kubectl -n "$HELM_NAMESPACE" rollout status \ + "deployment/${DEPLOYMENT_NAME}" --timeout=300s + kubectl -n "$HELM_NAMESPACE" get deploy,po,ing -o wide + ''' + } + } + } + } + } + post { + always { + script { + try { + container('docker') { + sh 'docker buildx rm "$BUILDX_BUILDER" 2>/dev/null || true' + } + } catch (Ignored) { + // pod may already be gone + } + } + } + success { + echo "✓ ${DOCKERHUB_IMAGE}:{${IMAGE_VERSION},latest} → https://${INGRESS_HOST}/" + } + failure { + echo "✗ Build/push/deploy failed — см. лог" + } + } + } + } + + post { + success { + echo "✓ Version: ${IMAGE_VERSION}" + echo "✓ Harbor: ${HARBOR_IMAGE}:{${IMAGE_VERSION},latest}" + echo "✓ Hub: ${DOCKERHUB_IMAGE}:{${IMAGE_VERSION},latest}" + echo "✓ Live: https://${INGRESS_HOST}/" + } + failure { + echo "✗ Pipeline failed" + } + } +} diff --git a/Makefile b/Makefile index 7c14cf8..7f2e66a 100644 --- a/Makefile +++ b/Makefile @@ -4,19 +4,22 @@ SERVICE_SIM := simulator PYTEST_OFFLINE := -m "not integration and not compatibility" # Docker Hub release image (runtime target only — not the local bind-mount "dev" image). +# SemVer source of truth: VERSION (synced to pyproject + Helm via bump targets). DOCKERHUB_USER ?= inecs IMAGE_NAME ?= proxmox-api-simulator -VERSION ?= $(shell sed -n 's/^version = "\(.*\)"/\1/p' pyproject.toml) +VERSION ?= $(shell cat VERSION 2>/dev/null || echo 0.1.0) DOCKER_IMAGE ?= $(DOCKERHUB_USER)/$(IMAGE_NAME) PUSH_LATEST ?= 1 COMPOSE_RELEASE ?= $(COMPOSE) -f docker-compose.release.yml HELM_CHART ?= ./helm/proxmox-api-simulator -.PHONY: help install format lint typecheck test test-unit test-integration test-contract test-compatibility test-surface evidence coverage run dev up up-local down down-local restart logs docker-build docker-up docker-down docker-logs docker-restart db-up db-down db-migrate db-reset api-import api-diff seed clean ci ci-all shell release release-build release-up release-down release-seed helm-deps helm-template helm-lint pulumi-tests push +.PHONY: help install format lint typecheck test test-unit test-integration test-contract test-compatibility test-surface evidence coverage run dev up up-local down down-local restart logs docker-build docker-up docker-down docker-logs docker-restart db-up db-down db-migrate db-reset api-import api-diff seed clean ci ci-all shell release release-build release-up release-down release-seed helm-deps helm-template helm-lint pulumi-tests push bump-patch bump-minor version-commit help: ## Show available commands @awk 'BEGIN {FS = ":.*## "}; /^[a-zA-Z0-9_-]+:.*## / {printf "%-22s %s\n", $$1, $$2}' $(MAKEFILE_LIST) + @echo + @echo "Version: $$(cat VERSION 2>/dev/null || echo 0.1.0) (make bump-patch | bump-minor)" install: ## Build runtime and development images @test -f .env || cp .env.example .env @@ -213,16 +216,34 @@ pulumi-tests: ## Full Pulumi suite (surface majors 6–9 + lifecycle, HTML repor $(MAKE) -C pulumi-tests up $(MAKE) -C pulumi-tests test -push: ## git add ., prompt for commit message, push origin (GitHub + antropoff.ru) +bump-patch: ## VERSION +0.0.1 (pyproject + Helm) + @PYTHONPATH=. python3 scripts/bump_version.py patch + @echo "VERSION → $$(cat VERSION)" + +bump-minor: ## VERSION +0.1.0 (pyproject + Helm) + @PYTHONPATH=. python3 scripts/bump_version.py minor + @echo "VERSION → $$(cat VERSION)" + +version-commit: ## Stage version files and commit "Bump version to …" + @git add VERSION pyproject.toml helm/proxmox-api-simulator/Chart.yaml helm/proxmox-api-simulator/values.yaml + @if git diff --cached --quiet; then \ + echo "Nothing to commit for version files."; \ + else \ + git commit -m "Bump version to $$(cat VERSION)."; \ + fi + +push: ## bump-patch + commit version + push origin (GitHub + antropoff.ru) + @$(MAKE) bump-patch + @$(MAKE) version-commit @set -e; \ git add .; \ echo "=== staged ==="; \ git status --short; \ echo; \ if git diff --cached --quiet; then \ - echo "Nothing to commit — pushing current branch."; \ + echo "Nothing else to commit — pushing current branch."; \ else \ - echo "Enter commit message, then Ctrl-D:"; \ + echo "Enter commit message for remaining changes, then Ctrl-D:"; \ msg=$$(cat &2; exit 1; fi; \ git commit -m "$$msg"; \ diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..17e51c3 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.1 diff --git a/app/main.py b/app/main.py index b5b1b4d..3d27a63 100644 --- a/app/main.py +++ b/app/main.py @@ -25,6 +25,7 @@ from app.tasks.lxc import lxc_handler from app.tasks.qemu import qemu_handler from app.tasks.repository import TaskRepository from app.tasks.worker import TaskWorker +from app.version import get_app_version from app.web.routes import router as web_router @@ -117,7 +118,7 @@ def create_app( resolved_workers = (task_worker,) app = FastAPI( title=resolved.app_name, - version="0.1.0", + version=get_app_version(), openapi_tags=openapi_tag_metadata(), lifespan=create_lifespan(resolved, database_factory, resolved_workers or ()), ) diff --git a/app/version.py b/app/version.py new file mode 100644 index 0000000..bfed7b0 --- /dev/null +++ b/app/version.py @@ -0,0 +1,130 @@ +"""SemVer source of truth: VERSION file (synced to pyproject + Helm).""" + +from __future__ import annotations + +import re +from functools import lru_cache +from pathlib import Path + +_VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION" +_PROJECT_ROOT = _VERSION_FILE.parent +_PYPROJECT_FILE = _PROJECT_ROOT / "pyproject.toml" +_CHART_FILE = _PROJECT_ROOT / "helm" / "proxmox-api-simulator" / "Chart.yaml" +_VALUES_FILE = _PROJECT_ROOT / "helm" / "proxmox-api-simulator" / "values.yaml" +_DEFAULT_VERSION = "0.1.0" +_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)$") + + +def _read_version_file(path: Path) -> str | None: + try: + text = path.read_text(encoding="utf-8").strip() + except OSError: + return None + if _VERSION_RE.match(text): + return text + return None + + +@lru_cache +def get_app_version() -> str: + for path in ( + Path("/app/VERSION"), + _VERSION_FILE, + Path.cwd() / "VERSION", + ): + found = _read_version_file(path) + if found: + return found + try: + from importlib.metadata import version + + meta = version("proxmox-api-simulator") + if _VERSION_RE.match(meta): + return meta + except Exception: + pass + return _DEFAULT_VERSION + + +def get_app_version_label() -> str: + clear_version_cache() + return f"v{get_app_version()}" + + +def parse_version(value: str) -> tuple[int, int, int]: + match = _VERSION_RE.match(value.strip()) + if not match: + raise ValueError(f"Invalid semantic version: {value!r}") + return int(match.group(1)), int(match.group(2)), int(match.group(3)) + + +def format_version(major: int, minor: int, patch: int) -> str: + return f"{major}.{minor}.{patch}" + + +def clear_version_cache() -> None: + get_app_version.cache_clear() + + +def write_project_version(version: str) -> None: + parse_version(version) + _VERSION_FILE.write_text(f"{version}\n", encoding="utf-8") + + pyproject = _PYPROJECT_FILE.read_text(encoding="utf-8") + pyproject, count = re.subn( + r'^version = ".*"$', + f'version = "{version}"', + pyproject, + count=1, + flags=re.MULTILINE, + ) + if count != 1: + raise RuntimeError("Failed to update pyproject.toml version") + _PYPROJECT_FILE.write_text(pyproject, encoding="utf-8") + + chart = _CHART_FILE.read_text(encoding="utf-8") + chart, chart_count = re.subn( + r"^version: .*$", + f"version: {version}", + chart, + count=1, + flags=re.MULTILINE, + ) + chart, app_count = re.subn( + r'^appVersion: ".*"$', + f'appVersion: "{version}"', + chart, + count=1, + flags=re.MULTILINE, + ) + if chart_count != 1 or app_count != 1: + raise RuntimeError("Failed to update Chart.yaml version") + _CHART_FILE.write_text(chart, encoding="utf-8") + + values = _VALUES_FILE.read_text(encoding="utf-8") + values, values_count = re.subn( + r'^(\s*tag:\s*).*$', + rf'\1"{version}"', + values, + count=1, + flags=re.MULTILINE, + ) + if values_count != 1: + raise RuntimeError("Failed to update helm values.yaml image.tag") + _VALUES_FILE.write_text(values, encoding="utf-8") + + clear_version_cache() + + +def bump_patch_version() -> str: + major, minor, patch = parse_version(get_app_version()) + version = format_version(major, minor, patch + 1) + write_project_version(version) + return version + + +def bump_minor_version() -> str: + major, minor, patch = parse_version(get_app_version()) + version = format_version(major, minor + 1, 0) + write_project_version(version) + return version diff --git a/app/web/contract_catalog.py b/app/web/contract_catalog.py index 6784833..38e3250 100644 --- a/app/web/contract_catalog.py +++ b/app/web/contract_catalog.py @@ -102,8 +102,10 @@ def list_majors( *, runtime_version: str | None, settings: Settings | None = None, + app_version: str | None = None, ) -> dict[str, object]: return { + "app_version": app_version, "runtime_version": runtime_version, "majors": [ { diff --git a/app/web/index.html b/app/web/index.html index b273fda..5ad57d8 100644 --- a/app/web/index.html +++ b/app/web/index.html @@ -796,6 +796,10 @@ } .help-about-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.45rem 0.65rem; margin: 0; padding: 0 14px 12px; font-size: 11px; @@ -809,6 +813,21 @@ color: var(--text); } + .help-about-version { + flex-shrink: 0; + padding: 0.22rem 0.55rem; + border-radius: 999px; + border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent); + background: color-mix(in srgb, var(--accent) 14%, transparent); + color: var(--accent); + font-family: var(--mono); + font-size: 10px; + font-weight: 600; + letter-spacing: 0.03em; + line-height: 1; + white-space: nowrap; + } + .help-panel { flex: 1; min-height: 0; @@ -3932,6 +3951,7 @@ major: 9, majors: [], runtimeVersion: null, + appVersion: null, catalog: null, method: null, pathValues: {}, @@ -5797,6 +5817,7 @@ function buildAboutHtml() { const version = state.runtimeVersion || "—"; const catalogMajor = state.major || "—"; + const appVersion = state.appVersion ? `v${state.appVersion}` : "v—"; return `