diff --git a/Dockerfile b/Dockerfile index f6580a9..f91546c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,6 +25,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 # Optional legacy PVE stub plane only (ENABLE_PVE_STUB=true). Native vSphere # contracts live under contracts/vsphere/ and app/vsphere/. diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..28ff78c --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,201 @@ +// VMware 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://vmware.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/vmware-api-simulator' + DOCKERHUB_IMAGE = 'inecs/vmware-api-simulator' + BUILDX_BUILDER = "jenkins-vmware-api-simulator-${env.BUILD_NUMBER}" + HELM_NAMESPACE = 'simulators' + DEPLOYMENT_NAME = 'simulators-vmware' + INGRESS_HOST = 'vmware.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 || true + + 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}/" + + # One set-image avoids double ReplicaSet churn; migrate when present. + SET_ARGS=("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 + SET_ARGS+=("migrate=${DOCKERHUB_IMAGE}:${IMAGE_VERSION}") + fi + kubectl -n "$HELM_NAMESPACE" set image \ + "deployment/${DEPLOYMENT_NAME}" "${SET_ARGS[@]}" + + kubectl -n "$HELM_NAMESPACE" rollout status \ + "deployment/${DEPLOYMENT_NAME}" --timeout=1200s + 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 69b99e6..4b0a9cc 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ PYTEST_OFFLINE := -m "not integration and not compatibility and not pve_stub" # Docker Hub release image (runtime target only — not the local bind-mount "dev" image). DOCKERHUB_USER ?= inecs IMAGE_NAME ?= vmware-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 @@ -20,11 +20,13 @@ LOCAL_HTTP_PORT ?= 18080 LOCAL_HTTPS_PORT ?= 18443 LOCAL_POSTGRES_PORT ?= 15434 -.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 push release release-build release-up release-down release-seed helm-deps helm-template \ +.PHONY: bump-patch bump-minor version-commit 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 push release release-build release-up release-down release-seed helm-deps helm-template \ pulumi-tests pulumi-tests-smoke test-pulumi-smoke test-pulumi test-smoke-all test-all clean-test-resources vsphere-universe vsphere-param-index vsphere-bundles vsphere-seed-dump 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 @@ -240,23 +242,41 @@ seed: ## Seed simulation data (vSphere; PROFILE= / VSPHERE_PROFILE=small|large|b shell: ## Open an interactive shell in the development container $(COMPOSE) run --rm --no-deps $(SERVICE_DEV) bash -push: ## git add ., multiline commit message (Ctrl-D), push to both remotes +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/vmware-api-simulator/Chart.yaml helm/vmware-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 + @$(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"; \ fi; \ - echo "Pushing to both remotes via origin..."; \ - git remote get-url --push --all origin 2>/dev/null | sed 's/^/ - /' || true; \ - git push -u origin HEAD + echo "Pushing to both remotes:"; \ + git remote get-url --push --all origin | sed 's/^/ - /'; \ + git push origin HEAD clean: ## Remove generated local artifacts rm -rf .coverage coverage.xml htmlcov .mypy_cache .pytest_cache .ruff_cache 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 220f8d9..4a172d4 100644 --- a/app/main.py +++ b/app/main.py @@ -30,6 +30,7 @@ from app.tasks.repository import TaskRepository from app.tasks.worker import TaskWorker from app.vsphere.rest import vsphere_rest_router from app.vsphere.soap.router import router as vsphere_soap_router +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(include_pve=pve_stub), 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..714cd85 --- /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" / "vmware-api-simulator" / "Chart.yaml" +_VALUES_FILE = _PROJECT_ROOT / "helm" / "vmware-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("vmware-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 cf1e726..7a05ac9 100644 --- a/app/web/contract_catalog.py +++ b/app/web/contract_catalog.py @@ -122,8 +122,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 8e99887..00634dc 100644 --- a/app/web/index.html +++ b/app/web/index.html @@ -795,7 +795,12 @@ stroke: none; } + .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 +814,22 @@ 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; @@ -3971,6 +3992,7 @@ major: 9, majors: [], runtimeVersion: null, + appVersion: null, catalog: null, method: null, pathValues: {}, @@ -6023,6 +6045,7 @@ function buildAboutHtml() { const version = state.runtimeVersion || "—"; const catalogMajor = state.major || "—"; + const appVersion = state.appVersion ? `v${state.appVersion}` : "v—"; return `