diff --git a/.devcontainer/demo-container/devcontainer.json b/.devcontainer/demo-container/devcontainer.json index e5af37c68a..e3e54dbb42 100644 --- a/.devcontainer/demo-container/devcontainer.json +++ b/.devcontainer/demo-container/devcontainer.json @@ -5,43 +5,48 @@ "context": ".." }, "customizations": { - "settings": { - "python.pythonPath": "/workspace/infrahub/.venv/bin/python", - "terminal.integrated.shell.linux": "/bin/bash", - "python.venvPath": "/workspace/infrahub/.venv", - "python.linting.enabled": true - }, - "vscode": { + "settings": { + "python.pythonPath": "/workspace/infrahub/.venv/bin/python", + "terminal.integrated.shell.linux": "/bin/bash", + "python.venvPath": "/workspace/infrahub/.venv", + "python.linting.enabled": true + }, + "vscode": { "extensions": [ - "pomdtr.excalidraw-editor", - "wholroyd.jinja", - "ms-python.vscode-pylance", - "shardulm94.trailing-spaces", - "nickmillerdev.pytest-fixtures", - "yzhang.markdown-all-in-one", - "GraphQL.vscode-graphql-syntax", - "MS-vsliveshare.vsliveshare" + "pomdtr.excalidraw-editor", + "wholroyd.jinja", + "ms-python.vscode-pylance", + "shardulm94.trailing-spaces", + "nickmillerdev.pytest-fixtures", + "yzhang.markdown-all-in-one", + "GraphQL.vscode-graphql-syntax", + "MS-vsliveshare.vsliveshare" ] - } + } }, "remoteUser": "vscode", "remoteEnv": { - "INFRAHUB_SDK_API_TOKEN": "06438eb2-8019-4776-878c-0941b1f1d1ec", - "INFRAHUB_DB_TYPE": "neo4j", - "INFRAHUB_IMAGE_VER": "local" + "INFRAHUB_API_TOKEN": "06438eb2-8019-4776-878c-0941b1f1d1ec", + "INFRAHUB_DB_TYPE": "neo4j", + "INFRAHUB_IMAGE_VER": "local" }, - "forwardPorts": [8000], - "runArgs": ["--volume=/var/lib/docker", "--privileged"], + "forwardPorts": [ + 8000 + ], + "runArgs": [ + "--volume=/var/lib/docker", + "--privileged" + ], "onCreateCommand": "./.devcontainer/onCreateCommand.sh", "postCreateCommand": "./.devcontainer/postCreateCommand.sh", "postStartCommand": "./.devcontainer/postStartCommand.sh", "postAttachCommand": "./.devcontainer/postAttachCommand.sh", "features": { - "docker-in-docker": "latest", - "github-cli": "latest" + "docker-in-docker": "latest", + "github-cli": "latest" }, "hostRequirements": { - "cpus": 8, - "memory": "16gb" + "cpus": 8, + "memory": "16gb" } -} +} \ No newline at end of file diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index f99c082640..af23e381f1 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,46 +1,51 @@ { - "name": "infrahub", - "build": { - "dockerfile": "./Dockerfile", - "context": "." + "name": "infrahub", + "build": { + "dockerfile": "./Dockerfile", + "context": "." + }, + "customizations": { + "settings": { + "python.pythonPath": "/workspace/infrahub/.venv/bin/python", + "terminal.integrated.shell.linux": "/bin/bash", + "python.venvPath": "/workspace/infrahub/.venv", + "python.linting.enabled": true }, - "customizations": { - "settings": { - "python.pythonPath": "/workspace/infrahub/.venv/bin/python", - "terminal.integrated.shell.linux": "/bin/bash", - "python.venvPath": "/workspace/infrahub/.venv", - "python.linting.enabled": true - }, - "vscode": { - "extensions": [ - "pomdtr.excalidraw-editor", - "wholroyd.jinja", - "ms-python.vscode-pylance", - "shardulm94.trailing-spaces", - "nickmillerdev.pytest-fixtures", - "yzhang.markdown-all-in-one", - "GraphQL.vscode-graphql-syntax", - "MS-vsliveshare.vsliveshare" - ] - } - }, - "remoteUser": "vscode", - "remoteEnv": { - "INFRAHUB_SDK_API_TOKEN": "06438eb2-8019-4776-878c-0941b1f1d1ec", - "INFRAHUB_DB_TYPE": "neo4j", - "INFRAHUB_IMAGE_VER": "local" - }, - "forwardPorts": [8000], - "runArgs": ["--volume=/var/lib/docker", "--privileged"], - "onCreateCommand": "./.devcontainer/onCreateCommand.sh", - "postCreateCommand": "./.devcontainer/postCreateCommand.sh", - "postAttachCommand": "./.devcontainer/postAttachCommand.sh", - "features": { - "docker-in-docker": "latest", - "github-cli": "latest" - }, - "hostRequirements": { - "cpus": 8, - "memory": "16gb" + "vscode": { + "extensions": [ + "pomdtr.excalidraw-editor", + "wholroyd.jinja", + "ms-python.vscode-pylance", + "shardulm94.trailing-spaces", + "nickmillerdev.pytest-fixtures", + "yzhang.markdown-all-in-one", + "GraphQL.vscode-graphql-syntax", + "MS-vsliveshare.vsliveshare" + ] } -} + }, + "remoteUser": "vscode", + "remoteEnv": { + "INFRAHUB_API_TOKEN": "06438eb2-8019-4776-878c-0941b1f1d1ec", + "INFRAHUB_DB_TYPE": "neo4j", + "INFRAHUB_IMAGE_VER": "local" + }, + "forwardPorts": [ + 8000 + ], + "runArgs": [ + "--volume=/var/lib/docker", + "--privileged" + ], + "onCreateCommand": "./.devcontainer/onCreateCommand.sh", + "postCreateCommand": "./.devcontainer/postCreateCommand.sh", + "postAttachCommand": "./.devcontainer/postAttachCommand.sh", + "features": { + "docker-in-docker": "latest", + "github-cli": "latest" + }, + "hostRequirements": { + "cpus": 8, + "memory": "16gb" + } +} \ No newline at end of file diff --git a/.devcontainer/welcome b/.devcontainer/welcome index c992fa769a..219f04c576 100644 --- a/.devcontainer/welcome +++ b/.devcontainer/welcome @@ -3,7 +3,7 @@ 👋👋👋 Welcome to the Infrahub Demo Codespace environment 👋👋👋 -The Infrahub API server, git agents and dependent services have been +The Infrahub API server, Git agents and dependent services have been started. Infrahub can be accessed by opening the ports tab, clicking on the globe icon in the Forwarded Address column of port 8000. diff --git a/.github/file-filters.yml b/.github/file-filters.yml index d89a44ec82..f5a96c6944 100644 --- a/.github/file-filters.yml +++ b/.github/file-filters.yml @@ -3,6 +3,9 @@ ci_config: &ci_config - ".github/workflows/ci.yml" - ".github/file-filters.yml" +github_workflows: &github_workflows + - ".github/workflows/*.yml" + development_files: &development_files - "development/**" - "tasks/**" @@ -31,6 +34,9 @@ sync_poetry_files: &sync_poetry_files frontend_files: &frontend_files - "frontend/**" +e2e_test_files: + - "frontend/tests/e2e/**" + demo_files: &demo_files - "models/**" diff --git a/.github/infrahub-release-drafter.yml b/.github/infrahub-release-drafter.yml index 42b45b7466..4495e43295 100644 --- a/.github/infrahub-release-drafter.yml +++ b/.github/infrahub-release-drafter.yml @@ -16,6 +16,7 @@ include-labels: - 'group/ci' - 'group/frontend' - 'type/documentation' +include-pre-releases: true change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks. tag-prefix: infrahub-v tag-template: infrahub-v diff --git a/.github/labels.yml b/.github/labels.yml index 8d44c34baf..b7f527fe0b 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -32,6 +32,14 @@ description: "Issue related to the CI pipeline" color: "f25009" +- name: "group/helm" + description: "Issue related to the Helm chart" + color: "326ce5" + +- name: "group/schema" + description: "Issue related to some schemas" + color: "fbceb1" + # ---------------------------------- # TYPE INFRAHUB (default) # ---------------------------------- @@ -47,6 +55,9 @@ description: "Maintenance task" color: "fef2c0" +- name: "type/tech-debt" + description: "Item we know we need to improve way it is implemented" + color: "73FA20" # ---------------------------------- # TYPE ALL # ---------------------------------- diff --git a/.github/python_sdk-release-drafter.yml b/.github/python_sdk-release-drafter.yml index b6379800b2..abfd6a6c14 100644 --- a/.github/python_sdk-release-drafter.yml +++ b/.github/python_sdk-release-drafter.yml @@ -14,6 +14,7 @@ exclude-labels: - 'ci/skip-changelog' include-labels: - 'group/python-sdk' +include-pre-releases: true change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks. tag-prefix: python-sdk-v tag-template: python-sdk-v diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc20b63418..a44db384de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ env: INFRAHUB_TEST_IN_DOCKER: 1 VALE_VERSION: "3.0.7" GITHUB_PR_NUMBER: ${{ github.event.pull_request.number }} + METRICS_ENDPOINT: ${{ secrets.METRICS_ENDPOINT }} jobs: # ------------------------------------------ Check Files Changes ------------------------------------------ @@ -44,9 +45,11 @@ jobs: python: ${{ steps.changes.outputs.python_all }} javascript: ${{ steps.changes.outputs.javascript_all }} yaml: ${{ steps.changes.outputs.yaml_all }} - infrahub_poetry_files: ${{ steps.changes.ouputs.infrahub_poetry_files }} - python_sdk_poetry_files: ${{ steps.changes.ouputs.python_sdk_poetry_files }} - sync_poetry_files: ${{ steps.changes.ouputs.sync_poetry_files }} + infrahub_poetry_files: ${{ steps.changes.outputs.infrahub_poetry_files }} + python_sdk_poetry_files: ${{ steps.changes.outputs.python_sdk_poetry_files }} + sync_poetry_files: ${{ steps.changes.outputs.sync_poetry_files }} + github_workflows: ${{ steps.changes.outputs.github_workflows }} + e2e_tests: ${{ steps.changes.outputs.e2e_test_files }} steps: - name: "Check out repository code" uses: "actions/checkout@v4" @@ -114,7 +117,7 @@ jobs: - name: "Check out repository code" uses: "actions/checkout@v4" - name: "Setup environment" - run: "pip install ruff==0.4.1" + run: "pip install ruff==0.4.3" - name: "Linting: ruff check" run: "ruff check --diff ." - name: "Linting: ruff format" @@ -134,6 +137,22 @@ jobs: config: .markdownlint.yaml globs: '**/*.{md,mdx}' + action-lint: + if: needs.files-changed.outputs.github_workflows == 'true' + needs: ["files-changed"] + runs-on: "ubuntu-latest" + timeout-minutes: 5 + steps: + - name: "Check out repository code" + uses: "actions/checkout@v4" + - name: Check workflow files + run: | + bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash) + ./actionlint -color + shell: bash + env: + SHELLCHECK_OPTS: --exclude=SC2086 --exclude=SC2046 --exclude=SC2004 + infrahub-poetry-check: if: | needs.files-changed.outputs.infrahub_poetry_files == 'true' || @@ -402,8 +421,24 @@ jobs: runs-on: group: huge-runners timeout-minutes: 45 - env: - INFRAHUB_DB_TYPE: neo4j + strategy: + fail-fast: false + matrix: + include: + - name: backend-tests-neo4j + env: + INFRAHUB_DB_TYPE: neo4j + - name: backend-tests-nats + env: + INFRAHUB_DB_TYPE: memgraph + INFRAHUB_USE_NATS: 1 + INFRAHUB_BROKER_DRIVER: nats + INFRAHUB_BROKER_PORT: 4222 + INFRAHUB_CACHE_DRIVER: nats + INFRAHUB_CACHE_ADDRESS: message-queue + INFRAHUB_CACHE_PORT: 4222 + name: ${{ matrix.name }} + env: ${{ matrix.env }} steps: - name: "Check out repository code" uses: "actions/checkout@v4" @@ -427,7 +462,8 @@ jobs: always() && !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && - needs.files-changed.outputs.backend == 'true' + (needs.files-changed.outputs.backend == 'true' || + needs.files-changed.outputs.documentation == 'true') needs: ["files-changed", "yaml-lint", "python-lint"] runs-on: ubuntu-latest steps: @@ -586,9 +622,24 @@ jobs: runs-on: group: huge-runners timeout-minutes: 40 - env: - INFRAHUB_DB_TYPE: neo4j - METRICS_ENDPOINT: ${{ secrets.METRICS_ENDPOINT }} + strategy: + fail-fast: false + matrix: + include: + - name: E2E-testing-playwright + env: + INFRAHUB_DB_TYPE: neo4j + - name: E2E-testing-playwright-nats + env: + INFRAHUB_DB_TYPE: neo4j + INFRAHUB_USE_NATS: 1 + INFRAHUB_BROKER_DRIVER: nats + INFRAHUB_BROKER_PORT: 4222 + INFRAHUB_CACHE_DRIVER: nats + INFRAHUB_CACHE_ADDRESS: message-queue + INFRAHUB_CACHE_PORT: 4222 + name: ${{ matrix.name }} + env: ${{ matrix.env }} steps: - name: Check out repository code uses: actions/checkout@v4 @@ -669,6 +720,16 @@ jobs: - name: Patch chromium run: printf '\xc3' | dd of=$CHROME_BIN_PATH bs=1 seek=$(($FUNC_OFFSET)) conv=notrunc + - name: Wait for artifacts to be generated before restarting infrahub + if: needs.files-changed.outputs.e2e_tests == 'true' + run: npx playwright test artifact + + - name: Add response delay if required + if: needs.files-changed.outputs.e2e_tests == 'true' + run: echo "INFRAHUB_MISC_RESPONSE_DELAY=2" >> $GITHUB_ENV && invoke dev.start + env: + INFRAHUB_MISC_RESPONSE_DELAY: 2 + - name: Run Playwright tests run: npm run ci:test:e2e @@ -686,7 +747,7 @@ jobs: if: always() uses: actions/upload-artifact@v4 with: - name: playwright-report + name: ${{ matrix.name }} path: frontend/playwright-report/ - name: Containers after tests @@ -709,6 +770,10 @@ jobs: if: always() run: docker logs "${INFRAHUB_BUILD_NAME}-database-1" + - name: Display message-queue logs + if: always() + run: docker logs "${INFRAHUB_BUILD_NAME}-message-queue-1" + - name: Display server status if: always() run: invoke demo.status @@ -731,11 +796,11 @@ jobs: - files-changed - yaml-lint - python-lint - if: false # | - # always() && !cancelled() && - # !contains(needs.*.result, 'failure') && - # !contains(needs.*.result, 'cancelled') && - # needs.files-changed.outputs.backend == 'true' + if: | + always() && !cancelled() && + !contains(needs.*.result, 'failure') && + !contains(needs.*.result, 'cancelled') && + needs.files-changed.outputs.backend == 'true' runs-on: group: huge-runners env: diff --git a/.github/workflows/poetry-check.yml b/.github/workflows/poetry-check.yml index 22e0d20841..1d6d25eb35 100644 --- a/.github/workflows/poetry-check.yml +++ b/.github/workflows/poetry-check.yml @@ -5,7 +5,6 @@ on: workflow_call: inputs: directory: - required: true type: "string" description: "Directory in which poetry check will be executed" default: "./" diff --git a/.github/workflows/publish-dev-docker-image.yml b/.github/workflows/publish-dev-docker-image.yml index beef016645..8a2435155e 100644 --- a/.github/workflows/publish-dev-docker-image.yml +++ b/.github/workflows/publish-dev-docker-image.yml @@ -58,7 +58,6 @@ jobs: labels: | org.opencontainers.image.source=${{ github.repository }} org.opencontainers.image.version=dev-${{ steps.short_ref.outputs.short_ref }} - org.opencontainers.image.created=${{ steps.meta.outputs.created }} flavor: | latest=false diff --git a/.github/workflows/push-bench-image.yml b/.github/workflows/push-bench-image.yml new file mode 100644 index 0000000000..e0053c1da8 --- /dev/null +++ b/.github/workflows/push-bench-image.yml @@ -0,0 +1,58 @@ +--- +# yamllint disable rule:truthy +name: Build And Push Bench image + +on: + workflow_dispatch: + +env: + DOCKERFILE: "utilities/benchmark/Dockerfile" + +jobs: + build: + runs-on: + group: huge-runners + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + uses: docker/login-action@v3 + id: login + with: + registry: ${{ vars.HARBOR_HOST }} + username: ${{ secrets.HARBOR_USERNAME }} + password: ${{ secrets.HARBOR_PASSWORD }} + + - name: Set docker image meta data + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ vars.HARBOR_HOST }}/opsmill/bench + tags: | + type=raw,value=latest + labels: | + org.opencontainers.image.source=opsmill/bench + flavor: | + latest=true + + - name: Build and push + uses: docker/build-push-action@v5 + id: push + with: + context: utilities/benchmark + file: ${{ env.DOCKERFILE }} + provenance: false # To avoid cross platform "unknown" + push: true + platforms: linux/amd64,linux/arm64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/release-preview.yml b/.github/workflows/release-preview.yml new file mode 100644 index 0000000000..a7c65fa2bc --- /dev/null +++ b/.github/workflows/release-preview.yml @@ -0,0 +1,57 @@ +--- +# yamllint disable rule:truthy +name: New Preview Release + +on: + push: + tags: + - 'infrahub-v*rc*' + +jobs: + meta_data: + runs-on: ubuntu-22.04 + outputs: + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + steps: + - name: Set docker image metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ vars.HARBOR_HOST }}/${{ github.repository }} + tags: | + type=match,pattern=infrahub-v(\d+\.\d+\.\d+rc\d+),group=1 + type=match,pattern=infrahub-v(\d+\.\d+rc\d+),group=1 + type=raw,value=rc + labels: | + org.opencontainers.image.source=${{ github.repository }} + + # Commented until we agree to link Infrahub version and chart version + # extract-version: + # runs-on: ubuntu-22.04 + # outputs: + # version: ${{ steps.extract_version.outputs.version }} + # steps: + # - name: Extract version from tag + # id: extract_version + # run: echo "version=${GITHUB_REF_NAME/infrahub-v/}" >> $GITHUB_OUTPUT + + publish-docker-image: + uses: ./.github/workflows/ci-docker-image.yml + secrets: inherit + needs: meta_data + with: + publish: true + version: ${{ github.ref_name }} + ref: ${{ github.sha }} + tags: ${{ needs.meta_data.outputs.tags }} + labels: ${{ needs.meta_data.outputs.labels }} + + publish-helm-chart: + uses: ./.github/workflows/publish-helm-chart.yml + secrets: inherit + # needs: extract-version + with: + publish: true + # version: ${{ needs.extract-version.outputs.version }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2064a33ccc..771293e072 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,6 +6,7 @@ on: push: tags: - 'infrahub-v*' + - '!infrahub-v*rc*' jobs: meta_data: @@ -51,7 +52,7 @@ jobs: publish-helm-chart: uses: ./.github/workflows/publish-helm-chart.yml secrets: inherit - needs: extract-version + # needs: extract-version with: publish: true # version: ${{ needs.extract-version.outputs.version }} diff --git a/.github/workflows/scale-tests.yml b/.github/workflows/scale-tests.yml index 3a64aa2cc8..d2eb603291 100644 --- a/.github/workflows/scale-tests.yml +++ b/.github/workflows/scale-tests.yml @@ -187,7 +187,7 @@ jobs: run: "sleep 10" - name: "Show graph URL" if: always() - run: 'echo "https://grafana-prod.tailc018d.ts.net/d/ebf7ec72-db79-4fb7-9b46-4621ca9c407a/scale-tests?orgId=1&var-run_id=$GITHUB_RUN_ID&var-job=$(echo $JOB_NAME | sed ''s/ /%20/g'')&var-stage=test&var-node_amount=${{ matrix.node-amount }}&var-attrs_amount=${{ matrix.attrs-amount }}&var-rels_amount=${{ matrix.rels-amount }}&var-runner=$INFRAHUB_BUILD_NAME&from=$TEST_START_TIME&to=$(date +%s)000"' + run: 'echo "https://grafana-prod.tailc018d.ts.net/d/ebf7ec72-db79-4fb7-9b46-4621ca9c407a/scale-tests?orgId=1&var-run_id=$GITHUB_RUN_ID&var-job=${JOB_NAME// /%20}&var-stage=test&var-node_amount=${{ matrix.node-amount }}&var-attrs_amount=${{ matrix.attrs-amount }}&var-rels_amount=${{ matrix.rels-amount }}&var-runner=$INFRAHUB_BUILD_NAME&from=$TEST_START_TIME&to=$(date +%s)000"' - name: Display server logs if: always() run: docker logs "${INFRAHUB_BUILD_NAME}-infrahub-server-1" diff --git a/.github/workflows/update-compose-file.yml b/.github/workflows/update-compose-file.yml index 157f3ea24f..f409db0cf7 100644 --- a/.github/workflows/update-compose-file.yml +++ b/.github/workflows/update-compose-file.yml @@ -11,6 +11,11 @@ on: - stable paths: - 'pyproject.toml' + pull_request: + branches: + - stable + types: + - closed jobs: update-docker-compose: diff --git a/.gitignore b/.gitignore index 62859ffca4..7f2630f698 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ python_sdk/dist/* # Generated files generated/ query_performance_results/ +sync/dist/ \ No newline at end of file diff --git a/.vale/styles/Infrahub/sentence-case.yml b/.vale/styles/Infrahub/sentence-case.yml index 7ff566fefd..646a0151d1 100644 --- a/.vale/styles/Infrahub/sentence-case.yml +++ b/.vale/styles/Infrahub/sentence-case.yml @@ -11,11 +11,16 @@ scope: - heading.h6 match: $sentence exceptions: + - Alpha + - Ansible - API - Attributes + - Beta + - BGP - CI - Codespaces - CoreArtifactTarget + - CoreRepository - Docker Compose - E2E - Generics @@ -32,15 +37,20 @@ exceptions: - IP - IPAM - JavaScript + - JetStream - Jinja - Jinja2 - Namespace + - NATS - Node - Python + - RabbitMQ - REST - RFile - SDK + - TLS - TransformPython - Vale - VS Code - VS Code extensions + - WebUI diff --git a/.vale/styles/spelling-exceptions.txt b/.vale/styles/spelling-exceptions.txt index e58f5e189d..b29dc35bc0 100644 --- a/.vale/styles/spelling-exceptions.txt +++ b/.vale/styles/spelling-exceptions.txt @@ -1,4 +1,5 @@ agent +Ansible APIs artifact_definitions artifact_name @@ -12,6 +13,7 @@ Config content_type convert_query_response CoreRepository +coroutine cypher Dagster datastore @@ -37,6 +39,8 @@ graphene graphiql graphql greymatter +hfid +Human Friendly Identifier idempotency include_in_menu Infrahub @@ -54,11 +58,13 @@ kbps markdownlint memgraph menu_placement +modeline modularization namespace namespaces Nautobot Netbox +Nornir npm o'brian openconfig diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..6d0926e87a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,118 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[opensource-security@opsmill.com](mailto:opensource-security@opsmill.com). +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..d33a1f0f1c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,17 @@ +# Contributing + +We develop Infrahub for customers and with the community. We are open to pull requests. Please first discuss your intentions via [Discussions](https://github.com/opsmill/infrahub/discussions). + +## Contribute to Infrahub + +Please see our [Development Docs](https://docs.infrahub.app/development/) for a guide to getting started developing for Infrahub. + +We maintain a [list of issues that are appropriate to newcomers](https://github.com/opsmill/infrahub/issues?q=is:open+is:issue+label:type/newcomers) to the Infrahub development community. This is a great place to get started! + +## Contributor License Agreement + +A CLA is a tool that allows outside contributors to sign a Contributor License Agreement (CLA), an important license protection for OpsMill and our contributors. Signing this agreement allows external contributors to contribute code to OpsMill open-source repos. Contributions to this repository are subject to the Contributor License Agreement. + +## Code of Conduct + +[View our CODE_OF_CONDUCT](./CODE_OF_CONDUCT.md) policy to find the latest information. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000000..bae94e189e --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/LICENSING.md b/LICENSING.md new file mode 100644 index 0000000000..49d4b361f6 --- /dev/null +++ b/LICENSING.md @@ -0,0 +1,15 @@ +# Licensing + +License names used in this document are as per [SPDX License List](https://spdx.org/licenses/). + +The default license for this project is [AGPL-3.0-only](LICENSE). + +## Apache-2.0 + +The following directories and their subdirectories are licensed under Apache-2.0: + +```bash +models/ +python_sdk/ +sync/ +``` \ No newline at end of file diff --git a/README.md b/README.md index 5de35115a8..855fbe8423 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,43 @@ - -![](./docs/media/Infrahub-horizontal.svg) +![Infrahub Logo](docs/static/img/infrahub-hori.svg) -# Welcome to Infrahub - -Infrahub is taking a new approach to Infrastructure Management by providing a new generation of datastore to organize and control all the data that defines how an infrastructure should run. +# Infrahub [![CI](https://github.com/opsmill/infrahub/actions/workflows/ci.yml/badge.svg?branch=stable)](https://github.com/opsmill/infrahub/actions/workflows/ci.yml) -At its heart, Infrahub is built on 3 fundamental pillars: +Infrahub from [OpsMill](https://opsmill.com) is taking a new approach to Infrastructure Management by providing a new generation of datastore to organize and control all the data that defines how an infrastructure should run. Infrahub offers a central hub to manage the data, templates and playbooks that powers your infrastructure by combining the version control and branch management capabilities of Git with the flexible data model and UI of a graph database. -- **Powerful Schema**: that's easily extensible -- **Unified Version Control**: for data and files -- **Data Synchronization**: with traceability and ownership +![infrahub screenshot](docs/docs/media/infrahub-readme.gif) ## Quick Start -Leveraging [Codespaces](https://docs.github.com/en/codespaces/overview) from Github, it's possible to start a fresh instance of Infrahub in the Cloud in minutes. This is the recommended method to try Infrahub as it reduces the effort to setup Infrahub to a couple of clicks. Use the table below to select the right environment for you, based on the branch and the initial data you would like pre-loaded in your instance. - -- The `stable` branch is for the latest release; this is the recommended version for most users. -- The `develop` branch is where the preparation of the next major release is done. -- The `Default` version does not include a schema or data pre-loaded. -- The `Demo` version includes a pre-loaded schema and a sample network dataset. - > [!NOTE] -> The documentation includes how to get setup and start using Infrahub. The documentation is currently protected by password : `cXsivxXAgL7Hae` +> Infrahub is currently in beta, and the team is actively working towards reaching version 1.0 by the end of the year. The project is committed to ensuring data safety and providing a migration path for future releases. See our [FAQ](https://docs.infrahub.app/faq/) for more information. + +Leveraging [GitHub Codespaces](https://docs.github.com/en/codespaces/overview), it's possible to start a new instance of Infrahub in the Cloud in minutes: -| | Branch `stable` | Branch `develop` | -|---|---|---| -| Run Default version of Infrahub in Codespaces | [![Start in Codespaces (stable), without data](https://img.shields.io/badge/Start%20stable%20version-0B6581?style=for-the-badge)]( https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=stable ) | [![Start in Codespaces (develop), without data](https://img.shields.io/badge/Start%20develop%20version-0B6581?style=for-the-badge)]( https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=develop ) | -| Run Demo version of Infrahub in Codespaces | [![Start in Codespaces (stable), with demo data](https://img.shields.io/badge/Start%20stable%20version%20demo%20data-0D3F54?style=for-the-badge)]( https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdemo-container%2Fdevcontainer.json&ref=stable ) | [![Start in Codespaces (develop), with demo data](https://img.shields.io/badge/Start%20develop%20version%20demo%20data-0D3F54?style=for-the-badge)]( https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdemo-container%2Fdevcontainer.json&ref=develop) | -| Documentation | [![Documentation](https://img.shields.io/badge/Documentation%20for%20stable-0B97BB?style=for-the-badge)](https://docs.infrahub.app/) | [![Documentation](https://img.shields.io/badge/Documentation%20for%20develop-0B97BB?style=for-the-badge)](https://develop.infrahub.pages.dev/) | +| No Data | Demo Data | +|---|---| +| [![Launch in GitHub Codespaces (No Data)](https://img.shields.io/badge/Launch%20Infrahub-0B6581?logo=github)](https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=stable) | [![Launch in GitHub Codespaces (Demo Data)](https://img.shields.io/badge/Infrahub%20with%20Data-0B6581?logo=github)](https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=stable) | -> [!TIP] -> The cost for running an Infrahub instance in Codespaces is covered by OpsMill. You can find your codespaces even after they are closed in your dashboard https://github.com/codespaces where you can reconnect to a previous codespace. +For details on how to deploy a local instance of Infrahub please refer to our guide: [Installing Infrahub](https://docs.infrahub.app/guides/installation) ## Documentation -If you'd like to learn more about Infrahub or deploy via alternate means, please check out the documentation: +If you'd like to learn more about Infrahub, please refer to the following resources: +- [Infrahub Overview](https://docs.infrahub.app/overview/) +- [Getting Started](https://docs.infrahub.app/tutorials/getting-started/) - [Infrahub Documentation](https://docs.infrahub.app/) -- [Deploy the demo environment on your laptop](https://docs.infrahub.app/tutorials/getting-started/#prepare-the-demo-environment) +- [FAQ](https://docs.infrahub.app/faq/) + +## Support and Community + +If you need help, support for the open-source Infrahub project is provided on [![Join our Discord server](https://img.shields.io/badge/Discord-7289DA?logo=discord&logoColor=white)](https://discord.gg/jXMRp9hXSX) or via [filing an issue on GitHub](https://github.com/opsmill/infrahub/issues). + +## Contributing + +[View our CONTRIBUTING](./CONTRIBUTING.md) policy to find the latest information. + +## Security + +[View our SECURITY](./SECURITY.md) policy to find the latest information. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..e5a062700b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Infrahub - Security + +We deeply appreciate any effort to discover and disclose security vulnerabilities responsibly. + +If you discover a security vulnerability, please use the GitHub Security Advisory **[Report a Vulnerability](https://github.com/opsmill/infrahub/security/advisories/new)** tab. + +## Reporting Security Issues + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + +- The type of issue (e.g., buffer overflow, input validation, or cross-site scripting) +- Full paths of source file(s) related to the manifestation of the issue +- The location of the affected source code (tag/branch/commit or direct URL) +- Any special configuration required to reproduce the issue +- Step-by-step instructions to reproduce the issue +- Proof-of-concept or exploit code (if possible) +- Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. diff --git a/backend/infrahub/api/artifact.py b/backend/infrahub/api/artifact.py index dc7136a29f..5a802cc6b0 100644 --- a/backend/infrahub/api/artifact.py +++ b/backend/infrahub/api/artifact.py @@ -41,9 +41,10 @@ async def get_artifact( branch_name=branch_params.branch.name, node_type=InfrahubKind.ARTIFACT, identifier=artifact_id ) - content = await registry.storage.retrieve(identifier=artifact.storage_id.value) - - return Response(content=content, headers={"Content-Type": artifact.content_type.value.value}) + return Response( + content=registry.storage.retrieve(identifier=artifact.storage_id.value), + headers={"Content-Type": artifact.content_type.value.value}, + ) @router.post("/generate/{artifact_definition_id:str}") @@ -62,7 +63,7 @@ async def generate_artifact( artifact_definition = await registry.manager.get_one_by_id_or_default_filter( db=db, id=artifact_definition_id, - schema_name=InfrahubKind.ARTIFACTDEFINITION, + kind=InfrahubKind.ARTIFACTDEFINITION, branch=branch_params.branch, ) diff --git a/backend/infrahub/api/file.py b/backend/infrahub/api/file.py index 09d00d096f..c4f48dea2b 100644 --- a/backend/infrahub/api/file.py +++ b/backend/infrahub/api/file.py @@ -40,7 +40,7 @@ async def get_file( repo = await NodeManager.get_one_by_id_or_default_filter( db=db, id=repository_id, - schema_name=InfrahubKind.GENERICREPOSITORY, + kind=InfrahubKind.GENERICREPOSITORY, branch=branch_params.branch, at=branch_params.at, ) diff --git a/backend/infrahub/api/internal.py b/backend/infrahub/api/internal.py index d6e7f4a2d4..b35fd89019 100644 --- a/backend/infrahub/api/internal.py +++ b/backend/infrahub/api/internal.py @@ -2,11 +2,11 @@ from typing import List, Optional import ujson -from fastapi import APIRouter +from fastapi import APIRouter, Request from lunr.index import Index from pydantic import BaseModel -from infrahub import __version__, config +from infrahub import config from infrahub.config import AnalyticsSettings, ExperimentalFeaturesSettings, LoggingSettings, MainSettings from infrahub.core import registry from infrahub.exceptions import NodeNotFoundError @@ -37,8 +37,8 @@ async def get_config() -> ConfigAPI: @router.get("/info") -async def get_info() -> InfoAPI: - return InfoAPI(deployment_id=str(registry.id), version=__version__) +async def get_info(request: Request) -> InfoAPI: + return InfoAPI(deployment_id=str(registry.id), version=request.app.version) class SearchDocs: diff --git a/backend/infrahub/api/menu.py b/backend/infrahub/api/menu.py index 6fba769f24..e38ee38e68 100644 --- a/backend/infrahub/api/menu.py +++ b/backend/infrahub/api/menu.py @@ -76,7 +76,7 @@ async def get_menu( icon=_extract_node_icon(full_schema[InfrahubKind.IPNAMESPACE]), ), InterfaceMenu( - title="Prefixes", path="/ipam/prefixes", icon=_extract_node_icon(full_schema[InfrahubKind.IPPREFIX]) + title="IP Prefixes", path="/ipam/prefixes", icon=_extract_node_icon(full_schema[InfrahubKind.IPPREFIX]) ), InterfaceMenu( title="IP Addresses", @@ -115,7 +115,7 @@ async def get_menu( objects.children.sort() groups = InterfaceMenu( - title="Groups & Profiles", + title="Object Management", children=[ InterfaceMenu( title="All Groups", @@ -129,6 +129,16 @@ async def get_menu( ), ], ) + + if has_ipam: + groups.children.append( + InterfaceMenu( + title="Resource Manager", + path="/resource-manager", + icon=_extract_node_icon(full_schema[InfrahubKind.RESOURCEPOOL]), + ) + ) + unified_storage = InterfaceMenu( title="Unified Storage", children=[ diff --git a/backend/infrahub/api/query.py b/backend/infrahub/api/query.py index 129f0c29d9..d115c2ea14 100644 --- a/backend/infrahub/api/query.py +++ b/backend/infrahub/api/query.py @@ -51,7 +51,7 @@ async def execute_query( subscribers: List[str], ) -> Dict[str, Any]: gql_query = await registry.manager.get_one_by_id_or_default_filter( - db=db, id=query_id, schema_name=InfrahubKind.GRAPHQLQUERY, branch=branch_params.branch, at=branch_params.at + db=db, id=query_id, kind=InfrahubKind.GRAPHQLQUERY, branch=branch_params.branch, at=branch_params.at ) gql_params = prepare_graphql_params(db=db, branch=branch_params.branch, at=branch_params.at) diff --git a/backend/infrahub/api/schema.py b/backend/infrahub/api/schema.py index c5fb8a39af..4af1175ef5 100644 --- a/backend/infrahub/api/schema.py +++ b/backend/infrahub/api/schema.py @@ -1,9 +1,15 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from fastapi import APIRouter, BackgroundTasks, Depends, Query, Request -from pydantic import BaseModel, Field, computed_field, model_validator +from pydantic import ( + BaseModel, + Field, + computed_field, + create_model, + model_validator, +) from starlette.responses import JSONResponse from infrahub import config, lock @@ -21,6 +27,7 @@ from infrahub.log import get_logger from infrahub.message_bus import Meta, messages from infrahub.services import services +from infrahub.types import ATTRIBUTE_PYTHON_TYPES from infrahub.worker import WORKER_IDENTITY if TYPE_CHECKING: @@ -82,6 +89,21 @@ class SchemasLoadAPI(SchemaRoot): schemas: List[SchemaLoadAPI] +class JSONSchema(BaseModel): + title: Optional[str] = Field(None, description="Title of the schema") + description: Optional[str] = Field(None, description="Description of the schema") + type: str = Field(..., description="Type of the schema element (e.g., 'object', 'array', 'string')") + properties: Optional[Dict[str, Any]] = Field(None, description="Properties of the object if type is 'object'") + items: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = Field( + None, description="Items of the array if type is 'array'" + ) + required: Optional[List[str]] = Field(None, description="List of required properties if type is 'object'") + schema_spec: Optional[str] = Field(None, alias="$schema", description="Schema version identifier") + additional_properties: Optional[Union[bool, Dict[str, Any]]] = Field( + None, description="Specifies whether additional properties are allowed", alias="additionalProperties" + ) + + class SchemaUpdate(BaseModel): hash: str = Field(..., description="The new hash for the entire schema") previous_hash: str = Field(..., description="The previous hash for the entire schema") @@ -178,6 +200,37 @@ async def get_schema_by_kind( return api_schema[key].from_schema(schema=schema) +@router.get("/json_schema/{schema_kind}") +async def get_json_schema_by_kind( + schema_kind: str, + branch: Branch = Depends(get_branch_dep), +) -> JSONSchema: + log.debug("json_schema_kind_request", branch=branch.name) + + fields: dict[str, Any] = {} + + schema = registry.schema.get(name=schema_kind, branch=branch) + + for attr in schema.attributes: + field_type = ATTRIBUTE_PYTHON_TYPES[attr.kind] + + default_value = attr.default_value if attr.optional else ... + field_info = Field(default=default_value, description=attr.description) + if attr.enum: + extras: dict[str, Any] = {"enum": attr.enum} + # ignore types because mypy hates generic kwargs + field_info = Field(default=default_value, description=attr.description, **extras) + fields[attr.name] = (field_type, field_info) + + # Use Pydantic's create_model to dynamically create the class, ignore types because fields are Any, and mypy hates that + json_schema = create_model(schema.name, **fields).model_json_schema() + + json_schema["description"] = schema.description + json_schema["$schema"] = "http://json-schema.org/draft-07/schema#" + + return json_schema + + @router.post("/load") async def load_schema( request: Request, @@ -232,6 +285,7 @@ async def load_schema( branch.update_schema_hash() log.info("Schema has been updated", branch=branch.name, hash=branch.active_schema_hash.main) + # NOTE shouldn't be required anymore, will need to cleanup later if not branch.is_isolated and not branch.is_default and branch.has_schema_changes: branch.is_isolated = True log.info("Branch converted to isolated mode because the schema has changed", branch=branch.name) diff --git a/backend/infrahub/api/transformation.py b/backend/infrahub/api/transformation.py index 5710d7f9f3..a4e77e9fae 100644 --- a/backend/infrahub/api/transformation.py +++ b/backend/infrahub/api/transformation.py @@ -43,7 +43,7 @@ async def transform_python( transform = await NodeManager.get_one_by_id_or_default_filter( db=db, id=transform_id, - schema_name=InfrahubKind.TRANSFORMPYTHON, + kind=InfrahubKind.TRANSFORMPYTHON, branch=branch_params.branch, at=branch_params.at, ) @@ -92,7 +92,7 @@ async def transform_jinja2( transform = await NodeManager.get_one_by_id_or_default_filter( db=db, id=transform_id, - schema_name=InfrahubKind.TRANSFORMJINJA2, + kind=InfrahubKind.TRANSFORMJINJA2, branch=branch_params.branch, at=branch_params.at, ) diff --git a/backend/infrahub/auth.py b/backend/infrahub/auth.py index e23b7abc6b..d7736ee6c9 100644 --- a/backend/infrahub/auth.py +++ b/backend/infrahub/auth.py @@ -40,6 +40,10 @@ class AccountSession(BaseModel): def read_only(self) -> bool: return self.role == "read-only" + @property + def authenticated_by_jwt(self) -> bool: + return self.auth_type == AuthType.JWT + async def authenticate_with_password( db: InfrahubDatabase, credentials: models.PasswordCredential, branch: Optional[str] = None @@ -223,22 +227,24 @@ def _validate_update_account(account_session: AccountSession, node_id: str, fiel def validate_mutation_permissions(operation: str, account_session: AccountSession) -> None: validation_map: Dict[str, Callable[[AccountSession], None]] = { - "AccountCreate": _validate_is_admin, - "AccountDelete": _validate_is_admin, + f"{InfrahubKind.ACCOUNT}Create": _validate_is_admin, + f"{InfrahubKind.ACCOUNT}Delete": _validate_is_admin, + f"{InfrahubKind.ACCOUNT}Upsert": _validate_is_admin, } if validator := validation_map.get(operation): - validator(account_session=account_session) + validator(account_session) def validate_mutation_permissions_update_node( operation: str, node_id: str, account_session: AccountSession, fields: List[str] ) -> None: validation_map: Dict[str, Callable[[AccountSession, str, List[str]], None]] = { - "AccountUpdate": _validate_update_account, + f"{InfrahubKind.ACCOUNT}Update": _validate_update_account, + f"{InfrahubKind.ACCOUNT}Upsert": _validate_update_account, } if validator := validation_map.get(operation): - validator(account_session=account_session, node_id=node_id, fields=fields) + validator(account_session, node_id, fields) async def invalidate_refresh_token(db: InfrahubDatabase, token_id: str) -> None: diff --git a/backend/infrahub/cli/__init__.py b/backend/infrahub/cli/__init__.py index b160666e44..f6d042be32 100644 --- a/backend/infrahub/cli/__init__.py +++ b/backend/infrahub/cli/__init__.py @@ -3,6 +3,7 @@ import typer from infrahub import config +from infrahub.cli.context import CliContext from infrahub.cli.db import app as db_app from infrahub.cli.events import app as events_app from infrahub.cli.git_agent import app as git_app @@ -12,7 +13,14 @@ # pylint: disable=import-outside-toplevel -app = typer.Typer(pretty_exceptions_enable=False) +app = typer.Typer(name="Infrahub CLI", pretty_exceptions_enable=False) + + +@app.callback() +def common(ctx: typer.Context) -> None: + """Infrahub CLI""" + ctx.obj = CliContext(database_class=InfrahubDatabase) + app.add_typer(server_app, name="server") app.add_typer(git_app, name="git-agent") diff --git a/backend/infrahub/cli/context.py b/backend/infrahub/cli/context.py new file mode 100644 index 0000000000..6f4e6a83e5 --- /dev/null +++ b/backend/infrahub/cli/context.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from infrahub.database import get_db + +if TYPE_CHECKING: + from infrahub.database import InfrahubDatabase + + +@dataclass +class CliContext: + database_class: type[InfrahubDatabase] + application: str = "infrahub.server:app" + + async def get_db(self, retry: int = 0) -> InfrahubDatabase: + return self.database_class(driver=await get_db(retry=retry)) diff --git a/backend/infrahub/cli/db.py b/backend/infrahub/cli/db.py index 90e5869148..33012f66a0 100644 --- a/backend/infrahub/cli/db.py +++ b/backend/infrahub/cli/db.py @@ -1,7 +1,7 @@ import importlib import logging from enum import Enum -from typing import Optional +from typing import TYPE_CHECKING, Optional import typer from infrahub_sdk.async_typer import AsyncTyper @@ -24,11 +24,14 @@ from infrahub.core.schema_manager import SchemaManager from infrahub.core.utils import delete_all_nodes from infrahub.core.validators.checker import schema_validators_checker -from infrahub.database import DatabaseType, InfrahubDatabase, get_db +from infrahub.database import DatabaseType from infrahub.log import get_logger from infrahub.services import InfrahubServices from infrahub.services.adapters.message_bus.local import BusSimulator +if TYPE_CHECKING: + from infrahub.cli.context import CliContext + app = AsyncTyper() PERMISSIONS_AVAILABLE = ["read", "write", "admin"] @@ -55,6 +58,7 @@ def callback() -> None: @app.command() async def init( + ctx: typer.Context, config_file: str = typer.Option( "infrahub.toml", envvar="INFRAHUB_CONFIG", help="Location of the configuration file to use for Infrahub" ), @@ -72,7 +76,8 @@ async def init( logging.getLogger("neo4j").setLevel(logging.ERROR) config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) async with dbdriver.start_transaction() as db: log.info("Delete All Nodes") await delete_all_nodes(db=db) @@ -83,6 +88,7 @@ async def init( @app.command() async def load_test_data( + ctx: typer.Context, config_file: str = typer.Option( "infrahub.toml", envvar="INFRAHUB_CONFIG", help="Location of the configuration file to use for Infrahub" ), @@ -93,7 +99,8 @@ async def load_test_data( logging.getLogger("neo4j").setLevel(logging.ERROR) config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) async with dbdriver.start_session() as db: await initialization(db=db) @@ -111,6 +118,7 @@ async def load_test_data( @app.command() async def migrate( + ctx: typer.Context, check: bool = typer.Option(False, help="Check the state of the database without applying the migrations."), config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"), ) -> None: @@ -119,7 +127,8 @@ async def migrate( config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) async with dbdriver.start_session() as db: rprint("Checking current state of the Database") @@ -161,6 +170,7 @@ async def migrate( @app.command() async def update_core_schema( # pylint: disable=too-many-statements + ctx: typer.Context, debug: bool = typer.Option(False, help="Enable advanced logging and troubleshooting"), config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"), ) -> None: @@ -169,7 +179,8 @@ async def update_core_schema( # pylint: disable=too-many-statements logging.getLogger("neo4j").setLevel(logging.ERROR) config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) error_badge = "[bold red]ERROR[/bold red]" @@ -270,13 +281,15 @@ async def update_core_schema( # pylint: disable=too-many-statements @app.command() async def constraint( + ctx: typer.Context, action: ConstraintAction = typer.Argument(ConstraintAction.SHOW), config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"), ) -> None: """Manage Database Constraints""" config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) manager: Optional[ConstraintManagerBase] = None if dbdriver.db_type == DatabaseType.NEO4J: @@ -312,13 +325,15 @@ async def constraint( @app.command() async def index( + ctx: typer.Context, action: IndexAction = typer.Argument(IndexAction.SHOW), config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"), ) -> None: """Manage Database Indexes""" config.load_and_exit(config_file_name=config_file) - dbdriver = InfrahubDatabase(driver=await get_db(retry=1)) + context: CliContext = ctx.obj + dbdriver = await context.get_db(retry=1) dbdriver.manager.index.init(nodes=node_indexes, rels=rel_indexes) if action == IndexAction.ADD: diff --git a/backend/infrahub/cli/git_agent.py b/backend/infrahub/cli/git_agent.py index 1e1301d7ce..06fd141b4a 100644 --- a/backend/infrahub/cli/git_agent.py +++ b/backend/infrahub/cli/git_agent.py @@ -1,29 +1,34 @@ import asyncio import logging import signal -from typing import Any +from typing import TYPE_CHECKING, Any import typer from infrahub_sdk import Config, InfrahubClient +from infrahub_sdk.async_typer import AsyncTyper +from infrahub_sdk.exceptions import Error as SdkError from prometheus_client import start_http_server from rich.logging import RichHandler from infrahub import __version__, config from infrahub.components import ComponentType from infrahub.core.initialization import initialization -from infrahub.database import InfrahubDatabase, get_db from infrahub.dependencies.registry import build_component_registry from infrahub.git import initialize_repositories_directory from infrahub.git.actions import sync_remote_repositories from infrahub.lock import initialize_lock from infrahub.log import get_logger from infrahub.services import InfrahubServices +from infrahub.services.adapters.cache.nats import NATSCache from infrahub.services.adapters.cache.redis import RedisCache +from infrahub.services.adapters.message_bus.nats import NATSMessageBus from infrahub.services.adapters.message_bus.rabbitmq import RabbitMQMessageBus from infrahub.trace import configure_trace -app = typer.Typer() +if TYPE_CHECKING: + from infrahub.cli.context import CliContext +app = AsyncTyper() log = get_logger() shutdown_event = asyncio.Event() @@ -51,8 +56,28 @@ async def initialize_git_agent(service: InfrahubServices) -> None: await sync_remote_repositories(service=service) -async def _start(debug: bool, port: int) -> None: +@app.command() +async def start( + ctx: typer.Context, + debug: bool = typer.Option(False, help="Enable advanced logging and troubleshooting"), + config_file: str = typer.Option( + "infrahub.toml", envvar="INFRAHUB_CONFIG", help="Location of the configuration file to use for Infrahub" + ), + port: int = typer.Argument(8000, envvar="INFRAHUB_METRICS_PORT", help="Port used to expose a metrics endpoint"), +) -> None: """Start Infrahub Git Agent.""" + logging.getLogger("httpx").setLevel(logging.ERROR) + logging.getLogger("httpcore").setLevel(logging.ERROR) + logging.getLogger("neo4j").setLevel(logging.ERROR) + logging.getLogger("aio_pika").setLevel(logging.ERROR) + logging.getLogger("aiormq").setLevel(logging.ERROR) + logging.getLogger("git").setLevel(logging.ERROR) + + log.debug(f"Config file : {config_file}") + + context: CliContext = ctx.obj + + config.load_and_exit(config_file_name=config_file) log_level = "DEBUG" if debug else "INFO" @@ -67,7 +92,11 @@ async def _start(debug: bool, port: int) -> None: client = InfrahubClient( config=Config(address=config.SETTINGS.main.internal_address, retry_on_failure=True, log=log) ) - await client.branch.all() + try: + await client.branch.all() + except SdkError as exc: + log.error(f"Error in communication with Infrahub: {exc.message}") + raise typer.Exit(1) # Initialize trace if config.SETTINGS.trace.enable: @@ -79,20 +108,27 @@ async def _start(debug: bool, port: int) -> None: exporter_protocol=config.SETTINGS.trace.exporter_protocol, ) - # Initialize the lock - initialize_lock() + database = await context.get_db(retry=1) + + message_bus = config.OVERRIDE.message_bus or ( + NATSMessageBus() if config.SETTINGS.broker.driver == config.BrokerDriver.NATS else RabbitMQMessageBus() + ) + cache = config.OVERRIDE.cache or ( + NATSCache() if config.SETTINGS.cache.driver == config.CacheDriver.NATS else RedisCache() + ) - driver = await get_db() - database = InfrahubDatabase(driver=driver) service = InfrahubServices( - cache=RedisCache(), + cache=cache, client=client, database=database, - message_bus=RabbitMQMessageBus(), + message_bus=message_bus, component_type=ComponentType.GIT_AGENT, ) await service.initialize() + # Initialize the lock + initialize_lock(service=service) + async with service.database.start_session() as db: await initialization(db=db) @@ -102,6 +138,8 @@ async def _start(debug: bool, port: int) -> None: build_component_registry() + log.info("Initialized Git Agent ...") + while not shutdown_event.is_set(): await asyncio.sleep(1) @@ -109,26 +147,3 @@ async def _start(debug: bool, port: int) -> None: await service.shutdown() log.info("All services stopped") - - -@app.command() -def start( - debug: bool = typer.Option(False, help="Enable advanced logging and troubleshooting"), - config_file: str = typer.Option( - "infrahub.toml", envvar="INFRAHUB_CONFIG", help="Location of the configuration file to use for Infrahub" - ), - port: int = typer.Argument(8000, envvar="INFRAHUB_METRICS_PORT", help="Port used to expose a metrics endpoint"), -) -> None: - """Start Infrahub Git Agent.""" - logging.getLogger("httpx").setLevel(logging.ERROR) - logging.getLogger("httpcore").setLevel(logging.ERROR) - logging.getLogger("neo4j").setLevel(logging.ERROR) - logging.getLogger("aio_pika").setLevel(logging.ERROR) - logging.getLogger("aiormq").setLevel(logging.ERROR) - logging.getLogger("git").setLevel(logging.ERROR) - - log.debug(f"Config file : {config_file}") - - config.load_and_exit(config_file_name=config_file) - - asyncio.run(_start(debug=debug, port=port)) diff --git a/backend/infrahub/cli/server.py b/backend/infrahub/cli/server.py index c9c8244561..56f0d15f8e 100644 --- a/backend/infrahub/cli/server.py +++ b/backend/infrahub/cli/server.py @@ -1,8 +1,12 @@ import logging +from typing import TYPE_CHECKING import typer import uvicorn +if TYPE_CHECKING: + from infrahub.cli.context import CliContext + app = typer.Typer() @@ -39,6 +43,7 @@ def callback() -> None: @app.command() def start( + ctx: typer.Context, listen: str = typer.Option("127.0.0.1", help="Address used to listen for new request."), port: int = typer.Option(8000, help="Port used to listen for new request."), debug: bool = typer.Option(False, help="Enable advanced logging and troubleshooting"), @@ -50,9 +55,11 @@ def start( logging.getLogger("neo4j").setLevel(logging.ERROR) + context: CliContext = ctx.obj + if debug: uvicorn.run( - "infrahub.server:app", + context.application, host=listen, port=port, log_level="info", @@ -62,7 +69,7 @@ def start( ) else: uvicorn.run( - "infrahub.server:app", + context.application, host=listen, port=port, log_level="info", diff --git a/backend/infrahub/config.py b/backend/infrahub/config.py index ea0c6d1c17..81533b3494 100644 --- a/backend/infrahub/config.py +++ b/backend/infrahub/config.py @@ -10,8 +10,9 @@ import toml from infrahub_sdk import generate_uuid -from pydantic import AliasChoices, Field, ValidationError +from pydantic import AliasChoices, Field, ValidationError, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict +from typing_extensions import Self from infrahub.database.constants import DatabaseType from infrahub.exceptions import InitializationError @@ -51,6 +52,16 @@ class TraceTransportProtocol(str, Enum): # HTTP_JSON = "http/json" +class BrokerDriver(str, Enum): + RabbitMQ = "rabbitmq" + NATS = "nats" + + +class CacheDriver(str, Enum): + Redis = "redis" + NATS = "nats" + + class MainSettings(BaseSettings): model_config = SettingsConfigDict(env_prefix="INFRAHUB_") docs_index_path: str = Field( @@ -61,6 +72,11 @@ class MainSettings(BaseSettings): allow_anonymous_access: bool = Field( default=True, description="Indicates if the system allows anonymous read access" ) + telemetry_optout: bool = Field(default=False, description="Disable anonymous usage reporting") + telemetry_endpoint: str = "https://telemetry.opsmill.cloud/infrahub" + telemetry_interval: int = Field( + default=3600 * 24, ge=60, description="Time (in seconds) between telemetry usage push" + ) class FileSystemStorageSettings(BaseSettings): @@ -99,7 +115,7 @@ class S3StorageSettings(BaseSettings): querystring_auth: bool = Field( default=False, alias="AWS_QUERYSTRING_AUTH", - validation_alias=AliasChoices("INFRAHUB_STORAGE_QUERYTSTRING_AUTH", "AWS_QUERYSTRING_AUTH"), + validation_alias=AliasChoices("INFRAHUB_STORAGE_QUERYSTRING_AUTH", "AWS_QUERYSTRING_AUTH"), ) custom_domain: str = Field( default="", @@ -109,7 +125,7 @@ class S3StorageSettings(BaseSettings): class StorageSettings(BaseSettings): - model_config = SettingsConfigDict(env_prefix="INFRAHUB_STORAGE") + model_config = SettingsConfigDict(env_prefix="INFRAHUB_STORAGE_") driver: StorageDriver = StorageDriver.FileSystemStorage local: FileSystemStorageSettings = FileSystemStorageSettings() s3: S3StorageSettings = S3StorageSettings() @@ -126,6 +142,9 @@ class DatabaseSettings(BaseSettings): address: str = "localhost" port: int = 7687 database: Optional[str] = Field(default=None, pattern=VALID_DATABASE_NAME_REGEX, description="Name of the database") + tls_enabled: bool = Field(default=False, description="Indicates if TLS is enabled for the connection") + tls_insecure: bool = Field(default=False, description="Indicates if TLS certificates are verified") + tls_ca_file: Optional[str] = Field(default=None, description="File path to CA cert or bundle in PEM format") query_size_limit: int = Field( default=5000, ge=1, @@ -138,7 +157,7 @@ class DatabaseSettings(BaseSettings): description="Maximum number of level to search in a hierarchy.", ) retry_limit: int = Field( - default=3, description="Maximumm number of time a transient issue in a transaction should be retried." + default=3, description="Maximum number of times a transient issue in a transaction should be retried." ) @property @@ -150,6 +169,8 @@ class BrokerSettings(BaseSettings): model_config = SettingsConfigDict(env_prefix="INFRAHUB_BROKER_") enable: bool = True tls_enabled: bool = Field(default=False, description="Indicates if TLS is enabled for the connection") + tls_insecure: bool = Field(default=False, description="Indicates if TLS certificates are verified") + tls_ca_file: Optional[str] = Field(default=None, description="File path to CA cert or bundle in PEM format") username: str = "infrahub" password: str = "infrahub" address: str = "localhost" @@ -162,10 +183,13 @@ class BrokerSettings(BaseSettings): default=2, description="The maximum number of concurrent messages fetched by each worker", ge=1 ) virtualhost: str = Field(default="/", description="The virtual host to connect to") + driver: BrokerDriver = BrokerDriver.RabbitMQ @property def service_port(self) -> int: default_ports: Dict[bool, int] = {True: 5671, False: 5672} + if self.driver == BrokerDriver.NATS: + return self.port or 4222 return self.port or default_ports[self.tls_enabled] @@ -177,10 +201,18 @@ class CacheSettings(BaseSettings): default=None, ge=1, le=65535, description="Specified if running on a non default port (6379)" ) database: int = Field(default=0, ge=0, le=15, description="Id of the database to use") + driver: CacheDriver = CacheDriver.Redis + username: str = "infrahub" + password: str = "infrahub" + tls_enabled: bool = Field(default=False, description="Indicates if TLS is enabled for the connection") + tls_insecure: bool = Field(default=False, description="Indicates if TLS certificates are verified") + tls_ca_file: Optional[str] = Field(default=None, description="File path to CA cert or bundle in PEM format") @property def service_port(self) -> int: default_ports: int = 6379 + if self.driver == CacheDriver.NATS: + return self.port or 4222 return self.port or default_ports @@ -203,6 +235,7 @@ class ApiSettings(BaseSettings): class GitSettings(BaseSettings): + model_config = SettingsConfigDict(env_prefix="INFRAHUB_GIT_") repositories_directory: str = "repositories" sync_interval: int = Field( default=10, ge=0, description="Time (in seconds) between git repositories synchronizations" @@ -215,6 +248,24 @@ class InitialSettings(BaseSettings): default="main", description="Defines the name of the default branch within Infrahub, can only be set once during initialization of the system.", ) + admin_token: Optional[str] = Field(default=None, description="An optional initial token for the admin account.") + admin_password: str = Field(default="infrahub", description="The initial password for the admin user") + agent_token: Optional[str] = Field(default=None, description="An optional initial token for a git-agent account.") + agent_password: Optional[str] = Field( + default=None, description="An optional initial password for a git-agent account." + ) + + @property + def create_agent_user(self) -> bool: + if self.agent_token or self.agent_password: + return True + return False + + @model_validator(mode="after") + def check_tokens_match(self) -> Self: + if self.admin_token is not None and self.agent_token is not None and self.admin_token == self.agent_token: + raise ValueError("Initial user tokens can't have the same values") + return self class MiscellaneousSettings(BaseSettings): @@ -224,6 +275,7 @@ class MiscellaneousSettings(BaseSettings): maximum_validator_execution_time: int = Field( default=1800, description="The maximum allowed time (in seconds) for a validator to run." ) + response_delay: int = Field(default=0, description="Arbitrary delay to add when processing API requests.") class RemoteLoggingSettings(BaseSettings): @@ -260,10 +312,6 @@ class SecuritySettings(BaseSettings): secret_key: str = Field( default_factory=generate_uuid, description="The secret key used to validate authentication tokens" ) - initial_admin_password: str = Field(default="infrahub", description="The initial password for the admin user") - initial_admin_token: Optional[str] = Field( - default=None, description="An optional initial token for the admin account." - ) class TraceSettings(BaseSettings): diff --git a/backend/infrahub/core/account.py b/backend/infrahub/core/account.py index fd7997ab37..ebc48dd109 100644 --- a/backend/infrahub/core/account.py +++ b/backend/infrahub/core/account.py @@ -2,8 +2,6 @@ from typing import TYPE_CHECKING, Optional, Tuple, Union -from infrahub.core.constants import InfrahubKind -from infrahub.core.manager import NodeManager from infrahub.core.query import Query from infrahub.core.registry import registry @@ -81,51 +79,3 @@ async def validate_token( query = await AccountTokenValidateQuery.init(db=db, branch=branch, token=token, at=at) await query.execute(db=db) return query.get_account_id(), query.get_account_role() - - -async def get_account( - account, - db: InfrahubDatabase, - branch=None, - at=None, -): - # No default value supported for now - if not account: - return None - - if hasattr(account, "schema") and account.schema.kind == InfrahubKind.ACCOUNT: - return account - - # Try to get it from the registry - # if not present in the registry, get it from the database directly - # and update the registry - if account in registry.account: - return registry.account[account] - - account_schema = registry.schema.get(name=InfrahubKind.ACCOUNT) - - obj = await NodeManager.query( - schema=account_schema, filters={account_schema.default_filter: account}, branch=branch, at=at, db=db - ) - registry.account[account] = obj - - return obj - - -def get_account_by_id(id: str): # pylint: disable=unused-argument - # No default value supported for now - # if not id: - return None - - # from .account import Account - - # if id in registry.account_id: - # return registry.account_id[id] - - # obj = Account.get(id=id) - # if not obj: - # return None - - # registry.account[obj.name.value] = obj - # registry.account_id[id] = obj - # return obj diff --git a/backend/infrahub/core/attribute.py b/backend/infrahub/core/attribute.py index ea32ed6145..3e63b4093b 100644 --- a/backend/infrahub/core/attribute.py +++ b/backend/infrahub/core/attribute.py @@ -169,6 +169,10 @@ def set_default_value(self) -> None: if self.is_enum and self.value: self.value = self.schema.convert_value_to_enum(self.value) + @staticmethod + def get_allowed_property_in_path() -> list[str]: + return ["value"] + @classmethod def validate(cls, value: Any, name: str, schema: AttributeSchema) -> bool: if value is None and schema.optional is False: @@ -486,6 +490,9 @@ async def to_graphql( elif isinstance(field, (int, bool, dict, list)): response[field_name] = field + if related_node_ids and self.is_from_profile and getattr(self, "source_id"): + related_node_ids.add(getattr(self, "source_id")) + return response def _filter_sensitive(self, value: str, filter_sensitive: bool) -> str: @@ -648,6 +655,10 @@ def validate_format(cls, value: Any, name: str, schema: AttributeSchema) -> None class IPNetwork(BaseAttribute): type = str + @staticmethod + def get_allowed_property_in_path() -> list[str]: + return ["value", "version", "binary_address"] + @property def obj(self) -> Union[ipaddress.IPv4Network, ipaddress.IPv6Network]: """Return an ipaddress interface object.""" @@ -772,6 +783,10 @@ def to_db(self) -> Dict[str, Any]: class IPHost(BaseAttribute): type = str + @staticmethod + def get_allowed_property_in_path() -> list[str]: + return ["value", "version", "binary_address"] + @property def obj(self) -> Union[ipaddress.IPv4Interface, ipaddress.IPv6Interface]: """Return the ip adress without a prefix or subnet mask.""" diff --git a/backend/infrahub/core/branch.py b/backend/infrahub/core/branch.py index a00d2465c2..048f282f7a 100644 --- a/backend/infrahub/core/branch.py +++ b/backend/infrahub/core/branch.py @@ -41,7 +41,7 @@ class Branch(StandardNode): # pylint: disable=too-many-public-methods default=True, description="Indicate if the branch should be extended to Git and if Infrahub should merge the branch in Git as part of a proposed change", ) - is_isolated: bool = False + is_isolated: bool = True schema_changed_at: Optional[str] = None schema_hash: Optional[SchemaBranchHash] = None @@ -279,7 +279,7 @@ def get_query_filter_relationships( return filters, params def get_query_filter_path( - self, at: Optional[Union[Timestamp, str]] = None, is_isolated: bool = True + self, at: Optional[Union[Timestamp, str]] = None, is_isolated: bool = True, branch_agnostic: bool = False ) -> Tuple[str, Dict]: """ Generate a CYPHER Query filter based on a path to query a part of the graph at a specific time and on a specific branch. @@ -292,10 +292,16 @@ def get_query_filter_path( There is a currently an assumption that the relationship in the path will be named 'r' """ + params: dict[str, Any] = {} at = Timestamp(at) - branches_times = self.get_branches_and_times_to_query_global(at=at.to_string(), is_isolated=is_isolated) + at_str = at.to_string() + if branch_agnostic: + filter_str = "r.from <= $time1 AND (r.to IS NULL or r.to >= $time1)" + params["time1"] = at_str + return filter_str, params + + branches_times = self.get_branches_and_times_to_query_global(at=at_str, is_isolated=is_isolated) - params: dict[str, Any] = {} for idx, (branch_name, time_to_query) in enumerate(branches_times.items()): params[f"branch{idx}"] = list(branch_name) params[f"time{idx}"] = time_to_query diff --git a/backend/infrahub/core/constants/__init__.py b/backend/infrahub/core/constants/__init__.py index fae83e697e..9f417d7c1c 100644 --- a/backend/infrahub/core/constants/__init__.py +++ b/backend/infrahub/core/constants/__init__.py @@ -7,9 +7,16 @@ from infrahub.exceptions import ValidationError from infrahub.utils import InfrahubStringEnum -from .schema import FlagProperty, NodeProperty, UpdateSupport, UpdateValidationErrorType - -__all__ = ["InfrahubKind", "FlagProperty", "NodeProperty", "UpdateSupport", "UpdateValidationErrorType"] +from .schema import FlagProperty, NodeProperty, SchemaElementPathType, UpdateSupport, UpdateValidationErrorType + +__all__ = [ + "InfrahubKind", + "FlagProperty", + "NodeProperty", + "UpdateSupport", + "UpdateValidationErrorType", + "SchemaElementPathType", +] GLOBAL_BRANCH_NAME = "-global-" @@ -29,6 +36,7 @@ "rel", "rels", "save", + "hfid", ] RESERVED_ATTR_GEN_NAMES = ["type"] diff --git a/backend/infrahub/core/constants/infrahubkind.py b/backend/infrahub/core/constants/infrahubkind.py index 23384c2b92..dc85cf82ff 100644 --- a/backend/infrahub/core/constants/infrahubkind.py +++ b/backend/infrahub/core/constants/infrahubkind.py @@ -24,7 +24,9 @@ GRAPHQLQUERYGROUP = "CoreGraphQLQueryGroup" IPNAMESPACE = "BuiltinIPNamespace" IPADDRESS = "BuiltinIPAddress" +IPADDRESSPOOL = "CoreIPAddressPool" IPPREFIX = "BuiltinIPPrefix" +IPPREFIXPOOL = "CoreIPPrefixPool" NAMESPACE = "IpamNamespace" NODE = "CoreNode" LINEAGEOWNER = "LineageOwner" @@ -34,6 +36,7 @@ PROPOSEDCHANGE = "CoreProposedChange" REFRESHTOKEN = "InternalRefreshToken" REPOSITORY = "CoreRepository" +RESOURCEPOOL = "CoreResourcePool" GENERICREPOSITORY = "CoreGenericRepository" READONLYREPOSITORY = "CoreReadOnlyRepository" REPOSITORYVALIDATOR = "CoreRepositoryValidator" diff --git a/backend/infrahub/core/constants/schema.py b/backend/infrahub/core/constants/schema.py index ad9503a0e3..fcfc79bc6c 100644 --- a/backend/infrahub/core/constants/schema.py +++ b/backend/infrahub/core/constants/schema.py @@ -1,4 +1,4 @@ -from enum import Enum +from enum import Enum, Flag, auto class FlagProperty(Enum): @@ -24,3 +24,16 @@ class UpdateValidationErrorType(Enum): VALIDATOR_FAILED = "validator_failed" MIGRATION_NOT_AVAILABLE = "migration_not_available" VALIDATOR_NOT_AVAILABLE = "validator_not_available" + + +class SchemaElementPathType(Flag): + ATTR = auto() + REL_ONE_NO_ATTR = auto() + REL_ONE_ATTR = auto() + REL_MANY_NO_ATTR = auto() + REL_MANY_ATTR = auto() + ALL_RELS = REL_ONE_NO_ATTR | REL_MANY_NO_ATTR | REL_ONE_ATTR | REL_MANY_ATTR + RELS_ATTR = REL_ONE_ATTR | REL_MANY_ATTR + RELS_NO_ATTR = REL_ONE_NO_ATTR | REL_MANY_NO_ATTR + REL_ONE = REL_ONE_NO_ATTR | REL_ONE_ATTR + REL_MANY = REL_MANY_NO_ATTR | REL_MANY_ATTR diff --git a/backend/infrahub/core/constraint/node/runner.py b/backend/infrahub/core/constraint/node/runner.py index d384297c34..f8a48f8b38 100644 --- a/backend/infrahub/core/constraint/node/runner.py +++ b/backend/infrahub/core/constraint/node/runner.py @@ -24,11 +24,14 @@ def __init__( self.relationship_manager_constraints = relationship_manager_constraints async def check(self, node: Node, field_filters: Optional[List[str]] = None) -> None: + await node.resolve_relationships(db=self.db) + for node_constraint in self.node_constraints: await node_constraint.check(node, filters=field_filters) + for relationship_name in node.get_schema().relationship_names: if field_filters and relationship_name not in field_filters: continue relationship_manager: RelationshipManager = getattr(node, relationship_name) for relationship_constraint in self.relationship_manager_constraints: - await relationship_constraint.check(relationship_manager) + await relationship_constraint.check(relm=relationship_manager) diff --git a/backend/infrahub/core/diff/branch_differ.py b/backend/infrahub/core/diff/branch_differ.py index bdcfa9c1a2..76060ed784 100644 --- a/backend/infrahub/core/diff/branch_differ.py +++ b/backend/infrahub/core/diff/branch_differ.py @@ -23,7 +23,6 @@ DiffRelationshipPropertyQuery, DiffRelationshipQuery, ) -from infrahub.core.registry import registry from infrahub.core.timestamp import Timestamp from infrahub.exceptions import ( DiffFromRequiredOnDefaultBranchError, @@ -355,7 +354,7 @@ async def get_modified_paths_graph(self) -> Dict[str, Set[ModifiedPath]]: for _, rel in rels.items(): for node_id in rel.nodes: neighbor_id = [neighbor for neighbor in rel.nodes.keys() if neighbor != node_id][0] - schema = registry.schema.get(name=rel.nodes[node_id].kind, branch=branch_name) + schema = self.db.schema.get(name=rel.nodes[node_id].kind, branch=branch_name) matching_relationship = [r for r in schema.relationships if r.identifier == rel_name] if ( matching_relationship @@ -410,7 +409,7 @@ async def get_modified_paths_graph(self) -> Dict[str, Set[ModifiedPath]]: for branch_name, entries in branch_kind_node.items(): for kind, ids in entries.items(): - schema = registry.schema.get(name=kind, branch=branch_name) + schema = self.db.schema.get(name=kind, branch=branch_name) fields = schema.generate_fields_for_display_label() query_nodes = await NodeManager.get_many(ids=ids, fields=fields, db=self.db, branch=branch_name) for node_id, node in query_nodes.items(): @@ -683,9 +682,9 @@ async def get_relationships_per_node(self) -> Dict[str, Dict[str, Dict[str, List ) for branch_name, items in rels.items(): for item in items.values(): - for sub_item in item.values(): - for node_id, _ in sub_item.nodes.items(): - rels_per_node[branch_name][node_id][sub_item.name].append(sub_item) + for rel_diff_element in item.values(): + for node_id, _ in rel_diff_element.nodes.items(): + rels_per_node[branch_name][node_id][rel_diff_element.name].append(rel_diff_element) return rels_per_node @@ -902,15 +901,14 @@ async def _calculated_diff_rels(self) -> None: self._calculated_diff_rels_at = Timestamp() - @staticmethod def parse_relationship_paths( - nodes: Dict[str, RelationshipEdgeNodeDiffElement], branch_name: str, relationship_name: str + self, nodes: Dict[str, RelationshipEdgeNodeDiffElement], branch_name: str, relationship_name: str ) -> RelationshipPath: node_ids = list(nodes.keys()) neighbor_map = {node_ids[0]: node_ids[1], node_ids[1]: node_ids[0]} relationship_paths = RelationshipPath() for relationship in nodes.values(): - schema = registry.schema.get(name=relationship.kind, branch=branch_name) + schema = self.db.schema.get(name=relationship.kind, branch=branch_name) matching_relationship = [r for r in schema.relationships if r.identifier == relationship_name] relationship_path_name = "-undefined-" if matching_relationship: diff --git a/backend/infrahub/core/diff/ipam_diff_parser.py b/backend/infrahub/core/diff/ipam_diff_parser.py index 94ade9b6aa..2b0994c70b 100644 --- a/backend/infrahub/core/diff/ipam_diff_parser.py +++ b/backend/infrahub/core/diff/ipam_diff_parser.py @@ -1,7 +1,6 @@ from dataclasses import dataclass from typing import Optional -from infrahub.core import registry from infrahub.core.constants import DiffAction, InfrahubKind from infrahub.core.constants.relationship_label import RELATIONSHIP_TO_VALUE_LABEL from infrahub.core.diff.branch_differ import BranchDiffer @@ -30,16 +29,16 @@ def __init__( self.db = db async def get_changed_ipam_node_details(self) -> list[IpamNodeDetails]: - prefix_generic_schema_source = registry.schema.get( + prefix_generic_schema_source = self.db.schema.get( InfrahubKind.IPPREFIX, branch=self.source_branch_name, duplicate=False ) - prefix_generic_schema_target = registry.schema.get( + prefix_generic_schema_target = self.db.schema.get( InfrahubKind.IPPREFIX, branch=self.target_branch_name, duplicate=False ) - address_generic_schema_source = registry.schema.get( + address_generic_schema_source = self.db.schema.get( InfrahubKind.IPADDRESS, branch=self.source_branch_name, duplicate=False ) - address_generic_schema_target = registry.schema.get( + address_generic_schema_target = self.db.schema.get( InfrahubKind.IPADDRESS, branch=self.target_branch_name, duplicate=False ) diff --git a/backend/infrahub/core/diff/payload_builder.py b/backend/infrahub/core/diff/payload_builder.py index 5d7cd54595..bc7e5519bd 100644 --- a/backend/infrahub/core/diff/payload_builder.py +++ b/backend/infrahub/core/diff/payload_builder.py @@ -46,8 +46,8 @@ async def get_display_labels_per_kind( ) -> Dict[str, str]: """Return the display_labels of a list of nodes of a specific kind.""" branch = await registry.get_branch(branch=branch_name, db=db) - schema = registry.schema.get(name=kind, branch=branch) - fields = schema.generate_fields_for_display_label() + schema_branch = db.schema.get_schema_branch(name=branch.name) + fields = schema_branch.generate_fields_for_display_label(name=kind) nodes = await NodeManager.get_many(ids=ids, fields=fields, db=db, branch=branch) return {node_id: await node.render_display_label(db=db) for node_id, node in nodes.items()} @@ -301,7 +301,7 @@ async def _process_one_node(self, node_diff: NodeDiffElement, branch_name: str) self._add_node_to_diff(node_id=node_diff_dict["id"], kind=node_diff_dict["kind"]) self._set_display_label(node_id=node_diff_dict["id"], branch=branch_name, display_label=display_label) self._set_node_action(node_id=node_diff_dict["id"], branch=branch_name, action=node_diff_dict["action"]) - schema = registry.schema.get(name=node_diff.kind, branch=node_diff.branch) + schema = self.db.schema.get(name=node_diff.kind, branch=node_diff.branch) # Extract the value from the list of properties for element in branch_diff_node.elements.values(): @@ -385,7 +385,7 @@ async def _process_one_node_relationships( if self.kinds_to_include and node_kind not in self.kinds_to_include: continue - schema = registry.schema.get(name=node_kind, branch=branch_name) + schema = self.db.schema.get(name=node_kind, branch=branch_name) rel_schema = schema.get_relationship_by_identifier(id=rel_name, raise_on_error=False) if not rel_schema: continue @@ -476,8 +476,18 @@ def extract_diff_relationship_one( changed_at = None - if len(rels) == 1: - rel = rels[0] + unique_action_rels_map: dict[DiffAction, RelationshipDiffElement] = {} + for rel in rels: + if rel.action not in unique_action_rels_map: + unique_action_rels_map[rel.action] = rel + continue + if rel.changed_at is None or unique_action_rels_map[rel.action].changed_at is None: + continue + if rel.changed_at > unique_action_rels_map[rel.action].changed_at: + unique_action_rels_map[rel.action] = rel + + if len(unique_action_rels_map) == 1: + _, rel = unique_action_rels_map.popitem() if rel.changed_at: changed_at = rel.changed_at.to_string() @@ -508,9 +518,12 @@ def extract_diff_relationship_one( action=rel.action, ) - if len(rels) == 2: - rel_added = [rel for rel in rels if rel.action.value == "added"][0] - rel_removed = [rel for rel in rels if rel.action.value == "removed"][0] + if len(unique_action_rels_map) == 2 and set(unique_action_rels_map.keys()) == { + DiffAction.ADDED, + DiffAction.REMOVED, + }: + rel_added = unique_action_rels_map[DiffAction.ADDED] + rel_removed = unique_action_rels_map[DiffAction.REMOVED] peer_added = dict([rel_node for rel_node in rel_added.nodes.values() if rel_node.id != node_id][0]) peer_added["display_label"] = display_labels.get(peer_added.get("id", None), "") @@ -530,10 +543,10 @@ def extract_diff_relationship_one( action=DiffAction.UPDATED, ) - if len(rels) > 2: - log.warning( - f"extract_diff_relationship_one: More than 2 relationships received, need to investigate. Node ID {node_id}, Name: {name}" - ) + errors = {r.id: r.action.value for r in rels} + log.warning( + f"extract_diff_relationship_one: Invalid relationship combination received: {errors}, need to investigate. {node_id=}, {name=}" + ) return None diff --git a/backend/infrahub/core/enums.py b/backend/infrahub/core/enums.py index 541717c893..7baa582d81 100644 --- a/backend/infrahub/core/enums.py +++ b/backend/infrahub/core/enums.py @@ -8,6 +8,10 @@ def generate_python_enum(name: str, options: List[Any]) -> Type[enum.Enum]: main_attrs = {} for option in options: - enum_name = "_".join(re.findall(ENUM_NAME_REGEX, option)).upper() + if isinstance(option, int): + enum_name = str(option) + else: + enum_name = "_".join(re.findall(ENUM_NAME_REGEX, option)).upper() + main_attrs[enum_name] = option return enum.Enum(name, main_attrs) # type: ignore[return-value] diff --git a/backend/infrahub/core/graph/__init__.py b/backend/infrahub/core/graph/__init__.py index eea35e9f19..f88e77fa9d 100644 --- a/backend/infrahub/core/graph/__init__.py +++ b/backend/infrahub/core/graph/__init__.py @@ -1 +1 @@ -GRAPH_VERSION = 7 +GRAPH_VERSION = 8 diff --git a/backend/infrahub/core/initialization.py b/backend/infrahub/core/initialization.py index c7e5e0652b..6f38832b67 100644 --- a/backend/infrahub/core/initialization.py +++ b/backend/infrahub/core/initialization.py @@ -1,12 +1,15 @@ from typing import List, Optional +from uuid import uuid4 from infrahub import config, lock from infrahub.core import registry from infrahub.core.branch import Branch -from infrahub.core.constants import DEFAULT_IP_NAMESPACE, GLOBAL_BRANCH_NAME, InfrahubKind +from infrahub.core.constants import DEFAULT_IP_NAMESPACE, GLOBAL_BRANCH_NAME, AccountRole, InfrahubKind from infrahub.core.graph import GRAPH_VERSION from infrahub.core.node import Node from infrahub.core.node.ipam import BuiltinIPPrefix +from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool from infrahub.core.root import Root from infrahub.core.schema import SchemaRoot, core_models, internal_schema from infrahub.core.schema_manager import SchemaManager @@ -73,7 +76,9 @@ async def initialize_registry(db: InfrahubDatabase, initialize: bool = False) -> # Load internal models into the registry # --------------------------------------------------- registry.node["Node"] = Node - registry.node["BuiltinIPPrefix"] = BuiltinIPPrefix + registry.node[InfrahubKind.IPPREFIX] = BuiltinIPPrefix + registry.node[InfrahubKind.IPADDRESSPOOL] = CoreIPAddressPool + registry.node[InfrahubKind.IPPREFIXPOOL] = CoreIPPrefixPool async def initialization(db: InfrahubDatabase) -> None: @@ -189,7 +194,7 @@ async def create_global_branch(db: InfrahubDatabase) -> Branch: async def create_branch( - branch_name: str, db: InfrahubDatabase, description: str = "", isolated: bool = False, at: Optional[str] = None + branch_name: str, db: InfrahubDatabase, description: str = "", isolated: bool = True, at: Optional[str] = None ) -> Branch: """Create a new Branch, currently all the branches are based on Main @@ -227,7 +232,7 @@ async def create_account( password: Optional[str] = None, token_value: Optional[str] = None, ) -> Node: - token_schema = registry.schema.get_node_schema(name=InfrahubKind.ACCOUNTTOKEN) + token_schema = db.schema.get_node_schema(name=InfrahubKind.ACCOUNTTOKEN) obj = await Node.init(db=db, schema=InfrahubKind.ACCOUNT) await obj.new( db=db, @@ -292,10 +297,21 @@ async def first_time_initialization(db: InfrahubDatabase) -> None: await create_account( db=db, name="admin", - password=config.SETTINGS.security.initial_admin_password, - token_value=config.SETTINGS.security.initial_admin_token, + password=config.SETTINGS.initial.admin_password, + token_value=config.SETTINGS.initial.admin_token, ) + if config.SETTINGS.initial.create_agent_user: + password = config.SETTINGS.initial.agent_password or str(uuid4()) + + await create_account( + db=db, + name="agent", + password=password, + role=AccountRole.READ_WRITE.value, + token_value=config.SETTINGS.initial.agent_token, + ) + # -------------------------------------------------- # Create Default IPAM Namespace # -------------------------------------------------- diff --git a/backend/infrahub/core/integrity/object_conflict/conflict_recorder.py b/backend/infrahub/core/integrity/object_conflict/conflict_recorder.py index 36b70e6823..7eb82fc5a2 100644 --- a/backend/infrahub/core/integrity/object_conflict/conflict_recorder.py +++ b/backend/infrahub/core/integrity/object_conflict/conflict_recorder.py @@ -18,7 +18,7 @@ def __init__(self, db: InfrahubDatabase, validator_kind: str, validator_label: s async def record_conflicts(self, proposed_change_id: str, conflicts: List[ObjectConflict]) -> None: proposed_change = await NodeManager.get_one_by_id_or_default_filter( - id=proposed_change_id, schema_name=InfrahubKind.PROPOSEDCHANGE, db=self.db + id=proposed_change_id, kind=InfrahubKind.PROPOSEDCHANGE, db=self.db ) validator = await self.get_or_create_validator(proposed_change) await self.initialize_validator(validator) diff --git a/backend/infrahub/core/ipam/constants.py b/backend/infrahub/core/ipam/constants.py index 824089281c..5f40d400ed 100644 --- a/backend/infrahub/core/ipam/constants.py +++ b/backend/infrahub/core/ipam/constants.py @@ -1,6 +1,12 @@ import ipaddress +from enum import Enum from typing import Union IPNetworkType = Union[ipaddress.IPv6Network, ipaddress.IPv4Network] IPAddressType = Union[ipaddress.IPv6Interface, ipaddress.IPv4Interface] AllIPTypes = Union[IPNetworkType, IPAddressType] + + +class PrefixMemberType(Enum): + PREFIX = "prefix" + ADDRESS = "address" diff --git a/backend/infrahub/core/ipam/reconciler.py b/backend/infrahub/core/ipam/reconciler.py index d11ebc99f2..f20aa0789b 100644 --- a/backend/infrahub/core/ipam/reconciler.py +++ b/backend/infrahub/core/ipam/reconciler.py @@ -72,9 +72,9 @@ async def _get_child_uuids(self, db: InfrahubDatabase, node: Optional[Node]) -> if not node: return set() child_uuids = set() - child_prefix_rels = await node.children.get_relationships(db=db) # type: ignore[attr-defined] + child_prefix_rels = await node.children.get_relationships(db=db, force_refresh=False) # type: ignore[attr-defined] child_uuids |= {cpr.get_peer_id() for cpr in child_prefix_rels} - child_address_rels = await node.ip_addresses.get_relationships(db=db) # type: ignore[attr-defined] + child_address_rels = await node.ip_addresses.get_relationships(db=db, force_refresh=False) # type: ignore[attr-defined] child_uuids |= {car.get_peer_id() for car in child_address_rels} return child_uuids diff --git a/backend/infrahub/core/ipam/size.py b/backend/infrahub/core/ipam/size.py new file mode 100644 index 0000000000..d5ab70e8ae --- /dev/null +++ b/backend/infrahub/core/ipam/size.py @@ -0,0 +1,18 @@ +from infrahub.core.node import Node + +from .constants import PrefixMemberType + + +def get_prefix_space(ip_prefix: Node) -> int: + prefix_space = ip_prefix.prefix.num_addresses # type: ignore[attr-defined] + + # Non-RFC3021 subnet + if ( + ip_prefix.member_type.value == PrefixMemberType.ADDRESS.value # type: ignore[attr-defined] + and ip_prefix.prefix.version == 4 # type: ignore[attr-defined] + and ip_prefix.prefix.prefixlen < 31 # type: ignore[attr-defined] + and not ip_prefix.is_pool.value # type: ignore[attr-defined] + ): + prefix_space -= 2 + + return prefix_space diff --git a/backend/infrahub/core/ipam/utilization.py b/backend/infrahub/core/ipam/utilization.py new file mode 100644 index 0000000000..7b48ce9cf4 --- /dev/null +++ b/backend/infrahub/core/ipam/utilization.py @@ -0,0 +1,151 @@ +from dataclasses import dataclass +from typing import Optional, Union + +from infrahub.core.constants import InfrahubKind +from infrahub.core.node import Node +from infrahub.core.query.ipam import IPPrefixUtilization +from infrahub.core.timestamp import Timestamp +from infrahub.database import InfrahubDatabase + +from .constants import PrefixMemberType +from .size import get_prefix_space + + +@dataclass +class PrefixChildDetails: + child_type: PrefixMemberType + prefixlen: int + ip_value: str + + +class PrefixUtilizationGetter: + def __init__( + self, db: InfrahubDatabase, ip_prefixes: list[Node], at: Optional[Union[Timestamp, str]] = None + ) -> None: + self.db = db + self.ip_prefixes = ip_prefixes + self.at = at + self._has_data = False + self._results_by_prefix_id: dict[str, dict[str, list[PrefixChildDetails]]] = {} + + async def _fetch_data(self) -> None: + if self._has_data is False: + await self._run_and_parse_query() + self._has_data = True + + async def _run_and_parse_query(self) -> None: + self._results_by_prefix_id = {} + query = await IPPrefixUtilization.init(db=self.db, at=self.at, ip_prefixes=self.ip_prefixes) + await query.execute(db=self.db) + + for result in query.get_results(): + prefix_node = result.get_node("pfx") + prefix_id = str(prefix_node.get("uuid")) + branch_name = str(result.get("branch")) + child_node = result.get_node("child") + if InfrahubKind.IPADDRESS in child_node.labels: + child_type = PrefixMemberType.ADDRESS + else: + child_type = PrefixMemberType.PREFIX + child_value_node = result.get_node("av") + child_prefixlen = child_value_node.get("prefixlen") + child_ip_value = child_value_node.get("value") + + if prefix_id not in self._results_by_prefix_id: + self._results_by_prefix_id[prefix_id] = {} + if branch_name not in self._results_by_prefix_id[prefix_id]: + self._results_by_prefix_id[prefix_id][branch_name] = [] + self._results_by_prefix_id[prefix_id][branch_name].append( + PrefixChildDetails(child_type=child_type, prefixlen=child_prefixlen, ip_value=child_ip_value) + ) + + async def get_children( + self, + ip_prefixes: Optional[list[Node]] = None, + prefix_member_type: Optional[PrefixMemberType] = None, + branch_names: Optional[list[str]] = None, + ) -> list[PrefixChildDetails]: + await self._fetch_data() + prefix_child_details_list: list[PrefixChildDetails] = [] + if ip_prefixes is None: + ip_prefixes = self.ip_prefixes + prefix_ids = {prefix.get_id() for prefix in ip_prefixes} + prefix_ids &= set(self._results_by_prefix_id.keys()) + if not prefix_ids: + return prefix_child_details_list + for prefix_id in prefix_ids: + child_details_by_branch = self._results_by_prefix_id[prefix_id] + branch_names_to_check = branch_names if branch_names else list(child_details_by_branch.keys()) + for branch_name in branch_names_to_check: + for child_details in child_details_by_branch.get(branch_name, []): + if prefix_member_type and child_details.child_type != prefix_member_type: + continue + prefix_child_details_list.append(child_details) + return prefix_child_details_list + + async def get_num_children_in_use( + self, + ip_prefixes: Optional[list[Node]] = None, + prefix_member_type: Optional[PrefixMemberType] = None, + branch_names: Optional[list[str]] = None, + ) -> int: + children = await self.get_children( + ip_prefixes=ip_prefixes, prefix_member_type=prefix_member_type, branch_names=branch_names + ) + return len(children) + + async def _get_prefix_use_fraction( + self, ip_prefixes: Optional[list[Node]] = None, branch_names: Optional[list[str]] = None + ) -> tuple[int, int]: + total_prefix_space = 0 + total_used_space = 0 + if ip_prefixes is None: + ip_prefixes = self.ip_prefixes + for ip_prefix in ip_prefixes: + total_prefix_space += get_prefix_space(ip_prefix=ip_prefix) + max_prefixlen = ip_prefix.prefix.obj.max_prefixlen # type: ignore[attr-defined] + children = await self.get_children( + ip_prefixes=[ip_prefix], prefix_member_type=PrefixMemberType.PREFIX, branch_names=branch_names + ) + for child in children: + total_used_space += 2 ** (max_prefixlen - child.prefixlen) + return total_used_space, total_prefix_space + + async def _get_address_use_fraction( + self, ip_prefixes: Optional[list[Node]] = None, branch_names: Optional[list[str]] = None + ) -> tuple[int, int]: + total_prefix_space = 0 + if ip_prefixes is None: + ip_prefixes = self.ip_prefixes + for ip_prefix in ip_prefixes: + total_prefix_space += get_prefix_space(ip_prefix=ip_prefix) + total_used_space = await self.get_num_children_in_use( + ip_prefixes=ip_prefixes, prefix_member_type=PrefixMemberType.ADDRESS, branch_names=branch_names + ) + return total_used_space, total_prefix_space + + async def get_use_percentage( + self, ip_prefixes: Optional[list[Node]] = None, branch_names: Optional[list[str]] = None + ) -> float: + grand_total_used, grand_total_space = 0, 0 + address_prefixes, prefix_prefixes = [], [] + if ip_prefixes is None: + ip_prefixes = self.ip_prefixes + for ip_prefix in ip_prefixes: + if ip_prefix.member_type.value == PrefixMemberType.ADDRESS.value: # type: ignore[union-attr,attr-defined] + address_prefixes.append(ip_prefix) + else: + prefix_prefixes.append(ip_prefix) + if address_prefixes: + address_total_used, address_total_space = await self._get_address_use_fraction( + ip_prefixes=address_prefixes, branch_names=branch_names + ) + grand_total_used += address_total_used + grand_total_space += address_total_space + if prefix_prefixes: + prefix_total_used, prefix_total_space = await self._get_prefix_use_fraction( + ip_prefixes=prefix_prefixes, branch_names=branch_names + ) + grand_total_used += prefix_total_used + grand_total_space += prefix_total_space + return (grand_total_used / grand_total_space) * 100 diff --git a/backend/infrahub/core/manager.py b/backend/infrahub/core/manager.py index 50a1f4880e..84e856abbc 100644 --- a/backend/infrahub/core/manager.py +++ b/backend/infrahub/core/manager.py @@ -1,9 +1,9 @@ from __future__ import annotations from functools import reduce -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, Union, overload -from infrahub_sdk.utils import deep_merge_dict +from infrahub_sdk.utils import deep_merge_dict, is_valid_uuid from infrahub.core.node import Node from infrahub.core.node.delete_validator import NodeDeleteValidator @@ -24,7 +24,7 @@ from infrahub.core.schema import GenericSchema, NodeSchema, ProfileSchema, RelationshipSchema from infrahub.core.timestamp import Timestamp from infrahub.dependencies.registry import get_component_registry -from infrahub.exceptions import NodeNotFoundError, SchemaNotFoundError +from infrahub.exceptions import NodeNotFoundError, ProcessingError, SchemaNotFoundError if TYPE_CHECKING: from infrahub.core.branch import Branch @@ -143,7 +143,7 @@ async def query( at = Timestamp(at) if isinstance(schema, str): - schema = registry.schema.get(name=schema, branch=branch.name) + schema = db.schema.get(name=schema, branch=branch.name) elif not isinstance(schema, (NodeSchema, GenericSchema, ProfileSchema)): raise ValueError(f"Invalid schema provided {schema}") @@ -161,10 +161,17 @@ async def query( await query.execute(db=db) node_ids = query.get_node_ids() - # if display_label has been requested we need to ensure we are querying the right fields - if fields and "display_label" in fields and schema.display_labels: - display_label_fields = schema.generate_fields_for_display_label() - fields = deep_merge_dict(fields, display_label_fields) + # if display_label or hfid has been requested we need to ensure we are querying the right fields + if fields and "display_label" in fields: + schema_branch = db.schema.get_schema_branch(name=branch.name) + display_label_fields = schema_branch.generate_fields_for_display_label(name=schema.kind) + if display_label_fields: + fields = deep_merge_dict(dicta=fields, dictb=display_label_fields) + + if fields and "hfid" in fields and schema.human_friendly_id: + hfid_fields = schema.generate_fields_for_hfid() + if hfid_fields: + fields = deep_merge_dict(dicta=fields, dictb=hfid_fields) response = await cls.get_many( ids=node_ids, @@ -184,7 +191,7 @@ async def query( async def count( cls, db: InfrahubDatabase, - schema: NodeSchema, + schema: Union[NodeSchema, GenericSchema, ProfileSchema, str], filters: Optional[dict] = None, at: Optional[Union[Timestamp, str]] = None, branch: Optional[Union[Branch, str]] = None, @@ -206,6 +213,11 @@ async def count( branch = await registry.get_branch(branch=branch, db=db) at = Timestamp(at) + if isinstance(schema, str): + schema = db.schema.get(name=schema, branch=branch.name) + elif not isinstance(schema, (NodeSchema, GenericSchema, ProfileSchema)): + raise ValueError(f"Invalid schema provided {schema}") + query = await NodeGetListQuery.init( db=db, schema=schema, branch=branch, filters=filters, at=at, partial_match=partial_match ) @@ -243,8 +255,8 @@ async def query_peers( fields: Optional[dict] = None, offset: Optional[int] = None, limit: Optional[int] = None, - at: Union[Timestamp, str] = None, - branch: Union[Branch, str] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, ) -> List[Relationship]: branch = await registry.get_branch(branch=branch, db=db) at = Timestamp(at) @@ -270,10 +282,11 @@ async def query_peers( # if display_label has been requested we need to ensure we are querying the right fields if fields and "display_label" in fields: - peer_schema = schema.get_peer_schema(branch=branch) - if peer_schema.display_labels: - display_label_fields = peer_schema.generate_fields_for_display_label() - fields = deep_merge_dict(fields, display_label_fields) + peer_schema = schema.get_peer_schema(db=db, branch=branch) + schema_branch = db.schema.get_schema_branch(name=branch.name) + display_label_fields = schema_branch.generate_fields_for_display_label(name=peer_schema.kind) + if display_label_fields: + fields = deep_merge_dict(dicta=fields, dictb=display_label_fields) return [ await Relationship(schema=schema, branch=branch, at=at, node_id=peer.source_id).load( @@ -323,8 +336,8 @@ async def query_hierarchy( fields: Optional[dict] = None, offset: Optional[int] = None, limit: Optional[int] = None, - at: Union[Timestamp, str] = None, - branch: Union[Branch, str] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, ) -> Dict[str, Node]: branch = await registry.get_branch(branch=branch, db=db) at = Timestamp(at) @@ -347,38 +360,120 @@ async def query_hierarchy( if not peers_ids: return [] - hierarchy_schema = node_schema.get_hierarchy_schema() + hierarchy_schema = node_schema.get_hierarchy_schema(db=db, branch=branch) # if display_label has been requested we need to ensure we are querying the right fields if fields and "display_label" in fields: - if hierarchy_schema.display_labels: - display_label_fields = hierarchy_schema.generate_fields_for_display_label() - fields = deep_merge_dict(fields, display_label_fields) + schema_branch = db.schema.get_schema_branch(name=branch.name) + display_label_fields = schema_branch.generate_fields_for_display_label(name=hierarchy_schema.kind) + if display_label_fields: + fields = deep_merge_dict(dicta=fields, dictb=display_label_fields) return await cls.get_many( db=db, ids=peers_ids, fields=fields, at=at, branch=branch, include_owner=True, include_source=True ) + @classmethod + async def find_object( + cls, + db: InfrahubDatabase, + kind: str, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + hfid: Optional[list[str]] = None, + ) -> Node: + if not id and not hfid: + raise ProcessingError(message="either id or hfid must be provided.") + + if id and is_valid_uuid(id): + return await cls.get_one( + db=db, + kind=kind, + id=id, + branch=branch, + at=at, + include_owner=True, + include_source=True, + ) + + if hfid: + return await cls.get_one_by_hfid( + db=db, + kind=kind, + hfid=hfid, + branch=branch, + at=at, + include_owner=True, + include_source=True, + ) + + return await cls.get_one_by_default_filter( + db=db, + kind=kind, + id=id, + branch=branch, + at=at, + include_owner=True, + include_source=True, + raise_on_error=True, + ) + + @overload @classmethod async def get_one_by_default_filter( cls, db: InfrahubDatabase, id: str, - schema_name: str, + kind: str, fields: Optional[dict] = None, - at: Union[Timestamp, str] = None, - branch: Union[Branch, str] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, include_source: bool = False, include_owner: bool = False, prefetch_relationships: bool = False, account=None, - ) -> Node: + raise_on_error: Literal[False] = False, + ) -> Optional[Node]: ... + + @overload + @classmethod + async def get_one_by_default_filter( + cls, + db: InfrahubDatabase, + id: str, + kind: str, + fields: Optional[dict] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, + include_source: bool = False, + include_owner: bool = False, + prefetch_relationships: bool = False, + account=None, + raise_on_error: Literal[True] = True, + ) -> Node: ... + + @classmethod + async def get_one_by_default_filter( + cls, + db: InfrahubDatabase, + id: str, + kind: str, + fields: Optional[dict] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, + include_source: bool = False, + include_owner: bool = False, + prefetch_relationships: bool = False, + account=None, + raise_on_error: bool = False, + ) -> Optional[Node]: branch = await registry.get_branch(branch=branch, db=db) at = Timestamp(at) - node_schema = registry.schema.get(name=schema_name, branch=branch) + node_schema = db.schema.get(name=kind, branch=branch) if not node_schema.default_filter: - raise NodeNotFoundError(branch_name=branch.name, node_type=schema_name, identifier=id) + raise NodeNotFoundError(branch_name=branch.name, node_type=kind, identifier=id) items = await NodeManager.query( db=db, @@ -397,11 +492,69 @@ async def get_one_by_default_filter( if len(items) > 1: raise NodeNotFoundError( branch_name=branch.name, - node_type=schema_name, + node_type=kind, identifier=id, message=f"Unable to find node {id!r}, {len(items)} nodes returned, expected 1", ) + if items: + return items[0] + if not raise_on_error: + return None + + raise NodeNotFoundError( + branch_name=branch.name, + node_type=kind, + identifier=id, + ) + + @classmethod + async def get_one_by_hfid( + cls, + db: InfrahubDatabase, + hfid: list[str], + kind: str, + fields: Optional[dict] = None, + at: Optional[Union[Timestamp, str]] = None, + branch: Optional[Union[Branch, str]] = None, + include_source: bool = False, + include_owner: bool = False, + prefetch_relationships: bool = False, + account=None, + ) -> Node: + branch = await registry.get_branch(branch=branch, db=db) + at = Timestamp(at) + + hfid_str = " :: ".join(hfid) + node_schema = db.schema.get(name=kind, branch=branch) + + if not node_schema.human_friendly_id or len(node_schema.human_friendly_id) != len(hfid): + raise NodeNotFoundError(branch_name=branch.name, node_type=kind, identifier=hfid_str) + + filters = {node_schema.human_friendly_id[idx]: item for idx, item in enumerate(hfid)} + + items = await NodeManager.query( + db=db, + schema=node_schema, + fields=fields, + limit=2, + filters=filters, + branch=branch, + at=at, + include_owner=include_owner, + include_source=include_source, + prefetch_relationships=prefetch_relationships, + account=account, + ) + + if len(items) > 1: + raise NodeNotFoundError( + branch_name=branch.name, + node_type=kind, + identifier=hfid_str, + message=f"Unable to find node {hfid_str!r}, {len(items)} nodes returned, expected 1", + ) + return items[0] if items else None @classmethod @@ -409,9 +562,9 @@ async def get_one_by_id_or_default_filter( cls, db: InfrahubDatabase, id: str, - schema_name: str, + kind: str, fields: Optional[dict] = None, - at: Union[Timestamp, str] = None, + at: Optional[Union[Timestamp, str]] = None, branch: Union[Branch, str] = None, include_source: bool = False, include_owner: bool = False, @@ -438,7 +591,7 @@ async def get_one_by_id_or_default_filter( node = await cls.get_one_by_default_filter( db=db, id=id, - schema_name=schema_name, + kind=kind, fields=fields, at=at, branch=branch, @@ -448,7 +601,7 @@ async def get_one_by_id_or_default_filter( account=account, ) if not node: - raise NodeNotFoundError(branch_name=branch.name, node_type=schema_name, identifier=id) + raise NodeNotFoundError(branch_name=branch.name, node_type=kind, identifier=id) return node @classmethod @@ -458,7 +611,7 @@ async def get_one( db: InfrahubDatabase, fields: Optional[dict] = None, at: Optional[Union[Timestamp, str]] = None, - branch: Union[Branch, str] = None, + branch: Optional[Union[Branch, str]] = None, include_source: bool = False, include_owner: bool = False, prefetch_relationships: bool = False, @@ -486,7 +639,16 @@ async def get_one( node = result[id] node_schema = node.get_schema() + # Temporary list of exception to the validation of the kind + kind_validation_exceptions = [ + ("CoreChangeThread", "CoreObjectThread"), # issue/3318 + ] + if kind and (node_schema.kind != kind and kind not in node_schema.inherit_from): + for item in kind_validation_exceptions: + if item[0] == kind and item[1] == node.get_kind(): + return node + raise NodeNotFoundError( branch_name=branch.name, node_type=kind, @@ -508,6 +670,7 @@ async def get_many( # pylint: disable=too-many-branches,too-many-statements include_owner: bool = False, prefetch_relationships: bool = False, account=None, + branch_agnostic: bool = False, ) -> Dict[str, Node]: """Return a list of nodes based on their IDs.""" @@ -515,11 +678,11 @@ async def get_many( # pylint: disable=too-many-branches,too-many-statements at = Timestamp(at) # Query all nodes - query = await NodeListGetInfoQuery.init(db=db, ids=ids, branch=branch, account=account, at=at) + query = await NodeListGetInfoQuery.init( + db=db, ids=ids, branch=branch, account=account, at=at, branch_agnostic=branch_agnostic + ) await query.execute(db=db) - nodes_info_by_id: Dict[str, NodeToProcess] = { - node.node_uuid: node async for node in query.get_nodes(duplicate=False) - } + nodes_info_by_id: Dict[str, NodeToProcess] = {node.node_uuid: node async for node in query.get_nodes(db=db)} profile_ids_by_node_id = query.get_profile_ids_by_node_id() all_profile_ids = reduce( lambda all_ids, these_ids: all_ids | set(these_ids), profile_ids_by_node_id.values(), set() @@ -541,6 +704,7 @@ async def get_many( # pylint: disable=too-many-branches,too-many-statements include_owner=include_owner, account=account, at=at, + branch_agnostic=branch_agnostic, ) await query.execute(db=db) all_node_attributes = query.get_attributes_group_by_node() @@ -560,7 +724,9 @@ async def get_many( # pylint: disable=too-many-branches,too-many-statements peers_per_node = None peers = None if prefetch_relationships: - query = await NodeListGetRelationshipsQuery.init(db=db, ids=ids, branch=branch, at=at) + query = await NodeListGetRelationshipsQuery.init( + db=db, ids=ids, branch=branch, at=at, branch_agnostic=branch_agnostic + ) await query.execute(db=db) peers_per_node = query.get_peers_group_by_node() peer_ids = [] diff --git a/backend/infrahub/core/migrations/graph/__init__.py b/backend/infrahub/core/migrations/graph/__init__.py index a86be3373c..928a163516 100644 --- a/backend/infrahub/core/migrations/graph/__init__.py +++ b/backend/infrahub/core/migrations/graph/__init__.py @@ -9,6 +9,7 @@ from .m005_add_rel_read_only import Migration005 from .m006_add_rel_on_delete import Migration006 from .m007_add_rel_allow_override import Migration007 +from .m008_add_human_friendly_id import Migration008 if TYPE_CHECKING: from infrahub.core.root import Root @@ -23,6 +24,7 @@ Migration005, Migration006, Migration007, + Migration008, ] diff --git a/backend/infrahub/core/migrations/graph/m008_add_human_friendly_id.py b/backend/infrahub/core/migrations/graph/m008_add_human_friendly_id.py new file mode 100644 index 0000000000..2b9a8e05f9 --- /dev/null +++ b/backend/infrahub/core/migrations/graph/m008_add_human_friendly_id.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict + +from typing_extensions import Self + +from infrahub.core.constants import SchemaPathType +from infrahub.core.migrations.shared import MigrationResult +from infrahub.core.path import SchemaPath + +from ..schema.node_attribute_add import NodeAttributeAddMigration +from ..shared import InternalSchemaMigration + +if TYPE_CHECKING: + from infrahub.database import InfrahubDatabase + + +class Migration008(InternalSchemaMigration): + name: str = "008_node_add_human_friendly_id" + minimum_version: int = 7 + + @classmethod + def init(cls, *args: Any, **kwargs: Dict[str, Any]) -> Self: + internal_schema = cls.get_internal_schema() + schema_node = internal_schema.get_node(name="SchemaNode") + schema_generic = internal_schema.get_node(name="SchemaGeneric") + + migrations = [ + NodeAttributeAddMigration( + new_node_schema=schema_node, + previous_node_schema=schema_node, + schema_path=SchemaPath( + schema_kind="SchemaNode", path_type=SchemaPathType.ATTRIBUTE, field_name="human_friendly_id" + ), + ), + NodeAttributeAddMigration( + new_node_schema=schema_generic, + previous_node_schema=schema_generic, + schema_path=SchemaPath( + schema_kind="SchemaGeneric", path_type=SchemaPathType.ATTRIBUTE, field_name="human_friendly_id" + ), + ), + ] + return cls(*args, migrations=migrations, **kwargs) # type: ignore[arg-type] + + async def validate_migration(self, db: InfrahubDatabase) -> MigrationResult: + result = MigrationResult() + return result diff --git a/backend/infrahub/core/node/__init__.py b/backend/infrahub/core/node/__init__.py index 9cfc7da040..efe4be9f62 100644 --- a/backend/infrahub/core/node/__init__.py +++ b/backend/infrahub/core/node/__init__.py @@ -6,7 +6,7 @@ from infrahub_sdk.utils import is_valid_uuid from infrahub.core import registry -from infrahub.core.constants import BranchSupportType, InfrahubKind +from infrahub.core.constants import BranchSupportType, InfrahubKind, RelationshipCardinality from infrahub.core.query.node import ( NodeCheckIDQuery, NodeCreateAllQuery, @@ -70,6 +70,49 @@ def get_id(self) -> str: raise InitializationError("The node has not been saved yet and doesn't have an id") + async def get_hfid(self, db: InfrahubDatabase, include_kind: bool = False) -> Optional[list[str]]: + """Return the Human friendly id of the node.""" + if not self._schema.human_friendly_id: + return None + + hfid = [await self.get_path_value(db=db, path=item) for item in self._schema.human_friendly_id] + if include_kind: + return [self.get_kind()] + hfid + return hfid + + async def get_hfid_as_string(self, db: InfrahubDatabase, include_kind: bool = False) -> Optional[str]: + """Return the Human friendly id of the node in string format separated with a dunder (__) .""" + hfid = await self.get_hfid(db=db, include_kind=include_kind) + if not hfid: + return None + return "__".join(hfid) + + async def get_path_value(self, db: InfrahubDatabase, path: str) -> str: + schema_path = self._schema.parse_schema_path( + path=path, schema=registry.schema.get_schema_branch(name=self._branch.name) + ) + + if not schema_path.has_property: + raise ValueError(f"Unable to retrive the value of a path without property {path!r} on {self.get_kind()!r}") + + if ( + schema_path.is_type_relationship + and schema_path.relationship_schema.cardinality == RelationshipCardinality.MANY + ): + raise ValueError( + f"Unable to retrive the value of a path on a relationship of cardinality many {path!r} on {self.get_kind()!r}" + ) + + if schema_path.is_type_attribute: + attr = getattr(self, schema_path.attribute_schema.name) + return getattr(attr, schema_path.attribute_property_name) + + if schema_path.is_type_relationship: + relm: RelationshipManager = getattr(self, schema_path.relationship_schema.name) + node = await relm.get_peer(db=db) + attr = getattr(node, schema_path.attribute_schema.name) + return getattr(attr, schema_path.attribute_property_name) + def get_labels(self) -> List[str]: """Return the labels for this object, composed of the kind and the list of Generic this object is inheriting from.""" @@ -145,7 +188,7 @@ async def init( attrs["schema"] = schema elif isinstance(schema, str): # TODO need to raise a proper exception for this, right now it will raise a generic ValueError - attrs["schema"] = registry.schema.get(name=schema, branch=branch) + attrs["schema"] = db.schema.get(name=schema, branch=branch) else: raise ValueError(f"Invalid schema provided {type(schema)}, expected NodeSchema or ProfileSchema") @@ -307,6 +350,11 @@ async def new(self, db: InfrahubDatabase, id: Optional[str] = None, **kwargs) -> return self + async def resolve_relationships(self, db: InfrahubDatabase) -> None: + for name in self._relationships: + relm: RelationshipManager = getattr(self, name) + await relm.resolve(db=db) + async def load( self, db: InfrahubDatabase, @@ -454,6 +502,10 @@ async def to_graphql( response[field_name] = await self.render_display_label(db=db) continue + if field_name == "hfid": + response[field_name] = await self.get_hfid(db=db) + continue + if field_name == "_updated_at": if self._updated_at: response[field_name] = await self._updated_at.to_graphql() @@ -498,7 +550,7 @@ async def from_graphql(self, data: dict, db: InfrahubDatabase) -> bool: return changed - async def render_display_label(self, db: Optional[InfrahubDatabase] = None): # pylint: disable=unused-argument + async def render_display_label(self, db: Optional[InfrahubDatabase] = None) -> str: # pylint: disable=unused-argument if not self._schema.display_labels: return repr(self) diff --git a/backend/infrahub/core/node/constraints/attribute_uniqueness.py b/backend/infrahub/core/node/constraints/attribute_uniqueness.py index ac8ff47f92..e6b66f757e 100644 --- a/backend/infrahub/core/node/constraints/attribute_uniqueness.py +++ b/backend/infrahub/core/node/constraints/attribute_uniqueness.py @@ -29,7 +29,7 @@ async def check(self, node: Node, at: Optional[Timestamp] = None, filters: Optio attr = getattr(node, unique_attr.name) if unique_attr.inherited: for generic_parent_schema_name in node_schema.inherit_from: - generic_parent_schema = registry.schema.get(generic_parent_schema_name, branch=self.branch) + generic_parent_schema = self.db.schema.get(generic_parent_schema_name, branch=self.branch) parent_attr = generic_parent_schema.get_attribute_or_none(unique_attr.name) if parent_attr is None: continue diff --git a/backend/infrahub/core/node/constraints/grouped_uniqueness.py b/backend/infrahub/core/node/constraints/grouped_uniqueness.py index ab059c7427..addb856224 100644 --- a/backend/infrahub/core/node/constraints/grouped_uniqueness.py +++ b/backend/infrahub/core/node/constraints/grouped_uniqueness.py @@ -142,7 +142,8 @@ async def _check_one_schema( at: Optional[Timestamp] = None, filters: Optional[List[str]] = None, ) -> None: - path_groups = node_schema.get_unique_constraint_schema_attribute_paths(branch=self.branch) + schema_branch = self.db.schema.get_schema_branch(name=self.branch.name) + path_groups = node_schema.get_unique_constraint_schema_attribute_paths(schema_branch=schema_branch) query_request = self._build_query_request( updated_node=node, node_schema=node_schema, path_groups=path_groups, filters=filters ) diff --git a/backend/infrahub/core/node/ipam.py b/backend/infrahub/core/node/ipam.py index 7638731793..971bbed3ae 100644 --- a/backend/infrahub/core/node/ipam.py +++ b/backend/infrahub/core/node/ipam.py @@ -2,7 +2,9 @@ from typing import TYPE_CHECKING, Optional -from infrahub.core.query.ipam import get_utilization +from infrahub.core.ipam.size import get_prefix_space +from infrahub.core.ipam.utilization import PrefixUtilizationGetter +from infrahub.core.manager import NodeManager from . import Node @@ -25,10 +27,30 @@ async def to_graphql( if fields: for read_only_attr in ["netmask", "hostmask", "network_address", "broadcast_address"]: if read_only_attr in fields: - response[read_only_attr] = {"value": getattr(self.prefix, read_only_attr)} # type: ignore[attr-defined] + response[read_only_attr] = {"value": getattr(self.prefix, read_only_attr)} # type: ignore[attr-defined,has-type] if "utilization" in fields: - utilization = await get_utilization(self, db, branch=self._branch) + if self.member_type.id is None or self.prefix.id is None: # type: ignore[has-type] + retrieved = await NodeManager.get_one( + db=db, branch=self._branch, id=self.id, fields={"member_type": None, "prefix": None} + ) + self.member_type = retrieved.member_type # type: ignore[union-attr] # pylint: disable=attribute-defined-outside-init + self.prefix = retrieved.prefix # type: ignore[union-attr] # pylint: disable=attribute-defined-outside-init + utilization_getter = PrefixUtilizationGetter(db=db, ip_prefixes=[self]) + utilization = await utilization_getter.get_use_percentage( + ip_prefixes=[self], branch_names=[self._branch.name] + ) response["utilization"] = {"value": int(utilization)} return response + + async def get_resource_weight(self, db: InfrahubDatabase) -> int: + member_type = self.member_type.value # type: ignore[has-type] # pylint: disable=access-member-before-definition + prefixlen = self.prefix.prefixlen # type: ignore[has-type] # pylint: disable=access-member-before-definition + if member_type is None or prefixlen is None: + retrieved = await NodeManager.get_one( + db=db, branch=self._branch, id=self.id, fields={"member_type": None, "prefix": None} + ) + self.member_type = retrieved.member_type # type: ignore[union-attr] # pylint: disable=attribute-defined-outside-init + self.prefix = retrieved.prefix # type: ignore[union-attr] # pylint: disable=attribute-defined-outside-init + return get_prefix_space(self) diff --git a/backend/infrahub/core/node/resource_manager/__init__.py b/backend/infrahub/core/node/resource_manager/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/infrahub/core/node/resource_manager/ip_address_pool.py b/backend/infrahub/core/node/resource_manager/ip_address_pool.py new file mode 100644 index 0000000000..63db902e2c --- /dev/null +++ b/backend/infrahub/core/node/resource_manager/ip_address_pool.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import ipaddress +from typing import TYPE_CHECKING, Any, Optional + +from infrahub.core import registry +from infrahub.core.ipam.reconciler import IpamReconciler +from infrahub.core.query.ipam import get_ip_addresses +from infrahub.core.query.resource_manager import ( + IPAddressPoolGetReserved, + IPAddressPoolSetReserved, +) +from infrahub.exceptions import PoolExhaustedError, ValidationError +from infrahub.pools.address import get_available + +from .. import Node + +if TYPE_CHECKING: + from infrahub.core.branch import Branch + from infrahub.core.ipam.constants import IPAddressType + from infrahub.database import InfrahubDatabase + + +class CoreIPAddressPool(Node): + async def get_resource( + self, + db: InfrahubDatabase, + branch: Branch, + identifier: Optional[str] = None, + data: Optional[dict[str, Any]] = None, + address_type: Optional[str] = None, + prefixlen: Optional[int] = None, + ) -> Node: + # Check if there is already a resource allocated with this identifier + # if not, pull all existing prefixes and allocated the next available + + if identifier: + query_get = await IPAddressPoolGetReserved.init(db=db, pool_id=self.id, identifier=identifier) + await query_get.execute(db=db) + result = query_get.get_result() + + if result: + address = result.get_node("address") + # TODO add support for branch, if the node is reserved with this id in another branch we should return an error + node = await registry.manager.get_one(db=db, id=address.get("uuid"), branch=branch) + + if node: + return node + + data = data or {} + + address_type = address_type or data.get("address_type") or self.default_address_type.value # type: ignore[attr-defined] + if not address_type: + raise ValueError( + f"IPAddressPool: {self.name.value} | " # type: ignore[attr-defined] + "An address_type or a default_value type must be provided to allocate a new IP address" + ) + + ip_namespace = await self.ip_namespace.get_peer(db=db) # type: ignore[attr-defined] + + prefixlen = prefixlen or data.get("prefixlen") or self.default_prefix_length.value # type: ignore[attr-defined] + + next_prefix = await self.get_next(db=db, prefixlen=prefixlen) + + target_schema = registry.get_node_schema(name=address_type, branch=branch) + node = await Node.init(db=db, schema=target_schema, branch=branch) + await node.new(db=db, address=str(next_prefix), ip_namespace=ip_namespace, **data) + await node.save(db=db) + reconciler = IpamReconciler(db=db, branch=branch) + await reconciler.reconcile(ip_value=next_prefix, namespace=ip_namespace.id, node_uuid=node.get_id()) + + if identifier: + query_set = await IPAddressPoolSetReserved.init( + db=db, pool_id=self.id, identifier=identifier, address_id=node.id + ) + await query_set.execute(db=db) + + return node + + async def get_next(self, db: InfrahubDatabase, prefixlen: Optional[int] = None) -> IPAddressType: + # Measure utilization of all prefixes identified as resources + resources = await self.resources.get_peers(db=db) # type: ignore[attr-defined] + ip_namespace = await self.ip_namespace.get_peer(db=db) # type: ignore[attr-defined] + + for resource in resources.values(): + ip_prefix = ipaddress.ip_network(resource.prefix.value) # type: ignore[attr-defined] + prefix_length = prefixlen or ip_prefix.prefixlen + + if not ip_prefix.prefixlen <= prefix_length <= ip_prefix.max_prefixlen: + raise ValidationError(input_value="Invalid prefix length for current selected prefix") + + addresses = await get_ip_addresses( + db=db, ip_prefix=ip_prefix, namespace=ip_namespace, branch=self._branch, branch_agnostic=True + ) + + available = get_available( + network=ip_prefix, + addresses=[ip.address for ip in addresses], + is_pool=resource.is_pool.value, # type: ignore[attr-defined] + ) + + if available: + next_address = available.iter_cidrs()[0] + return ipaddress.ip_interface(f"{next_address.ip}/{prefix_length}") + + raise PoolExhaustedError("There are no more addresses available in this pool.") diff --git a/backend/infrahub/core/node/resource_manager/ip_prefix_pool.py b/backend/infrahub/core/node/resource_manager/ip_prefix_pool.py new file mode 100644 index 0000000000..17eb587ccd --- /dev/null +++ b/backend/infrahub/core/node/resource_manager/ip_prefix_pool.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import ipaddress +from typing import TYPE_CHECKING, Any, Optional + +from infrahub.core import registry +from infrahub.core.ipam.reconciler import IpamReconciler +from infrahub.core.query.ipam import get_subnets +from infrahub.core.query.resource_manager import ( + PrefixPoolGetReserved, + PrefixPoolSetReserved, +) +from infrahub.pools.prefix import PrefixPool + +from .. import Node + +if TYPE_CHECKING: + from infrahub.core.branch import Branch + from infrahub.core.ipam.constants import IPNetworkType + from infrahub.database import InfrahubDatabase + + +class CoreIPPrefixPool(Node): + async def get_resource( + self, + db: InfrahubDatabase, + branch: Branch, + identifier: Optional[str] = None, + data: Optional[dict[str, Any]] = None, + prefixlen: Optional[int] = None, + member_type: Optional[str] = None, + prefix_type: Optional[str] = None, + ) -> Node: + # Check if there is already a resource allocated with this identifier + # if not, pull all existing prefixes and allocated the next available + if identifier: + query_get = await PrefixPoolGetReserved.init(db=db, pool_id=self.id, identifier=identifier) + await query_get.execute(db=db) + result = query_get.get_result() + if result: + prefix = result.get_node("prefix") + # TODO add support for branch, if the node is reserved with this id in another branch we should return an error + node = await registry.manager.get_one(db=db, id=prefix.get("uuid"), branch=branch) + if node: + return node + + ip_namespace = await self.ip_namespace.get_peer(db=db) # type: ignore[attr-defined] + + data = data or {} + + prefixlen = prefixlen or data.get("prefixlen", None) or self.default_prefix_length.value # type: ignore[attr-defined] + if not prefixlen: + raise ValueError( + f"PrefixPool: {self.name.value} | " # type: ignore[attr-defined] + "A prefixlen or a default_value must be provided to allocate a new prefix" + ) + + next_prefix = await self.get_next(db=db, prefixlen=prefixlen) + + prefix_type = prefix_type or data.get("prefix_type", None) or self.default_prefix_type.value # type: ignore[attr-defined] + if not prefix_type: + raise ValueError( + f"PrefixPool: {self.name.value} | " # type: ignore[attr-defined] + "A prefix_type or a default_value type must be provided to allocate a new prefix" + ) + + member_type = member_type or data.get("member_type", None) or self.default_member_type.value.value # type: ignore[attr-defined] + + target_schema = registry.get_node_schema(name=prefix_type, branch=branch) + node = await Node.init(db=db, schema=target_schema, branch=branch) + await node.new(db=db, prefix=str(next_prefix), member_type=member_type, ip_namespace=ip_namespace, **data) + await node.save(db=db) + reconciler = IpamReconciler(db=db, branch=branch) + await reconciler.reconcile(ip_value=next_prefix, namespace=ip_namespace.id, node_uuid=node.get_id()) + + if identifier: + query_set = await PrefixPoolSetReserved.init( + db=db, pool_id=self.id, identifier=identifier, prefix_id=node.id + ) + await query_set.execute(db=db) + + return node + + async def get_next(self, db: InfrahubDatabase, prefixlen: int) -> IPNetworkType: + # Measure utilization of all prefixes identified as resources + resources = await self.resources.get_peers(db=db) # type: ignore[attr-defined] + ip_namespace = await self.ip_namespace.get_peer(db=db) # type: ignore[attr-defined] + + for resource in resources.values(): + subnets = await get_subnets( + db=db, + ip_prefix=ipaddress.ip_network(resource.prefix.value), # type: ignore[attr-defined] + namespace=ip_namespace, + branch=self._branch, + branch_agnostic=True, + ) + + pool = PrefixPool(resource.prefix.value) # type: ignore[attr-defined] + for subnet in subnets: + pool.reserve(subnet=str(subnet.prefix)) + + try: + next_available = pool.get(prefixlen=prefixlen) + return next_available + except IndexError: + continue + + raise IndexError("No more resources available") diff --git a/backend/infrahub/core/query/__init__.py b/backend/infrahub/core/query/__init__.py index ee90d7b76e..d5ae4b4e93 100644 --- a/backend/infrahub/core/query/__init__.py +++ b/backend/infrahub/core/query/__init__.py @@ -307,10 +307,13 @@ def __init__( limit: Optional[int] = None, offset: Optional[int] = None, order_by: Optional[List[str]] = None, + branch_agnostic: bool = False, ): if branch: self.branch = branch + self.branch_agnostic = branch_agnostic + if not hasattr(self, "at"): self.at = Timestamp(at) diff --git a/backend/infrahub/core/query/ipam.py b/backend/infrahub/core/query/ipam.py index d48b4d32ab..3341d459ea 100644 --- a/backend/infrahub/core/query/ipam.py +++ b/backend/infrahub/core/query/ipam.py @@ -20,6 +20,10 @@ from infrahub.database import InfrahubDatabase +PREFIX_ATTRIBUTE_LABEL = "AttributeIPNetwork" +ADDRESS_ATTRIBUTE_LABEL = "AttributeIPHost" + + @dataclass class IPPrefixData: id: UUID @@ -65,7 +69,9 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): self.params["maxprefixlen"] = self.obj.prefixlen self.params["ip_version"] = self.obj.version - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) + branch_filter, branch_params = self.branch.get_query_filter_path( + at=self.at.to_string(), branch_agnostic=self.branch_agnostic + ) self.params.update(branch_params) # ruff: noqa: E501 @@ -132,94 +138,6 @@ def get_subnets(self): return subnets -class IPPrefixContainerFetch(Query): - name: str = "ipprefix_container_fetch" - - def __init__( - self, - obj: Union[ipaddress.IPv6Network, ipaddress.IPv4Network, ipaddress.IPv4Interface, ipaddress.IPv6Interface], - namespace: Optional[Union[Node, str]] = None, - *args, - **kwargs, - ): - self.obj = obj - self.namespace_id = _get_namespace_id(namespace) - - if isinstance(obj, (ipaddress.IPv6Network, ipaddress.IPv4Network)): - self.prefixlen = obj.prefixlen - self.minprefixlen = obj.prefixlen - elif isinstance(obj, (ipaddress.IPv4Interface, ipaddress.IPv6Interface)): - self.prefixlen = obj.network.prefixlen - self.minprefixlen = self.prefixlen + 1 - - super().__init__(*args, **kwargs) - - async def query_init(self, db: InfrahubDatabase, *args, **kwargs): - self.params["ns_id"] = self.namespace_id - prefix_bin = convert_ip_to_binary_str(self.obj)[: self.prefixlen] - - self.params["minprefixlen"] = self.minprefixlen - self.params["ip_version"] = self.obj.version - - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) - self.params.update(branch_params) - - possible_prefixes = set() - for idx in range(1, self.prefixlen): - tmp_prefix = prefix_bin[: self.prefixlen - idx] - padding = "0" * (self.obj.max_prefixlen - len(tmp_prefix)) - possible_prefixes.add(f"{tmp_prefix}{padding}") - - self.params["possible_prefixes"] = list(possible_prefixes) - - # ruff: noqa: E501 - query = """ - // First match on IPNAMESPACE - MATCH (ns:%(ns_label)s) - WHERE ns.uuid = $ns_id - CALL { - WITH ns - MATCH (ns)-[r:IS_PART_OF]-(root:Root) - WHERE %(branch_filter)s - RETURN ns as ns1, r as r1 - ORDER BY r.branch_level DESC, r.from DESC - LIMIT 1 - } - WITH ns, r1 as r - WHERE r.status = "active" - WITH ns - // MATCH all prefixes that are IN SCOPE - MATCH path2 = (ns)-[:IS_RELATED]-(ns_rel:Relationship)-[:IS_RELATED]-(pfx:%(node_label)s)-[:HAS_ATTRIBUTE]-(an:Attribute {name: "prefix"})-[:HAS_VALUE]-(av:AttributeIPNetwork) - WHERE ns_rel.name = "ip_namespace__ip_prefix" - AND av.binary_address IN $possible_prefixes - AND av.prefixlen < $minprefixlen - AND av.version = $ip_version - AND all(r IN relationships(path2) WHERE (%(branch_filter)s)) - """ % { - "ns_label": InfrahubKind.IPNAMESPACE, - "node_label": InfrahubKind.IPPREFIX, - "branch_filter": branch_filter, - } - - self.add_to_query(query) - self.return_labels = ["pfx", "av"] - self.order_by = ["av.prefixlen"] - - def get_container(self) -> Optional[IPPrefixData]: - """Return the more specific prefix that contains this one.""" - candidates: List[IPPrefixData] = [] - - if not self.num_of_results: - return None - - for result in self.get_results(): - candidate = IPPrefixData( - id=result.get("pfx").get("uuid"), prefix=ipaddress.ip_network(result.get("av").get("value")) - ) - candidates.append(candidate) - return candidates[-1] - - class IPPrefixIPAddressFetch(Query): name: str = "ipprefix_ipaddress_fetch" @@ -243,7 +161,9 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): self.params["maxprefixlen"] = self.obj.prefixlen self.params["ip_version"] = self.obj.version - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) + branch_filter, branch_params = self.branch.get_query_filter_path( + at=self.at.to_string(), branch_agnostic=self.branch_agnostic + ) self.params.update(branch_params) # ruff: noqa: E501 @@ -292,28 +212,18 @@ def get_addresses(self): return addresses -async def get_container( - db: InfrahubDatabase, - ip_prefix: IPNetworkType, - namespace: Optional[Union[Node, str]] = None, - branch: Optional[Union[Branch, str]] = None, - at: Optional[Union[Timestamp, str]] = None, -) -> Optional[IPPrefixData]: - branch = await registry.get_branch(db=db, branch=branch) - query = await IPPrefixContainerFetch.init(db=db, branch=branch, obj=ip_prefix, namespace=namespace, at=at) - await query.execute(db=db) - return query.get_container() - - async def get_subnets( db: InfrahubDatabase, ip_prefix: IPNetworkType, namespace: Optional[Union[Node, str]] = None, branch: Optional[Union[Branch, str]] = None, at: Optional[Union[Timestamp, str]] = None, + branch_agnostic: bool = False, ) -> Iterable[IPPrefixData]: branch = await registry.get_branch(db=db, branch=branch) - query = await IPPrefixSubnetFetch.init(db=db, branch=branch, obj=ip_prefix, namespace=namespace, at=at) + query = await IPPrefixSubnetFetch.init( + db=db, branch=branch, obj=ip_prefix, namespace=namespace, at=at, branch_agnostic=branch_agnostic + ) await query.execute(db=db) return query.get_subnets() @@ -324,144 +234,79 @@ async def get_ip_addresses( namespace: Optional[Union[Node, str]] = None, branch: Optional[Union[Branch, str]] = None, at=None, + branch_agnostic: bool = False, ) -> Iterable[IPAddressData]: branch = await registry.get_branch(db=db, branch=branch) - query = await IPPrefixIPAddressFetch.init(db=db, branch=branch, obj=ip_prefix, namespace=namespace, at=at) + query = await IPPrefixIPAddressFetch.init( + db=db, branch=branch, obj=ip_prefix, namespace=namespace, at=at, branch_agnostic=branch_agnostic + ) await query.execute(db=db) return query.get_addresses() -async def get_ip_prefix_for_ip_address( - db: InfrahubDatabase, - ip_address: IPAddressType, - namespace: Optional[str] = None, - branch: Optional[Union[Branch, str]] = None, - at: Optional[Union[Timestamp, str]] = None, -) -> Optional[IPPrefixData]: - branch = await registry.get_branch(db=db, branch=branch) - query = await IPPrefixContainerFetch.init(db=db, branch=branch, obj=ip_address, namespace=namespace, at=at) - await query.execute(db=db) - return query.get_container() - - -class IPPrefixUtilizationPrefix(Query): +class IPPrefixUtilization(Query): name: str = "ipprefix_utilization_prefix" - def __init__(self, ip_prefix: Node, *args, **kwargs): - self.ip_prefix = ip_prefix - super().__init__(*args, **kwargs) - - async def query_init(self, db: InfrahubDatabase, *args, **kwargs): - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) - self.params.update(branch_params) - - self.params["id"] = self.ip_prefix.id - - query = """ - MATCH path = (pfx:Node)<-[:IS_RELATED]-(rl:Relationship)<-[:IS_RELATED]-(children:%(label)s) - WHERE pfx.uuid = $id - AND all(r IN relationships(path) WHERE (%(branch_filter)s)) - AND rl.name = "parent__child" - CALL { - WITH pfx, children - MATCH path = (pfx)<-[r1:IS_RELATED]-(rl:Relationship)<-[r2:IS_RELATED]-(children:%(label)s) - WHERE all(r IN relationships(path) WHERE (%(branch_filter)s)) - AND rl.name = "parent__child" - RETURN r1 as r11, r2 as r21 - ORDER BY r1.branch_level DESC, r1.from DESC, r2.branch_level DESC, r2.from DESC - LIMIT 1 - } - WITH pfx, children, r11, r21 - WHERE r11.status = "active" AND r21.status = "active" - CALL { - WITH children - MATCH path = (children)-[r1:HAS_ATTRIBUTE]-(:Attribute {name: "prefix"})-[r2:HAS_VALUE]-(av:AttributeIPNetwork) - WHERE all(r IN relationships(path) WHERE (%(branch_filter)s)) - RETURN r1 as r12, r2 as r22, av - ORDER BY r1.branch_level DESC, r1.from DESC, r2.branch_level DESC, r2.from DESC - LIMIT 1 - } - WITH pfx, children, r12, r22, av - WHERE r12.status = "active" AND r22.status = "active" - """ % {"label": InfrahubKind.IPPREFIX, "branch_filter": branch_filter} # noqa: E501 - - self.return_labels = ["av.prefixlen as prefixlen"] - - self.add_to_query(query) - - def get_percentage(self): - prefix_space = self.ip_prefix.prefix.num_addresses - max_prefixlen = self.ip_prefix.prefix.obj.max_prefixlen - used_space = 0 - for result in self.get_results(): - used_space += 2 ** (max_prefixlen - int(result.get("prefixlen"))) - - return (used_space / prefix_space) * 100 - - -class IPPrefixUtilizationAddress(Query): - name: str = "ipprefix_utilization_address" - - def __init__(self, ip_prefix: Node, *args, **kwargs): - self.ip_prefix = ip_prefix + def __init__(self, ip_prefixes: list[str], *args, **kwargs): + self.ip_prefixes = ip_prefixes super().__init__(*args, **kwargs) async def query_init(self, db: InfrahubDatabase, *args, **kwargs): - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) - self.params.update(branch_params) - - self.params["id"] = self.ip_prefix.id - - query = """ - MATCH path = (pfx:Node)-[:IS_RELATED]->(rl:Relationship)<-[:IS_RELATED]-(children:%(label)s) - WHERE pfx.uuid = $id - AND all(r IN relationships(path) WHERE (%(branch_filter)s)) - AND rl.name = "ip_prefix__ip_address" - CALL { - WITH pfx, children - MATCH path = (pfx)-[r1:IS_RELATED]->(rl:Relationship)<-[r2:IS_RELATED]-(children:%(label)s) - WHERE all(r IN relationships(path) WHERE (%(branch_filter)s)) - AND rl.name = "ip_prefix__ip_address" - RETURN r1, r2 - ORDER BY r1.branch_level DESC, r1.from DESC, r2.branch_level DESC, r2.from DESC - LIMIT 1 - } - WITH pfx, children, r1, r2 - WHERE r1.status = "active" AND r2.status = "active" - """ % {"label": InfrahubKind.IPADDRESS, "branch_filter": branch_filter} # noqa: E501 - - self.return_labels = ["count(children) as nbr_children"] - + self.params["ids"] = [p.get_id() for p in self.ip_prefixes] + self.params["time_at"] = self.at.to_string() + + def rel_filter(rel_name: str) -> str: + return f"{rel_name}.from <= $time_at AND ({rel_name}.to IS NULL OR {rel_name}.to >= $time_at)" + + query = f""" + MATCH (pfx:Node) + WHERE pfx.uuid IN $ids + CALL {{ + WITH pfx + MATCH (pfx)-[r_rel1:IS_RELATED]-(rl:Relationship)<-[r_rel2:IS_RELATED]-(child:Node) + WHERE rl.name IN ["parent__child", "ip_prefix__ip_address"] + AND any(l IN labels(child) WHERE l in ["{InfrahubKind.IPPREFIX}", "{InfrahubKind.IPADDRESS}"]) + AND ({rel_filter("r_rel1")}) + AND ({rel_filter("r_rel2")}) + RETURN r_rel1, rl, r_rel2, child + }} + WITH pfx, r_rel1, rl, r_rel2, child + MATCH path = ( + (pfx)-[r_1:IS_RELATED]-(rl:Relationship)-[r_2:IS_RELATED]-(child:Node) + -[r_attr:HAS_ATTRIBUTE]->(attr:Attribute) + -[r_attr_val:HAS_VALUE]->(av:AttributeValue) + ) + WHERE ID(r_1) = ID(r_rel1) + AND ID(r_2) = ID(r_rel2) + AND ({rel_filter("r_attr")}) + AND ({rel_filter("r_attr_val")}) + AND attr.name IN ["prefix", "address"] + AND any(l in labels(av) WHERE l in ["{PREFIX_ATTRIBUTE_LABEL}", "{ADDRESS_ATTRIBUTE_LABEL}"]) + WITH + path, + pfx, + child, + av, + reduce(br_lvl = 0, r in relationships(path) | br_lvl + r.branch_level) AS sum_branch_level, + all(r in relationships(path) WHERE r.status = "active") AS is_active, + [r_attr_val.from, r_attr.from, r_2.from, r_1.from] AS from_times, + reduce( + b_details = [0, null], r in relationships(path) | + CASE WHEN r.branch_level > b_details[0] THEN [r.branch_level, r.branch] ELSE b_details END + ) as deepest_branch_details + ORDER BY pfx.uuid, child.uuid, av.uuid, sum_branch_level DESC, from_times[3] DESC, from_times[2] DESC, from_times[1] DESC, from_times[0] DESC + WITH + pfx, + child, + av, + deepest_branch_details[0] AS branch_level, + deepest_branch_details[1] AS branch, + head(collect(is_active)) AS is_latest_active + WHERE is_latest_active = TRUE + """ + self.return_labels = ["pfx", "child", "av", "branch_level", "branch"] self.add_to_query(query) - def get_percentage(self): - prefix_space = self.ip_prefix.prefix.num_addresses - - # Non-RFC3021 subnet - if ( - self.ip_prefix.prefix.version == 4 - and self.ip_prefix.prefix.prefixlen < 31 - and not self.ip_prefix.is_pool.value - ): - prefix_space -= 2 - - return (self.get_result().get("nbr_children") / prefix_space) * 100 - - -async def get_utilization( - ip_prefix: Node, - db: InfrahubDatabase, - branch: Optional[Branch] = None, - at: Optional[Union[Timestamp, str]] = None, -) -> float: - if ip_prefix.member_type.value == "address": - query = await IPPrefixUtilizationAddress.init(db, branch=branch, at=at, ip_prefix=ip_prefix) - else: - query = await IPPrefixUtilizationPrefix.init(db, branch=branch, at=at, ip_prefix=ip_prefix) - - await query.execute(db=db) - return query.get_percentage() - class IPPrefixReconcileQuery(Query): name: str = "ip_prefix_reconcile" @@ -482,32 +327,42 @@ def __init__( async def query_init(self, db: InfrahubDatabase, *args, **kwargs): branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) self.params.update(branch_params) - self.params["ip_prefix_kind"] = InfrahubKind.IPPREFIX - self.params["ip_address_kind"] = InfrahubKind.IPADDRESS - self.params["ip_prefix_attribute_kind"] = "AttributeIPNetwork" - self.params["ip_address_attribute_kind"] = "AttributeIPHost" self.params["namespace_kind"] = InfrahubKind.IPNAMESPACE self.params["namespace_id"] = self.namespace_id - prefix_bin = convert_ip_to_binary_str(self.ip_value) - self.params["prefix_binary"] = prefix_bin + self.params["ip_prefix_kind"] = InfrahubKind.IPPREFIX + self.params["ip_address_kind"] = InfrahubKind.IPADDRESS + self.params["ip_prefix_attribute_kind"] = PREFIX_ATTRIBUTE_LABEL + self.params["ip_address_attribute_kind"] = ADDRESS_ATTRIBUTE_LABEL + if isinstance(self.ip_value, IPAddressType): - prefixlen = self.ip_value.max_prefixlen + is_address = True + prefixlen = self.ip_value.network.prefixlen else: + is_address = False prefixlen = self.ip_value.prefixlen + self.params["is_prefix"] = not is_address self.params["prefixlen"] = prefixlen + prefix_bin = convert_ip_to_binary_str(self.ip_value) + prefix_bin_host = prefix_bin[:prefixlen] + self.params["prefix_binary_full"] = prefix_bin + self.params["prefix_binary_host"] = prefix_bin_host self.params["ip_version"] = self.ip_value.version - possible_prefixes = set() - for idx in range(1, prefixlen): - tmp_prefix = prefix_bin[: prefixlen - idx] - padding = "0" * (self.ip_value.max_prefixlen - len(tmp_prefix)) - possible_prefixes.add(f"{tmp_prefix}{padding}") - self.params["possible_prefixes"] = list(possible_prefixes) + # possible prefix: highest possible prefix length for a match + possible_prefix_map: dict[str, int] = {} + start_prefixlen = prefixlen if is_address else prefixlen - 1 + for max_prefix_len in range(start_prefixlen, 0, -1): + tmp_prefix = prefix_bin_host[:max_prefix_len] + possible_prefix = tmp_prefix.ljust(self.ip_value.max_prefixlen, "0") + if possible_prefix not in possible_prefix_map: + possible_prefix_map[possible_prefix] = max_prefix_len + self.params["possible_prefix_and_length_list"] = [ + [possible_prefix, max_length] for possible_prefix, max_length in possible_prefix_map.items() + ] namespace_query = """ // Get IP Namespace - MATCH (ip_namespace:%(namespace_kind)s)-[r:IS_PART_OF]->(root:Root) - WHERE ip_namespace.uuid = $namespace_id - AND %(branch_filter)s + MATCH (ip_namespace:%(namespace_kind)s {uuid: $namespace_id})-[r:IS_PART_OF]->(root:Root) + WHERE %(branch_filter)s """ % {"branch_filter": branch_filter, "namespace_kind": self.params["namespace_kind"]} self.add_to_query(namespace_query) @@ -522,16 +377,23 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): else: get_node_by_prefix_query = """ // Get IP Prefix node by prefix value - OPTIONAL MATCH ip_node_path = (:Root)<-[:IS_PART_OF]-(ip_node:Node)-[:HAS_ATTRIBUTE]->(a:Attribute)-[:HAS_VALUE]->(aipn), (ip_namespace)-[:IS_RELATED]-(nsr:Relationship)-[:IS_RELATED]-(ip_node) - WHERE any(label IN LABELS(ip_node) WHERE label IN [$ip_prefix_kind, $ip_address_kind]) - AND nsr.name IN ["ip_namespace__ip_prefix", "ip_namespace__ip_address"] - AND any(label IN LABELS(aipn) WHERE label IN [$ip_prefix_attribute_kind, $ip_address_attribute_kind]) - AND aipn.binary_address = $prefix_binary + OPTIONAL MATCH ip_node_path = (:Root)<-[:IS_PART_OF]-(ip_node:%(ip_kind)s) + -[:HAS_ATTRIBUTE]->(a:Attribute)-[:HAS_VALUE]->(aipn:%(ip_attribute_kind)s), + (ip_namespace)-[:IS_RELATED]-(nsr:Relationship) + -[:IS_RELATED]-(ip_node) + WHERE nsr.name IN ["ip_namespace__ip_prefix", "ip_namespace__ip_address"] + AND aipn.binary_address = $prefix_binary_full AND aipn.prefixlen = $prefixlen AND aipn.version = $ip_version AND all(r IN relationships(ip_node_path) WHERE (%(branch_filter)s) and r.status = "active") """ % { "branch_filter": branch_filter, + "ip_kind": InfrahubKind.IPADDRESS + if isinstance(self.ip_value, IPAddressType) + else InfrahubKind.IPPREFIX, + "ip_attribute_kind": ADDRESS_ATTRIBUTE_LABEL + if isinstance(self.ip_value, IPAddressType) + else PREFIX_ATTRIBUTE_LABEL, } self.add_to_query(get_node_by_prefix_query) @@ -541,7 +403,7 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): WHERE all(r IN relationships(parent_prefix_path) WHERE (%(branch_filter)s) and r.status = "active") """ % { "branch_filter": branch_filter, - "ip_prefix_kind": self.params["ip_prefix_kind"], + "ip_prefix_kind": InfrahubKind.IPPREFIX, } self.add_to_query(get_current_parent_query) @@ -557,8 +419,8 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): WITH ip_namespace, ip_node, current_parent, current_prefix_children + current_address_children AS current_children """ % { "branch_filter": branch_filter, - "ip_prefix_kind": self.params["ip_prefix_kind"], - "ip_address_kind": self.params["ip_address_kind"], + "ip_prefix_kind": InfrahubKind.IPPREFIX, + "ip_address_kind": InfrahubKind.IPADDRESS, } self.add_to_query(get_current_children_query) @@ -566,14 +428,13 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): // Identify the correct parent, if any, for the prefix node CALL { WITH ip_namespace - OPTIONAL MATCH parent_path = (ip_namespace)-[pr1:IS_RELATED]-(ns_rel:Relationship)-[pr2:IS_RELATED]-(maybe_new_parent:%(ip_prefix_kind)s)-[har:HAS_ATTRIBUTE]->(:Attribute {name: "prefix"})-[hvr:HAS_VALUE]->(av:%(ip_prefix_attribute_kind)s) - WHERE ns_rel.name = "ip_namespace__ip_prefix" - AND all(r IN relationships(parent_path) WHERE (%(branch_filter)s)) - AND pr1.status = "active" - AND pr2.status = "active" - AND av.binary_address IN $possible_prefixes - AND av.prefixlen < $prefixlen + OPTIONAL MATCH parent_path = (ip_namespace)-[pr1:IS_RELATED {status: "active"}]-(ns_rel:Relationship {name: "ip_namespace__ip_prefix"}) + -[pr2:IS_RELATED {status: "active"}]-(maybe_new_parent:%(ip_prefix_kind)s) + -[har:HAS_ATTRIBUTE]->(:Attribute {name: "prefix"}) + -[hvr:HAS_VALUE]->(av:%(ip_prefix_attribute_kind)s) + WHERE all(r IN relationships(parent_path) WHERE (%(branch_filter)s)) AND av.version = $ip_version + AND any(prefix_and_length IN $possible_prefix_and_length_list WHERE av.binary_address = prefix_and_length[0] AND av.prefixlen <= prefix_and_length[1]) WITH maybe_new_parent, har, @@ -592,8 +453,8 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): WITH ip_namespace, ip_node, current_parent, current_children, head(collect(maybe_new_parent)) as new_parent """ % { "branch_filter": branch_filter, - "ip_prefix_kind": self.params["ip_prefix_kind"], - "ip_prefix_attribute_kind": self.params["ip_prefix_attribute_kind"], + "ip_prefix_kind": InfrahubKind.IPPREFIX, + "ip_prefix_attribute_kind": PREFIX_ATTRIBUTE_LABEL, } self.add_to_query(get_new_parent_query) @@ -602,18 +463,25 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): CALL { // Get ALL possible children for the prefix node WITH ip_namespace, ip_node - OPTIONAL MATCH child_path = (ip_namespace)-[:IS_RELATED]-(ns_rel:Relationship)-[:IS_RELATED]-(maybe_new_child)-[har:HAS_ATTRIBUTE]->(a:Attribute)-[hvr:HAS_VALUE]->(av:AttributeValue) - WHERE (ip_node IS NULL OR maybe_new_child.uuid <> ip_node.uuid) + OPTIONAL MATCH child_path = ( + (ip_namespace)-[:IS_RELATED] + -(ns_rel:Relationship)-[:IS_RELATED] + -(maybe_new_child:Node)-[har:HAS_ATTRIBUTE] + ->(a:Attribute)-[hvr:HAS_VALUE] + ->(av:AttributeValue) + ) + WHERE $is_prefix // only prefix nodes can have children AND ns_rel.name IN ["ip_namespace__ip_prefix", "ip_namespace__ip_address"] + AND any(child_kind IN [$ip_prefix_kind, $ip_address_kind] WHERE child_kind IN labels(maybe_new_child)) AND a.name in ["prefix", "address"] - AND any(label IN LABELS(maybe_new_child) WHERE label IN [$ip_prefix_kind, $ip_address_kind]) - AND any(label IN LABELS(av) WHERE label IN [$ip_prefix_attribute_kind, $ip_address_attribute_kind]) + AND any(attr_kind IN [$ip_prefix_attribute_kind, $ip_address_attribute_kind] WHERE attr_kind IN labels(av)) + AND (ip_node IS NULL OR maybe_new_child.uuid <> ip_node.uuid) AND ( - ($ip_prefix_kind IN LABELS(maybe_new_child) AND av.prefixlen > $prefixlen) - OR ($ip_address_kind IN LABELS(maybe_new_child) AND av.prefixlen >= $prefixlen) + ($ip_prefix_kind IN labels(maybe_new_child) AND av.prefixlen > $prefixlen) + OR ($ip_address_kind IN labels(maybe_new_child) AND av.prefixlen >= $prefixlen) ) AND av.version = $ip_version - AND av.binary_address STARTS WITH SUBSTRING($prefix_binary, 0, $prefixlen) + AND av.binary_address STARTS WITH $prefix_binary_host AND all(r IN relationships(child_path) WHERE (%(branch_filter)s) AND r.status = "active") WITH maybe_new_child, @@ -642,9 +510,9 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): WHEN has_more_specific_parent THEN has_more_specific_parent // keep it True once set WHEN potential_parent IS NULL OR ips[ind][0] IS NULL THEN has_more_specific_parent WHEN potential_parent[0] = ips[ind][0] THEN has_more_specific_parent // skip comparison to self - WHEN $ip_address_kind in LABELS(potential_parent[0]) THEN has_more_specific_parent // address cannot be a parent - WHEN $ip_prefix_attribute_kind IN LABELS(ips[ind][1]) AND (potential_parent[1]).prefixlen >= (ips[ind][1]).prefixlen THEN has_more_specific_parent // prefix with same or greater prefixlen for prefix cannot be parent - WHEN $ip_address_attribute_kind IN LABELS(ips[ind][1]) AND (potential_parent[1]).prefixlen > (ips[ind][1]).prefixlen THEN has_more_specific_parent // prefix with greater prefixlen for address cannot be parent + WHEN $ip_address_kind in labels(potential_parent[0]) THEN has_more_specific_parent // address cannot be a parent + WHEN $ip_prefix_attribute_kind IN labels(ips[ind][1]) AND (potential_parent[1]).prefixlen >= (ips[ind][1]).prefixlen THEN has_more_specific_parent // prefix with same or greater prefixlen for prefix cannot be parent + WHEN $ip_address_attribute_kind IN labels(ips[ind][1]) AND (potential_parent[1]).prefixlen > (ips[ind][1]).prefixlen THEN has_more_specific_parent // prefix with greater prefixlen for address cannot be parent WHEN (ips[ind][1]).binary_address STARTS WITH SUBSTRING((potential_parent[1]).binary_address, 0, (potential_parent[1]).prefixlen) THEN TRUE // we found a parent ELSE has_more_specific_parent END @@ -659,7 +527,9 @@ async def query_init(self, db: InfrahubDatabase, *args, **kwargs): current_children, new_parent, collect(new_child) as new_children - """ % {"branch_filter": branch_filter} + """ % { + "branch_filter": branch_filter, + } self.add_to_query(get_new_children_query) self.return_labels = ["ip_node", "current_parent", "current_children", "new_parent", "new_children"] diff --git a/backend/infrahub/core/query/node.py b/backend/infrahub/core/query/node.py index 7167937f61..4663b033e3 100644 --- a/backend/infrahub/core/query/node.py +++ b/backend/infrahub/core/query/node.py @@ -424,7 +424,9 @@ def __init__( async def query_init(self, db: InfrahubDatabase, *args, **kwargs): self.params["ids"] = self.ids - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) + branch_filter, branch_params = self.branch.get_query_filter_path( + at=self.at, branch_agnostic=self.branch_agnostic + ) self.params.update(branch_params) query = """ @@ -566,7 +568,7 @@ def __init__( async def query_init(self, db: InfrahubDatabase, *args, **kwargs): self.params["ids"] = self.ids - rels_filter, rels_params = self.branch.get_query_filter_path(at=self.at) + rels_filter, rels_params = self.branch.get_query_filter_path(at=self.at, branch_agnostic=self.branch_agnostic) self.params.update(rels_params) query = ( @@ -604,7 +606,9 @@ def __init__(self, ids: List[str], account=None, *args: Any, **kwargs: Any) -> N super().__init__(*args, **kwargs) async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> None: - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) + branch_filter, branch_params = self.branch.get_query_filter_path( + at=self.at, branch_agnostic=self.branch_agnostic + ) self.params.update(branch_params) query = """ @@ -631,11 +635,11 @@ async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> N self.return_labels = ["collect(profile.uuid) as profile_uuids", "n", "rb"] - async def get_nodes(self, duplicate: bool = True) -> AsyncIterator[NodeToProcess]: + async def get_nodes(self, db: InfrahubDatabase, duplicate: bool = False) -> AsyncIterator[NodeToProcess]: """Return all the node objects as NodeToProcess.""" for result in self.get_results_group_by(("n", "uuid")): - schema = find_node_schema(node=result.get_node("n"), branch=self.branch, duplicate=duplicate) + schema = find_node_schema(db=db, node=result.get_node("n"), branch=self.branch, duplicate=duplicate) yield NodeToProcess( schema=schema, node_id=result.get_node("n").element_id, @@ -1105,9 +1109,8 @@ def __init__( super().__init__(*args, **kwargs) - self.hierarchy_schema = node_schema.get_hierarchy_schema(self.branch) - async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> None: # pylint: disable=too-many-statements + hierarchy_schema = self.node_schema.get_hierarchy_schema(db=db, branch=self.branch) branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) self.params.update(branch_params) self.order_by = [] @@ -1116,7 +1119,7 @@ async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> N filter_str = "[:IS_RELATED*2..%s { hierarchy: $hierarchy }]" % ( config.SETTINGS.database.max_depth_search_hierarchy * 2, ) - self.params["hierarchy"] = self.hierarchy_schema.kind + self.params["hierarchy"] = hierarchy_schema.kind if self.direction == RelationshipHierarchyDirection.ANCESTORS: filter_str = f"-{filter_str}->" @@ -1177,10 +1180,10 @@ async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> N filter_field_name, filter_next_name = peer_filter_name.split("__", maxsplit=1) - if filter_field_name not in self.hierarchy_schema.valid_input_names: + if filter_field_name not in hierarchy_schema.valid_input_names: continue - field = self.hierarchy_schema.get_field(filter_field_name) + field = hierarchy_schema.get_field(filter_field_name) subquery, subquery_params, subquery_result_name = await build_subquery_filter( db=db, @@ -1204,13 +1207,13 @@ async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Any) -> N # ---------------------------------------------------------------------------- # ORDER Results # ---------------------------------------------------------------------------- - if hasattr(self.hierarchy_schema, "order_by") and self.hierarchy_schema.order_by: + if hasattr(hierarchy_schema, "order_by") and hierarchy_schema.order_by: order_cnt = 1 - for order_by_value in self.hierarchy_schema.order_by: + for order_by_value in hierarchy_schema.order_by: order_by_field_name, order_by_next_name = order_by_value.split("__", maxsplit=1) - field = self.hierarchy_schema.get_field(order_by_field_name) + field = hierarchy_schema.get_field(order_by_field_name) subquery, subquery_params, subquery_result_name = await build_subquery_order( db=db, diff --git a/backend/infrahub/core/query/relationship.py b/backend/infrahub/core/query/relationship.py index 7a15b8470a..a84f6cd0c4 100644 --- a/backend/infrahub/core/query/relationship.py +++ b/backend/infrahub/core/query/relationship.py @@ -520,11 +520,13 @@ def __init__( super().__init__(*args, **kwargs) async def query_init(self, db: InfrahubDatabase, *args, **kwargs): # pylint: disable=too-many-statements - branch_filter, branch_params = self.branch.get_query_filter_path(at=self.at.to_string()) + branch_filter, branch_params = self.branch.get_query_filter_path( + at=self.at, branch_agnostic=self.branch_agnostic + ) self.params.update(branch_params) self.order_by = [] - peer_schema = self.schema.get_peer_schema(branch=self.branch) + peer_schema = self.schema.get_peer_schema(db=db, branch=self.branch) self.params["source_ids"] = self.source_ids self.params["rel_identifier"] = self.schema.identifier diff --git a/backend/infrahub/core/query/resource_manager.py b/backend/infrahub/core/query/resource_manager.py new file mode 100644 index 0000000000..b7c75a34de --- /dev/null +++ b/backend/infrahub/core/query/resource_manager.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from infrahub.core import registry +from infrahub.core.constants import InfrahubKind, RelationshipStatus +from infrahub.core.query import Query + +if TYPE_CHECKING: + from infrahub.database import InfrahubDatabase + + +class IPAddressPoolGetIdentifiers(Query): + name: str = "ipaddresspool_get_identifiers" + + def __init__( + self, + *args: Any, + pool_id: str, + allocated: list[str], + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.addresses = allocated + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["addresses"] = self.addresses + + query = """ + MATCH (pool:%(ipaddress_pool)s { uuid: $pool_id })-[reservation:IS_RESERVED]->(allocated:BuiltinIPAddress) + WHERE allocated.uuid in $addresses + """ % {"ipaddress_pool": InfrahubKind.IPADDRESSPOOL} + self.add_to_query(query) + self.return_labels = ["allocated", "reservation"] + + +class IPAddressPoolGetReserved(Query): + name: str = "ipaddresspool_get_reserved" + + def __init__( + self, + *args: Any, + pool_id: str, + identifier: str, + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.identifier = identifier + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["identifier"] = self.identifier + + query = """ + MATCH (pool:%(ipaddress_pool)s { uuid: $pool_id })-[rel:IS_RESERVED]->(address:BuiltinIPAddress) + WHERE rel.identifier = $identifier + """ % {"ipaddress_pool": InfrahubKind.IPADDRESSPOOL} + self.add_to_query(query) + self.return_labels = ["address"] + + +class IPAddressPoolSetReserved(Query): + name: str = "ipaddresspool_set_reserved" + + def __init__( + self, + pool_id: str, + address_id: str, + identifier: str, + *args: Any, + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.address_id = address_id + self.identifier = identifier + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["address_id"] = self.address_id + self.params["identifier"] = self.identifier + + global_branch = registry.get_global_branch() + self.params["rel_prop"] = { + "branch": global_branch.name, + "branch_level": global_branch.hierarchy_level, + "status": RelationshipStatus.ACTIVE.value, + "from": self.at.to_string(), + "identifier": self.identifier, + } + + query = """ + MATCH (pool:%(ipaddress_pool)s { uuid: $pool_id }) + MATCH (address:Node { uuid: $address_id }) + CREATE (pool)-[rel:IS_RESERVED $rel_prop]->(address) + """ % {"ipaddress_pool": InfrahubKind.IPADDRESSPOOL} + + self.add_to_query(query) + self.return_labels = ["pool", "rel", "address"] + + +class PrefixPoolGetIdentifiers(Query): + name: str = "prefixpool_get_identifiers" + + def __init__( + self, + *args: Any, + pool_id: str, + allocated: list[str], + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.prefixes = allocated + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["prefixes"] = self.prefixes + + query = """ + MATCH (pool:%(ipaddress_pool)s { uuid: $pool_id })-[reservation:IS_RESERVED]->(allocated:BuiltinIPPrefix) + WHERE allocated.uuid in $prefixes + """ % {"ipaddress_pool": InfrahubKind.IPPREFIXPOOL} + self.add_to_query(query) + self.return_labels = ["allocated", "reservation"] + + +class PrefixPoolGetReserved(Query): + name: str = "prefixpool_get_reserved" + + def __init__( + self, + *args: Any, + pool_id: str, + identifier: str, + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.identifier = identifier + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["identifier"] = self.identifier + + query = """ + MATCH (pool:%(prefix_pool)s { uuid: $pool_id })-[rel:IS_RESERVED]->(prefix:BuiltinIPPrefix) + WHERE rel.identifier = $identifier + """ % {"prefix_pool": InfrahubKind.IPPREFIXPOOL} + self.add_to_query(query) + self.return_labels = ["prefix"] + + +class PrefixPoolSetReserved(Query): + name: str = "prefixpool_set_reserved" + + def __init__( + self, + pool_id: str, + prefix_id: str, + identifier: str, + *args: Any, + **kwargs: dict[str, Any], + ) -> None: + self.pool_id = pool_id + self.prefix_id = prefix_id + self.identifier = identifier + + super().__init__(*args, **kwargs) # type: ignore[arg-type] + + async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: dict[str, Any]) -> None: + self.params["pool_id"] = self.pool_id + self.params["prefix_id"] = self.prefix_id + self.params["identifier"] = self.identifier + + global_branch = registry.get_global_branch() + self.params["rel_prop"] = { + "branch": global_branch.name, + "branch_level": global_branch.hierarchy_level, + "status": RelationshipStatus.ACTIVE.value, + "from": self.at.to_string(), + "identifier": self.identifier, + } + + query = """ + MATCH (pool:%(prefix_pool)s { uuid: $pool_id }) + MATCH (prefix:Node { uuid: $prefix_id }) + CREATE (pool)-[rel:IS_RESERVED $rel_prop]->(prefix) + """ % {"prefix_pool": InfrahubKind.IPPREFIXPOOL} + + self.add_to_query(query) + self.return_labels = ["pool", "rel", "prefix"] diff --git a/backend/infrahub/core/query/utils.py b/backend/infrahub/core/query/utils.py index 82a72c4b24..ff47e384cc 100644 --- a/backend/infrahub/core/query/utils.py +++ b/backend/infrahub/core/query/utils.py @@ -2,21 +2,21 @@ from typing import TYPE_CHECKING, Optional, Union -from infrahub.core import registry from infrahub.core.schema import NodeSchema, ProfileSchema if TYPE_CHECKING: from neo4j.graph import Node as Neo4jNode from infrahub.core.branch import Branch + from infrahub.database import InfrahubDatabase def find_node_schema( - node: Neo4jNode, branch: Union[Branch, str], duplicate: bool + db: InfrahubDatabase, node: Neo4jNode, branch: Union[Branch, str], duplicate: bool = False ) -> Optional[Union[NodeSchema, ProfileSchema]]: for label in node.labels: - if registry.schema.has(name=label, branch=branch): - schema = registry.schema.get(name=label, branch=branch, duplicate=duplicate) + if db.schema.has(name=label, branch=branch): + schema = db.schema.get(name=label, branch=branch, duplicate=duplicate) if isinstance(schema, (NodeSchema, ProfileSchema)): return schema diff --git a/backend/infrahub/core/relationship/constraints/count.py b/backend/infrahub/core/relationship/constraints/count.py index f45044931b..0d8d17e565 100644 --- a/backend/infrahub/core/relationship/constraints/count.py +++ b/backend/infrahub/core/relationship/constraints/count.py @@ -27,12 +27,10 @@ def __init__(self, db: InfrahubDatabase, branch: Optional[Branch] = None): async def check(self, relm: RelationshipManager) -> None: branch = await registry.get_branch(db=self.db) if not self.branch else self.branch - ( - _, - peer_ids_present_local_only, - peer_ids_present_database_only, - _, - ) = await relm.fetch_relationship_ids(db=self.db) + + # NOTE adding resolve here because we need to retrieve the real ID + # but if the validation fails we'll end up with some allocated resources that are not being used + await relm.resolve(db=self.db) nodes_to_validate: List[NodeToValidate] = [] @@ -46,18 +44,19 @@ async def check(self, relm: RelationshipManager) -> None: if not peer_rels: return + update_details = await relm.fetch_relationship_ids(db=self.db, force_refresh=False) for peer_rel in peer_rels: # If a relationship is directional and both have the same direction they can't work together if relm.schema.direction == peer_rel.direction and peer_rel.direction != RelationshipDirection.BIDIR: continue - for peer_id in peer_ids_present_local_only + peer_ids_present_database_only: - if peer_rel.max_count and peer_id in peer_ids_present_local_only: + for peer_id in update_details.peer_ids_present_local_only + update_details.peer_ids_present_database_only: + if peer_rel.max_count and peer_id in update_details.peer_ids_present_local_only: nodes_to_validate.append( NodeToValidate(uuid=peer_id, max_count=peer_rel.max_count, cardinality=peer_rel.cardinality) ) - if peer_rel.min_count and peer_id in peer_ids_present_database_only: + if peer_rel.min_count and peer_id in update_details.peer_ids_present_database_only: nodes_to_validate.append( NodeToValidate(uuid=peer_id, min_count=peer_rel.min_count, cardinality=peer_rel.cardinality) ) diff --git a/backend/infrahub/core/relationship/constraints/peer_kind.py b/backend/infrahub/core/relationship/constraints/peer_kind.py new file mode 100644 index 0000000000..1cb224caa4 --- /dev/null +++ b/backend/infrahub/core/relationship/constraints/peer_kind.py @@ -0,0 +1,63 @@ +from dataclasses import dataclass +from typing import Optional + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import RelationshipCardinality +from infrahub.core.query.node import NodeListGetInfoQuery +from infrahub.core.schema.generic_schema import GenericSchema +from infrahub.database import InfrahubDatabase +from infrahub.exceptions import ValidationError + +from ..model import RelationshipManager +from .interface import RelationshipManagerConstraintInterface + + +@dataclass +class NodeToValidate: + uuid: str + cardinality: RelationshipCardinality + min_count: Optional[int] = None + max_count: Optional[int] = None + + +class RelationshipPeerKindConstraint(RelationshipManagerConstraintInterface): + def __init__(self, db: InfrahubDatabase, branch: Optional[Branch] = None): + self.db = db + self.branch = branch + + async def check(self, relm: RelationshipManager) -> None: + branch = await registry.get_branch(db=self.db) if not self.branch else self.branch + peer_schema = registry.schema.get(name=relm.schema.peer, branch=branch, duplicate=False) + if isinstance(peer_schema, GenericSchema): + allowed_kinds = peer_schema.used_by + else: + allowed_kinds = [peer_schema.kind] + relationships = await relm.get_relationships(db=self.db, force_refresh=False) + if not relationships: + return + + peer_ids = [r.peer_id for r in relationships] + peers_query = await NodeListGetInfoQuery.init(db=self.db, branch=branch, ids=peer_ids) + await peers_query.execute(db=self.db) + + errors: list[ValidationError] = [] + async for peer_node in peers_query.get_nodes(db=self.db, duplicate=False): + if not peer_node.schema: + raise ValueError(f"Cannot identify schema for node {peer_node.node_uuid}") + if peer_node.schema.kind not in allowed_kinds: + errors.append( + ValidationError( + { + relm.name: ( + f"{peer_node.schema.kind} - {peer_node.node_uuid} cannot be added to relationship, " + f"must be of type: {allowed_kinds}" + ) + } + ) + ) + + if not errors: + return + + raise ValidationError(errors) diff --git a/backend/infrahub/core/relationship/model.py b/backend/infrahub/core/relationship/model.py index f6e1705b3c..703c3eac5e 100644 --- a/backend/infrahub/core/relationship/model.py +++ b/backend/infrahub/core/relationship/model.py @@ -1,10 +1,12 @@ from __future__ import annotations +import copy import sys -from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union from infrahub_sdk import UUIDT -from infrahub_sdk.utils import intersection +from infrahub_sdk.utils import intersection, is_valid_uuid from pydantic.v1 import BaseModel, Field from infrahub.core import registry @@ -37,7 +39,7 @@ from infrahub.core.schema import MainSchemaTypes, RelationshipSchema from infrahub.database import InfrahubDatabase -# pylint: disable=redefined-builtin +# pylint: disable=redefined-builtin,too-many-lines PREFIX_PROPERTY = "_relation__" @@ -60,6 +62,14 @@ class RelationshipCreateData(BaseModel): owner_prop: List[NodePropertyData] = Field(default_factory=list) +@dataclass +class RelationshipUpdateDetails: + peers_database: dict[str, RelationshipPeerData] + peer_ids_present_both: list[str] + peer_ids_present_local_only: list[str] + peer_ids_present_database_only: list[str] + + class Relationship(FlagPropertyMixin, NodePropertyMixin): rel_type: str = "IS_RELATED" @@ -90,7 +100,10 @@ def __init__( self._peer: Optional[Union[Node, str]] = None self.peer_id: Optional[str] = None - self.data: Optional[Union[Dict, RelationshipPeerData, str]] = None + self.peer_hfid: Optional[list[str]] = None + self.data: Optional[Union[dict, RelationshipPeerData, str]] = None + + self.from_pool: Optional[dict[str, Any]] = None self._init_node_property_mixin(kwargs=kwargs) self._init_flag_property_mixin(kwargs=kwargs) @@ -109,7 +122,8 @@ def __hash__(self) -> int: def get_peer_id(self) -> str: if not self.peer_id: - raise ValueError("Relationship has not been initialized") + raise ValueError("Relationship has not been initialized yet") + return self.peer_id @property @@ -131,11 +145,11 @@ def get_branch_based_on_support_type(self) -> Branch: return registry.get_global_branch() return self.branch - async def _process_data(self, data: Union[Dict, RelationshipPeerData, str]) -> None: + async def _process_data(self, data: Union[Dict, RelationshipPeerData, str]) -> None: # pylint: disable=too-many-branches self.data = data if isinstance(data, RelationshipPeerData): - await self.set_peer(str(data.peer_id)) + await self.set_peer(value=str(data.peer_id)) if not self.id and data.rel_node_id: self.id = data.rel_node_id @@ -153,10 +167,15 @@ async def _process_data(self, data: Union[Dict, RelationshipPeerData, str]) -> N for key, value in data.items(): if key in ["peer", "id"]: await self.set_peer(value=data.get(key, None)) + elif key == "hfid" and self.peer_id is None: + self.peer_hfid = value elif key.startswith(PREFIX_PROPERTY) and key.replace(PREFIX_PROPERTY, "") in self._flag_properties: setattr(self, key.replace(PREFIX_PROPERTY, ""), value) elif key.startswith(PREFIX_PROPERTY) and key.replace(PREFIX_PROPERTY, "") in self._node_properties: setattr(self, key.replace(PREFIX_PROPERTY, ""), value) + elif key == "from_pool": + self.from_pool = value + else: await self.set_peer(value=data) @@ -202,7 +221,7 @@ async def get_node(self, db: InfrahubDatabase) -> Node: node = await registry.manager.get_one_by_id_or_default_filter( db=db, id=self.node_id, - schema_name=self.schema.kind, + kind=self.schema.kind, branch=self.branch, at=self.at, include_owner=True, @@ -239,7 +258,7 @@ async def _get_peer(self, db: InfrahubDatabase) -> None: peer = await registry.manager.get_one_by_id_or_default_filter( db=db, id=self.get_peer_id(), - schema_name=self.schema.peer, + kind=self.schema.peer, branch=self.branch, at=self.at, include_owner=True, @@ -252,8 +271,8 @@ async def _get_peer(self, db: InfrahubDatabase) -> None: self._peer = peer self.peer_id = self._peer.id - def get_peer_schema(self) -> MainSchemaTypes: - return registry.schema.get(name=self.schema.peer, branch=self.branch, duplicate=False) + def get_peer_schema(self, db: InfrahubDatabase) -> MainSchemaTypes: + return db.schema.get(name=self.schema.peer, branch=self.branch, duplicate=False) def compare_properties_with_data(self, data: RelationshipPeerData) -> List[str]: different_properties = [] @@ -354,6 +373,50 @@ async def delete(self, db: InfrahubDatabase, at: Optional[Timestamp] = None) -> ) await delete_query.execute(db=db) + async def resolve(self, db: InfrahubDatabase) -> None: + """Resolve the peer of the relationship.""" + + if self._peer is not None: + return + + if self.peer_id and not is_valid_uuid(self.peer_id): + peer = await registry.manager.get_one_by_default_filter( + db=db, id=self.peer_id, branch=self.branch, kind=self.schema.peer, fields={"display_label": None} + ) + if peer: + await self.set_peer(value=peer) + + if not self.peer_id and self.peer_hfid: + peer = await registry.manager.get_one_by_hfid( + db=db, hfid=self.peer_hfid, branch=self.branch, kind=self.schema.peer, fields={"display_label": None} + ) + if peer: + await self.set_peer(value=peer) + + if not self.peer_id and self.from_pool and "id" in self.from_pool: + pool_id = str(self.from_pool.get("id")) + pool = await registry.manager.get_one(db=db, id=pool_id, branch=self.branch) + + if not pool: + raise NodeNotFoundError( + node_type="CoreResourcePool", + identifier=pool_id, + branch_name=self.branch.name, + message=f"Unable to find the pool to generate a node for the relationship {self.name!r} on {self.node_id!r}", + ) + + data_from_pool = copy.deepcopy(self.from_pool) + del data_from_pool["id"] + + if "identifier" not in data_from_pool and self._node: + hfid_str = await self._node.get_hfid_as_string(db=db, include_kind=True) + if hfid_str: + data_from_pool["identifier"] = f"hfid={hfid_str} rel={self.name}" + + assigned_peer: Node = await pool.get_resource(db=db, branch=self.branch, **data_from_pool) # type: ignore[attr-defined] + await self.set_peer(value=assigned_peer) + self.set_source(value=pool.id) + async def save(self, db: InfrahubDatabase, at: Optional[Timestamp] = None) -> Self: """Create or Update the Relationship in the database.""" @@ -413,6 +476,8 @@ async def get_create_data(self, db: InfrahubDatabase) -> RelationshipCreateData: branch = self.get_branch_based_on_support_type() + await self.resolve(db=db) + peer = await self.get_peer(db=db) data = RelationshipCreateData( uuid=str(UUIDT()), @@ -446,6 +511,7 @@ class RelationshipValidatorList: def __init__( self, *relationships: Relationship, + name: str, min_count: int = 0, max_count: int = 0, ) -> None: @@ -462,6 +528,7 @@ def __init__( raise ValidationError({"msg": "max_count must be greater than min_count"}) self.min_count: int = min_count self.max_count: int = max_count + self.name = name self._relationships: List[Relationship] = [rel for rel in relationships if isinstance(rel, Relationship)] self._relationships_count: int = len(self._relationships) @@ -470,9 +537,9 @@ def __init__( # Allow this class to be instantiated without relationships if self._relationships: if self.max_count and self._relationships_count > self.max_count: - raise ValidationError({relationships[0].node_id: f"Too many relationships, max {self.max_count}"}) + self._raise_too_many() if self.min_count and self._relationships_count < self.min_count: - raise ValidationError({relationships[0].node_id: f"Too few relationships, min {self.min_count}"}) + self._raise_too_few() def __contains__(self, item: Relationship) -> bool: return item in self._relationships @@ -495,7 +562,7 @@ def __setitem__(self, index: int, value: Relationship) -> None: def __delitem__(self, index: int) -> None: if self._relationships_count - 1 < self.min_count: - raise ValidationError({self._relationships[0].name: f"Too few relationships, min {self.min_count}"}) + self._raise_too_few() del self._relationships[index] def __len__(self) -> int: @@ -516,9 +583,7 @@ def append(self, rel: Relationship) -> None: # If the max_count is greater than 0 then validate if self.max_count and self._relationships_count + 1 > self.max_count: - raise ValidationError( - {rel.name: f"Too many relationships, max {self.max_count}, count {self._relationships_count}"} - ) + self._raise_too_many() self._relationships.append(rel) self._relationships_count += 1 @@ -533,7 +598,7 @@ def extend(self, iterable: Iterable[Relationship]) -> None: rel_len = len(relationships) # If the max_count is greater than 0 then validate if self.max_count and self._relationships_count + rel_len > self.max_count: - raise ValidationError({self._relationships[0].name: f"Too many relationships, max {self.max_count}"}) + self._raise_too_many() self._relationships.extend(relationships) self._relationships_count += rel_len @@ -550,13 +615,13 @@ def insert(self, index: int, value: Relationship) -> None: if not isinstance(value, Relationship): raise ValidationError("RelationshipValidatorList only accepts Relationship objects") if self.max_count and self._relationships_count + 1 > self.max_count: - raise ValidationError({value.name: f"Too many relationships, max {self.max_count}"}) + self._raise_too_many() self._relationships.insert(index, value) self._relationships_count += 1 def pop(self, idx: int = -1) -> Relationship: if self.min_count and self._relationships_count - 1 < self.min_count: - raise ValidationError({self._relationships[0].name: f"Too few relationships, min {self.min_count}"}) + self._raise_too_few() result = self._relationships.pop(idx) self._relationships_count -= 1 @@ -564,13 +629,35 @@ def pop(self, idx: int = -1) -> Relationship: def remove(self, value: Relationship) -> None: if self.min_count and self._relationships_count - 1 < self.min_count: - raise ValidationError({self._relationships[0].name: f"Too few relationships, min {self.min_count}"}) + self._raise_too_few() self._relationships.remove(value) self._relationships_count -= 1 def as_list(self) -> List[Relationship]: return self._relationships + def _raise_too_few(self) -> None: + raise ValidationError({self.name: f"Too few relationships, min {self.min_count}"}) + + def _raise_too_many(self) -> None: + raise ValidationError({self.name: f"Too many relationships, max {self.max_count}"}) + + def validate_min(self) -> None: + if not self.min_count: + return + if self._relationships_count < self.min_count: + raise ValidationError({self.name: f"Too few relationships, min {self.min_count}"}) + + def validate_max(self) -> None: + if not self.max_count: + return + if self._relationships_count > self.max_count: + raise ValidationError({self.name: f"Too many relationships, max {self.max_count}"}) + + def validate(self) -> None: + self.validate_min() + self.validate_max() + class RelationshipManager: def __init__(self, schema: RelationshipSchema, branch: Branch, at: Timestamp, node: Node) -> None: @@ -584,9 +671,11 @@ def __init__(self, schema: RelationshipSchema, branch: Branch, at: Timestamp, no self.rel_class = Relationship self._relationships: RelationshipValidatorList = RelationshipValidatorList( - min_count=self.schema.min_count, + name=self.schema.name, + min_count=0 if self.schema.optional else self.schema.min_count, max_count=self.schema.max_count, ) + self._relationship_id_details: Optional[RelationshipUpdateDetails] = None self.has_fetched_relationships: bool = False @classmethod @@ -654,10 +743,12 @@ async def get_peer(self, db: InfrahubDatabase) -> Optional[Node]: return await rels[0].get_peer(db=db) - async def get_peers(self, db: InfrahubDatabase) -> Dict[str, Node]: - rels = await self.get_relationships(db=db) + async def get_peers(self, db: InfrahubDatabase, branch_agnostic: bool = False) -> Dict[str, Node]: + rels = await self.get_relationships(db=db, branch_agnostic=branch_agnostic) peer_ids = [rel.peer_id for rel in rels if rel.peer_id] - nodes = await registry.manager.get_many(db=db, ids=peer_ids, branch=self.branch) + nodes = await registry.manager.get_many( + db=db, ids=peer_ids, branch=self.branch, branch_agnostic=branch_agnostic + ) return nodes def get_branch_based_on_support_type(self) -> Branch: @@ -672,13 +763,20 @@ def get_branch_based_on_support_type(self) -> Branch: return self.branch async def fetch_relationship_ids( - self, db: InfrahubDatabase, at: Optional[Timestamp] = None - ) -> Tuple[List[str], List[str], List[str], Dict[str, RelationshipPeerData]]: + self, + db: InfrahubDatabase, + at: Optional[Timestamp] = None, + branch_agnostic: bool = False, + force_refresh: bool = True, + ) -> RelationshipUpdateDetails: """Fetch the latest relationships from the database and returns : - the list of nodes present on both sides - the list of nodes present only locally - the list of nodes present only in the database """ + if not force_refresh and self._relationship_id_details is not None: + return self._relationship_id_details + current_peer_ids = [rel.get_peer_id() for rel in self._relationships] query = await RelationshipGetPeerQuery.init( @@ -686,6 +784,7 @@ async def fetch_relationship_ids( source=self.node, at=at or self.at, rel=self.rel_class(schema=self.schema, branch=self.branch, node=self.node), + branch_agnostic=branch_agnostic, ) await query.execute(db=db) @@ -697,31 +796,40 @@ async def fetch_relationship_ids( peer_ids_present_local_only = list(set(current_peer_ids) - set(peer_ids_present_both)) peer_ids_present_database_only = list(set(peer_ids) - set(peer_ids_present_both)) - return peer_ids_present_both, peer_ids_present_local_only, peer_ids_present_database_only, peers_database + self._relationship_id_details = RelationshipUpdateDetails( + peer_ids_present_both=peer_ids_present_both, + peer_ids_present_local_only=peer_ids_present_local_only, + peer_ids_present_database_only=peer_ids_present_database_only, + peers_database=peers_database, + ) + return self._relationship_id_details - async def _fetch_relationships(self, db: InfrahubDatabase, at: Optional[Timestamp] = None) -> None: + async def _fetch_relationships( + self, + db: InfrahubDatabase, + at: Optional[Timestamp] = None, + branch_agnostic: bool = False, + force_refresh: bool = True, + ) -> None: """Fetch the latest relationships from the database and update the local cache.""" - ( - _, - peer_ids_present_local_only, - peer_ids_present_database_only, - peers_database, - ) = await self.fetch_relationship_ids(at=at, db=db) + details = await self.fetch_relationship_ids( + at=at, db=db, branch_agnostic=branch_agnostic, force_refresh=force_refresh + ) - for peer_id in peer_ids_present_database_only: + for peer_id in details.peer_ids_present_database_only: self._relationships.append( await Relationship( schema=self.schema, branch=self.branch, at=at or self.at, node=self.node, - ).load(db=db, data=peers_database[peer_id]) + ).load(db=db, data=details.peers_database[peer_id]) ) self.has_fetched_relationships = True - for peer_id in peer_ids_present_local_only: + for peer_id in details.peer_ids_present_local_only: await self.remove(peer_id=peer_id, db=db) async def get(self, db: InfrahubDatabase) -> Union[Relationship, List[Relationship]]: @@ -732,9 +840,11 @@ async def get(self, db: InfrahubDatabase) -> Union[Relationship, List[Relationsh return rels - async def get_relationships(self, db: InfrahubDatabase) -> List[Relationship]: - if not self.has_fetched_relationships: - await self._fetch_relationships(db=db) + async def get_relationships( + self, db: InfrahubDatabase, branch_agnostic: bool = False, force_refresh: bool = False + ) -> List[Relationship]: + if force_refresh or not self.has_fetched_relationships: + await self._fetch_relationships(db=db, branch_agnostic=branch_agnostic, force_refresh=force_refresh) return self._relationships.as_list() @@ -794,6 +904,9 @@ async def update( # pylint: disable=too-many-branches if set(list(previous_relationships.keys())) <= {rel.peer_id for rel in await self.get_relationships(db=db)}: changed = True + if changed: + self._relationships.validate() + return changed async def add(self, data: Union[Dict[str, Any], Node], db: InfrahubDatabase) -> bool: @@ -819,13 +932,17 @@ async def add(self, data: Union[Dict[str, Any], Node], db: InfrahubDatabase) -> return True + async def resolve(self, db: InfrahubDatabase) -> None: + for rel in self._relationships: + await rel.resolve(db=db) + async def remove( self, peer_id: Union[str, UUID], db: InfrahubDatabase, update_db: bool = False, ) -> bool: - """Remote a peer id from the local relationships list, + """Remove a peer id from the local relationships list, need to investigate if and when we should update the relationship in the database.""" for idx, rel in enumerate(await self.get_relationships(db=db)): @@ -870,32 +987,31 @@ async def remove_in_db( async def save(self, db: InfrahubDatabase, at: Optional[Timestamp] = None) -> Self: """Create or Update the Relationship in the database.""" + await self.resolve(db=db) + save_at = Timestamp(at) - ( - peer_ids_present_both, - peer_ids_present_local_only, - peer_ids_present_database_only, - peers_database, - ) = await self.fetch_relationship_ids(db=db) + details = await self.fetch_relationship_ids(db=db, force_refresh=True) # If we have previously fetched the relationships from the database # Update the one in the database that shouldn't be here. if self.has_fetched_relationships: - for peer_id in peer_ids_present_database_only: - await self.remove_in_db(peer_data=peers_database[peer_id], at=save_at, db=db) + for peer_id in details.peer_ids_present_database_only: + await self.remove_in_db(peer_data=details.peers_database[peer_id], at=save_at, db=db) # Create the new relationship that are not present in the database # and Compare the existing one for rel in await self.get_relationships(db=db): - if rel.peer_id in peer_ids_present_local_only: + if rel.peer_id in details.peer_ids_present_local_only: await rel.save(at=save_at, db=db) - elif rel.peer_id in peer_ids_present_both: - if properties_not_matching := rel.compare_properties_with_data(data=peers_database[rel.peer_id]): + elif rel.peer_id in details.peer_ids_present_both: + if properties_not_matching := rel.compare_properties_with_data( + data=details.peers_database[rel.peer_id] + ): await rel.update( at=save_at, properties_to_update=properties_not_matching, - data=peers_database[rel.peer_id], + data=details.peers_database[rel.peer_id], db=db, ) @@ -910,7 +1026,7 @@ async def delete( delete_at = Timestamp(at) - await self._fetch_relationships(at=delete_at, db=db) + await self._fetch_relationships(at=delete_at, db=db, force_refresh=True) for rel in await self.get_relationships(db=db): await rel.delete(at=delete_at, db=db) diff --git a/backend/infrahub/core/schema/basenode_schema.py b/backend/infrahub/core/schema/basenode_schema.py index 2a0854fa39..91baf5a2ee 100644 --- a/backend/infrahub/core/schema/basenode_schema.py +++ b/backend/infrahub/core/schema/basenode_schema.py @@ -19,9 +19,9 @@ if TYPE_CHECKING: from typing_extensions import Self - from infrahub.core.branch import Branch from infrahub.core.constants import RelationshipKind from infrahub.core.schema import GenericSchema, NodeSchema + from infrahub.core.schema_manager import SchemaBranch # pylint: disable=redefined-builtin @@ -33,6 +33,18 @@ class BaseNodeSchema(GeneratedBaseNodeSchema): # pylint: disable=too-many-publi _exclude_from_hash: List[str] = ["attributes", "relationships", "filters"] _sort_by: List[str] = ["namespace", "name"] + @property + def is_node_schema(self) -> bool: + return False + + @property + def is_generic_schema(self) -> bool: + return False + + @property + def is_profile_schema(self) -> bool: + return False + @property def kind(self) -> str: if self.namespace == "Attribute": @@ -103,7 +115,7 @@ def _diff_element( get_func: Callable, get_map_func: Callable, obj_type: Union[Type[AttributeSchema], Type[RelationshipSchema], Type[FilterSchema]], - ): + ) -> HashableModelDiff: """The goal of this function is to reduce the amount of code duplicated between Attribute and Relationship to calculate a diff The logic is the same for both, except that the functions we are using to access these objects are differents @@ -212,7 +224,13 @@ def get_relationship_by_id(self, id: str) -> RelationshipSchema: raise ValueError(f"Unable to find the relationship with the ID: {id}") - def get_filter(self, name, raise_on_error: bool = True) -> FilterSchema: + @overload + def get_filter(self, name: str, raise_on_error: Literal[True] = True) -> FilterSchema: ... + + @overload + def get_filter(self, name: str, raise_on_error: Literal[False] = False) -> Optional[FilterSchema]: ... + + def get_filter(self, name: str, raise_on_error: bool = True) -> Optional[FilterSchema]: for item in self.filters: if item.name == name: return item @@ -228,7 +246,15 @@ def get_relationship_or_none(self, name: str) -> Optional[RelationshipSchema]: return item return None - def get_relationship_by_identifier(self, id: str, raise_on_error: bool = True) -> RelationshipSchema: + @overload + def get_relationship_by_identifier(self, id: str, raise_on_error: Literal[True] = True) -> RelationshipSchema: ... + + @overload + def get_relationship_by_identifier( + self, id: str, raise_on_error: Literal[False] = False + ) -> Optional[RelationshipSchema]: ... + + def get_relationship_by_identifier(self, id: str, raise_on_error: bool = True) -> Optional[RelationshipSchema]: for item in self.relationships: if item.identifier == id: return item @@ -308,26 +334,44 @@ def local_relationships(self) -> List[RelationshipSchema]: def unique_attributes(self) -> List[AttributeSchema]: return [item for item in self.attributes if item.unique] - def generate_fields_for_display_label(self) -> Dict: + @classmethod + def convert_path_to_graphql_fields(cls, path: str) -> dict: + subpaths = path.split("__", maxsplit=1) + fields = {} + if len(subpaths) == 1: + fields[subpaths[0]] = None + elif len(subpaths) == 2: + fields[subpaths[0]] = cls.convert_path_to_graphql_fields(path=subpaths[1]) + return fields + + def generate_fields_for_display_label(self) -> Optional[dict]: """Generate a Dictionary containing the list of fields that are required to generate the display_label. If display_labels is not defined, we return None which equal to everything. """ - if not hasattr(self, "display_labels") or not isinstance(self.display_labels, list): + if not self.display_labels: return None fields: dict[str, Union[str, None, dict[str, None]]] = {} for item in self.display_labels: - elements = item.split("__") - if len(elements) == 1: - fields[elements[0]] = None - elif len(elements) == 2: - fields[elements[0]] = {elements[1]: None} - else: - raise ValueError(f"Unexpected value for display_labels, {item} is not valid.") + fields.update(self.convert_path_to_graphql_fields(path=item)) + return fields + def generate_fields_for_hfid(self) -> Optional[dict]: + """Generate a Dictionary containing the list of fields that are required + to generate the hfid. + + If display_labels is not defined, we return None which equal to everything. + """ + + if not self.human_friendly_id: + return None + + fields: dict[str, Union[str, None, dict[str, None]]] = {} + for item in self.human_friendly_id: + fields.update(self.convert_path_to_graphql_fields(path=item)) return fields @field_validator("name") @@ -338,18 +382,13 @@ def name_is_not_keyword(cls, value: str) -> str: return value - def parse_attribute_path( - self, - attribute_path: str, - branch: Optional[Union[Branch, str]] = None, - schema_map_override: Optional[Dict[str, Union[NodeSchema, GenericSchema]]] = None, - ) -> SchemaAttributePath: - allowed_leaf_properties = ["value", "version", "binary_address"] + def parse_schema_path(self, path: str, schema: Optional[SchemaBranch] = None) -> SchemaAttributePath: schema_path = SchemaAttributePath() relationship_piece: Optional[str] = None attribute_piece: Optional[str] = None property_piece: Optional[str] = None - path_parts = attribute_path.split("__") + + path_parts = path.split("__") if path_parts[0] in self.relationship_names: relationship_piece = path_parts[0] attribute_piece = path_parts[1] if len(path_parts) > 1 else None @@ -358,34 +397,36 @@ def parse_attribute_path( attribute_piece = path_parts[0] property_piece = path_parts[1] if len(path_parts) > 1 else None else: - raise AttributePathParsingError(f"{attribute_path} is invalid on schema {self.kind}") + raise AttributePathParsingError(f"{path} is invalid on schema {self.kind}") + + if relationship_piece and not schema: + raise AttributePathParsingError("schema must be provided in order to check a path with a relationship") + if relationship_piece: - if relationship_piece not in self.relationship_names: - raise AttributePathParsingError(f"{relationship_piece} is not a relationship of schema {self.kind}") - relationship_schema = self.get_relationship(path_parts[0]) + relationship_schema = self.get_relationship(name=path_parts[0]) schema_path.relationship_schema = relationship_schema - if schema_map_override: - try: - schema_path.related_schema = schema_map_override.get(relationship_schema.peer) - except KeyError as exc: - raise AttributePathParsingError(f"No schema {relationship_schema.peer} in map") from exc - else: - schema_path.related_schema = relationship_schema.get_peer_schema(branch=branch) + schema_path.related_schema = schema.get(name=relationship_schema.peer, duplicate=True) + if attribute_piece: schema_to_check = schema_path.related_schema or self if attribute_piece not in schema_to_check.attribute_names: raise AttributePathParsingError(f"{attribute_piece} is not a valid attribute of {schema_to_check.kind}") - schema_path.attribute_schema = schema_to_check.get_attribute(attribute_piece) - if property_piece: - if property_piece not in allowed_leaf_properties: - raise AttributePathParsingError( - f"{property_piece} is not a valid property of {schema_path.attribute_schema.name}" - ) - schema_path.attribute_property_name = property_piece + schema_path.attribute_schema = schema_to_check.get_attribute(name=attribute_piece) + + if property_piece: + attr_class = schema_path.attribute_schema.get_class() + if property_piece not in attr_class.get_allowed_property_in_path(): + raise AttributePathParsingError( + f"{property_piece} is not a valid property of {schema_path.attribute_schema.name}" + ) + schema_path.attribute_property_name = property_piece + return schema_path def get_unique_constraint_schema_attribute_paths( - self, include_unique_attributes: bool = False, branch: Optional[Branch] = None + self, + schema_branch: SchemaBranch, + include_unique_attributes: bool = False, ) -> List[List[SchemaAttributePath]]: constraint_paths_groups = [] if include_unique_attributes: @@ -400,7 +441,7 @@ def get_unique_constraint_schema_attribute_paths( for uniqueness_path_group in self.uniqueness_constraints: constraint_paths_groups.append( [ - self.parse_attribute_path(attribute_path=uniqueness_path_part, branch=branch) + self.parse_schema_path(path=uniqueness_path_part, schema=schema_branch) for uniqueness_path_part in uniqueness_path_group ] ) @@ -414,6 +455,18 @@ class SchemaAttributePath: attribute_schema: Optional[AttributeSchema] = None attribute_property_name: Optional[str] = None + @property + def is_type_attribute(self) -> bool: + return bool(self.attribute_schema and not self.related_schema and not self.relationship_schema) + + @property + def is_type_relationship(self) -> bool: + return bool(self.relationship_schema and self.related_schema) + + @property + def has_property(self) -> bool: + return bool(self.attribute_property_name) + @dataclass class SchemaAttributePathValue(SchemaAttributePath): diff --git a/backend/infrahub/core/schema/definitions/core.py b/backend/infrahub/core/schema/definitions/core.py index 5e9bb99152..f3e2f6526b 100644 --- a/backend/infrahub/core/schema/definitions/core.py +++ b/backend/infrahub/core/schema/definitions/core.py @@ -658,6 +658,33 @@ }, ], }, + { + "name": "ResourcePool", + "namespace": "Core", + "label": "Resource Pool", + "description": "The resource manager contains pools of resources to allow for automatic assignments.", + "include_in_menu": False, + "default_filter": "name__value", + "order_by": ["name__value"], + "display_labels": ["name__value"], + "human_friendly_id": ["name__value"], + "icon": "mdi:view-grid-outline", + "branch": BranchSupportType.AGNOSTIC.value, + "attributes": [ + { + "name": "name", + "kind": "Text", + "order_weight": 1000, + "unique": True, + }, + { + "name": "description", + "kind": "Text", + "optional": True, + "order_weight": 2000, + }, + ], + }, ], "nodes": [ { @@ -1348,7 +1375,13 @@ {"name": "name", "kind": "Text", "unique": True}, {"name": "description", "kind": "Text", "optional": True}, {"name": "query", "kind": "TextArea"}, - {"name": "variables", "kind": "JSON", "description": "variables in use in the query", "optional": True}, + { + "name": "variables", + "kind": "JSON", + "description": "variables in use in the query", + "optional": True, + "read_only": True, + }, { "name": "operations", "kind": "List", @@ -1625,6 +1658,7 @@ "description": "A namespace that segments IPAM", "label": "IPAM Namespace", "default_filter": "name__value", + "human_friendly_id": ["name__value"], "order_by": ["name__value"], "display_labels": ["name__value"], "include_in_menu": False, @@ -1635,5 +1669,104 @@ {"name": "default", "kind": "Boolean", "optional": True, "read_only": True, "order_weight": 9000} ], }, + { + "name": "IPPrefixPool", + "namespace": "Core", + "description": "A pool of IP prefix resources", + "label": "IP Prefix Pool", + "include_in_menu": False, + "branch": BranchSupportType.AGNOSTIC.value, + "inherit_from": [InfrahubKind.RESOURCEPOOL, InfrahubKind.LINEAGESOURCE], + "attributes": [ + { + "name": "default_prefix_length", + "kind": "Number", + "optional": True, + "order_weight": 5000, + }, + { + "name": "default_member_type", + "kind": "Text", + "enum": ["prefix", "address"], + "default_value": "prefix", + "optional": True, + "order_weight": 3000, + }, + { + "name": "default_prefix_type", + "kind": "Text", + "optional": True, + "order_weight": 4000, + }, + ], + "relationships": [ + { + "name": "resources", + "peer": "BuiltinIPPrefix", + "kind": "Attribute", + "identifier": "prefixpool__resource", + "cardinality": "many", + "branch": BranchSupportType.AGNOSTIC.value, + "optional": False, + "order_weight": 6000, + }, + { + "name": "ip_namespace", + "peer": "BuiltinIPNamespace", + "kind": "Attribute", + "identifier": "prefixpool__ipnamespace", + "cardinality": "one", + "branch": BranchSupportType.AGNOSTIC.value, + "optional": False, + "order_weight": 7000, + }, + ], + }, + { + "name": "IPAddressPool", + "namespace": "Core", + "description": "A pool of IP address resources", + "label": "IP Address Pool", + "include_in_menu": False, + "branch": BranchSupportType.AGNOSTIC.value, + "inherit_from": [InfrahubKind.RESOURCEPOOL, InfrahubKind.LINEAGESOURCE], + "attributes": [ + { + "name": "default_address_type", + "kind": "Text", + "optional": False, + "description": "The object type to create when reserving a resource in the pool", + "order_weight": 3000, + }, + { + "name": "default_prefix_length", + "kind": "Number", + "optional": True, + "order_weight": 4000, + }, + ], + "relationships": [ + { + "name": "resources", + "peer": "BuiltinIPPrefix", + "kind": "Attribute", + "identifier": "ipaddresspool__resource", + "cardinality": "many", + "branch": BranchSupportType.AGNOSTIC.value, + "optional": False, + "order_weight": 5000, + }, + { + "name": "ip_namespace", + "peer": "BuiltinIPNamespace", + "kind": "Attribute", + "identifier": "ipaddresspool__ipnamespace", + "cardinality": "one", + "branch": BranchSupportType.AGNOSTIC.value, + "optional": False, + "order_weight": 6000, + }, + ], + }, ], } diff --git a/backend/infrahub/core/schema/definitions/internal.py b/backend/infrahub/core/schema/definitions/internal.py index 321d6ad905..e6b1d38a12 100644 --- a/backend/infrahub/core/schema/definitions/internal.py +++ b/backend/infrahub/core/schema/definitions/internal.py @@ -269,7 +269,15 @@ def to_dict(self) -> dict[str, Any]: name="default_filter", kind="Text", regex=str(NAME_REGEX), - description="Default filter used to search for a node in addition to its ID.", + description="Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead)", + optional=True, + extra={"update": UpdateSupport.ALLOWED}, + ), + SchemaAttribute( + name="human_friendly_id", + kind="List", + internal_kind=str, + description="Human friendly and unique identifier for the object.", optional=True, extra={"update": UpdateSupport.ALLOWED}, ), diff --git a/backend/infrahub/core/schema/generated/base_node_schema.py b/backend/infrahub/core/schema/generated/base_node_schema.py index ffb9319309..48924adefc 100644 --- a/backend/infrahub/core/schema/generated/base_node_schema.py +++ b/backend/infrahub/core/schema/generated/base_node_schema.py @@ -52,10 +52,15 @@ class GeneratedBaseNodeSchema(HashableModel): ) default_filter: Optional[str] = Field( default=None, - description="Default filter used to search for a node in addition to its ID.", + description="Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead)", pattern=r"^[a-z0-9\_]+$", json_schema_extra={"update": "allowed"}, ) + human_friendly_id: Optional[list[str]] = Field( + default=None, + description="Human friendly and unique identifier for the object.", + json_schema_extra={"update": "allowed"}, + ) display_labels: Optional[list[str]] = Field( default=None, description="List of attributes to use to generate the display label", diff --git a/backend/infrahub/core/schema/generic_schema.py b/backend/infrahub/core/schema/generic_schema.py index cb80fb1236..a8fead9214 100644 --- a/backend/infrahub/core/schema/generic_schema.py +++ b/backend/infrahub/core/schema/generic_schema.py @@ -6,12 +6,25 @@ if TYPE_CHECKING: from infrahub.core.branch import Branch + from infrahub.database import InfrahubDatabase class GenericSchema(GeneratedGenericSchema): """A Generic can be either an Interface or a Union depending if there are some Attributes or Relationships defined.""" - def get_hierarchy_schema(self, branch: Optional[Union[Branch, str]] = None) -> GenericSchema: # pylint: disable=unused-argument + @property + def is_node_schema(self) -> bool: + return False + + @property + def is_generic_schema(self) -> bool: + return True + + @property + def is_profile_schema(self) -> bool: + return False + + def get_hierarchy_schema(self, db: InfrahubDatabase, branch: Optional[Union[Branch, str]] = None) -> GenericSchema: # pylint: disable=unused-argument if self.hierarchical: return self diff --git a/backend/infrahub/core/schema/node_schema.py b/backend/infrahub/core/schema/node_schema.py index bb2070083b..42f2db02a3 100644 --- a/backend/infrahub/core/schema/node_schema.py +++ b/backend/infrahub/core/schema/node_schema.py @@ -2,7 +2,6 @@ from typing import TYPE_CHECKING, List, Optional, Union -from infrahub.core import registry from infrahub.core.constants import AllowOverrideType, InfrahubKind from .generated.node_schema import GeneratedNodeSchema @@ -10,9 +9,22 @@ if TYPE_CHECKING: from infrahub.core.branch import Branch + from infrahub.database import InfrahubDatabase class NodeSchema(GeneratedNodeSchema): + @property + def is_node_schema(self) -> bool: + return True + + @property + def is_generic_schema(self) -> bool: + return False + + @property + def is_profile_schema(self) -> bool: + return False + def validate_inheritance(self, interface: GenericSchema) -> None: """Check that protected attributes and relationships are not overriden before inheriting them from interface.""" for attribute in self.attributes: @@ -44,6 +56,19 @@ def inherit_from_interface(self, interface: GenericSchema) -> None: existing_inherited_relationships.keys() ) + properties_to_inherit = [ + "human_friendly_id", + "display_labels", + "default_filter", + "menu_placement", + "uniqueness_constraints", + "icon", + "order_by", + ] + for prop_name in properties_to_inherit: + if getattr(interface, prop_name) and not getattr(self, prop_name): + setattr(self, prop_name, getattr(interface, prop_name)) + for attribute in interface.attributes: if attribute.name in self.valid_input_names: continue @@ -70,10 +95,10 @@ def inherit_from_interface(self, interface: GenericSchema) -> None: item_idx = existing_inherited_relationships[relationship.name] self.relationships[item_idx] = new_relationship - def get_hierarchy_schema(self, branch: Optional[Union[Branch, str]] = None) -> GenericSchema: + def get_hierarchy_schema(self, db: InfrahubDatabase, branch: Optional[Union[Branch, str]] = None) -> GenericSchema: if not self.hierarchy: raise ValueError("The node is not part of a hierarchy") - schema = registry.schema.get(name=self.hierarchy, branch=branch) + schema = db.schema.get(name=self.hierarchy, branch=branch) if not isinstance(schema, GenericSchema): raise TypeError return schema diff --git a/backend/infrahub/core/schema/profile_schema.py b/backend/infrahub/core/schema/profile_schema.py index 0e097d59bd..49543a83b2 100644 --- a/backend/infrahub/core/schema/profile_schema.py +++ b/backend/infrahub/core/schema/profile_schema.py @@ -14,6 +14,18 @@ class ProfileSchema(BaseNodeSchema): description="List of Generic Kind that this profile is inheriting from", ) + @property + def is_node_schema(self) -> bool: + return False + + @property + def is_generic_schema(self) -> bool: + return False + + @property + def is_profile_schema(self) -> bool: + return True + def get_labels(self) -> List[str]: """Return the labels for this object, composed of the kind and the list of Generic this object is inheriting from.""" diff --git a/backend/infrahub/core/schema/relationship_schema.py b/backend/infrahub/core/schema/relationship_schema.py index 22280f068b..11bd25a973 100644 --- a/backend/infrahub/core/schema/relationship_schema.py +++ b/backend/infrahub/core/schema/relationship_schema.py @@ -5,7 +5,6 @@ from pydantic import BaseModel from infrahub import config -from infrahub.core import registry from infrahub.core.constants import RelationshipDirection from infrahub.core.query import QueryNode, QueryRel, QueryRelDirection from infrahub.core.relationship import Relationship @@ -34,8 +33,8 @@ def is_relationship(self) -> bool: def get_class(self) -> type[Relationship]: return Relationship - def get_peer_schema(self, branch: Optional[Union[Branch, str]] = None) -> MainSchemaTypes: - return registry.schema.get(name=self.peer, branch=branch, duplicate=False) + def get_peer_schema(self, db: InfrahubDatabase, branch: Optional[Union[Branch, str]] = None) -> MainSchemaTypes: + return db.schema.get(name=self.peer, branch=branch, duplicate=False) @property def internal_peer(self) -> bool: @@ -79,7 +78,7 @@ async def get_query_filter( query_params[f"{prefix}_rel_name"] = self.identifier rel_type = self.get_class().rel_type - peer_schema = self.get_peer_schema(branch=branch) + peer_schema = self.get_peer_schema(db=db, branch=branch) if include_match: query_filter.append(QueryNode(name="n")) diff --git a/backend/infrahub/core/schema_manager.py b/backend/infrahub/core/schema_manager.py index a741dd0236..e3e4de66f3 100644 --- a/backend/infrahub/core/schema_manager.py +++ b/backend/infrahub/core/schema_manager.py @@ -3,10 +3,11 @@ import copy import hashlib from collections import defaultdict +from itertools import chain from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union from infrahub_sdk.topological_sort import DependencyCycleExistsError, topological_sort -from infrahub_sdk.utils import compare_lists, duplicates, intersection +from infrahub_sdk.utils import compare_lists, deep_merge_dict, duplicates, intersection from pydantic import BaseModel from infrahub import lock @@ -22,6 +23,7 @@ RelationshipDeleteBehavior, RelationshipDirection, RelationshipKind, + SchemaElementPathType, ) from infrahub.core.manager import NodeManager from infrahub.core.migrations import MIGRATION_MAP @@ -422,6 +424,22 @@ def get_schemas_by_rel_identifier(self, identifier: str) -> List[MainSchemaTypes nodes.append(self.get(name=node_name, duplicate=True)) return nodes + def generate_fields_for_display_label(self, name: str) -> Optional[dict]: + node = self.get(name=name, duplicate=False) + if isinstance(node, (NodeSchema, ProfileSchema)): + return node.generate_fields_for_display_label() + + fields: dict[str, Union[str, None, dict[str, None]]] = {} + if isinstance(node, GenericSchema): + for child_node_name in node.used_by: + child_node = self.get(name=child_node_name, duplicate=False) + resp = child_node.generate_fields_for_display_label() + if not resp: + continue + fields = deep_merge_dict(dicta=fields, dictb=resp) + + return fields or None + def load_schema(self, schema: SchemaRoot) -> None: """Load a SchemaRoot object and store all NodeSchema or GenericSchema. @@ -470,6 +488,7 @@ def process_validate(self) -> None: self.validate_order_by() self.validate_default_filters() self.validate_parent_component() + self.validate_human_friendly_id() def process_post_validation(self) -> None: self.add_groups() @@ -480,6 +499,7 @@ def process_post_validation(self) -> None: self.process_labels() self.process_dropdowns() self.process_relationships() + self.process_human_friendly_id() def generate_identifiers(self) -> None: """Generate the identifier for all relationships if it's not already present.""" @@ -550,48 +570,53 @@ def validate_identifiers(self) -> None: f" {rels[0].direction.value} <> {peer_direction.value}" ) from None - def _validate_attribute_path( + def validate_schema_path( self, node_schema: BaseNodeSchema, path: str, - schema_map_override: Dict[str, Union[NodeSchema, GenericSchema]], - relationship_allowed: bool = False, - relationship_attribute_allowed: bool = False, - schema_attribute_name: Optional[str] = None, + allowed_path_types: SchemaElementPathType, + element_name: Optional[str] = None, ) -> SchemaAttributePath: error_header = f"{node_schema.kind}" - error_header += f".{schema_attribute_name}" if schema_attribute_name else "" - allowed_leaf_properties = ["value", "version", "binary_address"] + error_header += f".{element_name}" if element_name else "" + try: - schema_attribute_path = node_schema.parse_attribute_path(path, schema_map_override=schema_map_override) + schema_attribute_path = node_schema.parse_schema_path(path=path, schema=self) except AttributePathParsingError as exc: raise ValueError(f"{error_header}: {exc}") from exc - if schema_attribute_path.relationship_schema: - if not relationship_allowed: - raise ValueError(f"{error_header}: this property only supports attributes, not relationships") - if schema_attribute_path.relationship_schema.cardinality != RelationshipCardinality.ONE: + if not (SchemaElementPathType.ATTR & allowed_path_types) and schema_attribute_path.is_type_attribute: + raise ValueError(f"{error_header}: this property only supports relationships not attributes") + + if not (SchemaElementPathType.ALL_RELS & allowed_path_types) and schema_attribute_path.is_type_relationship: + raise ValueError(f"{error_header}: this property only supports attributes, not relationships") + + if schema_attribute_path.is_type_relationship and schema_attribute_path.relationship_schema: + if ( + schema_attribute_path.relationship_schema.cardinality == RelationshipCardinality.ONE + and not SchemaElementPathType.REL_ONE & allowed_path_types + ): raise ValueError( f"{error_header}: cannot use {schema_attribute_path.relationship_schema.name} relationship," - " relationship must be of cardinality one" + " relationship must be of cardinality many" ) - if not relationship_attribute_allowed and schema_attribute_path.attribute_schema: + if ( + schema_attribute_path.relationship_schema.cardinality == RelationshipCardinality.MANY + and not SchemaElementPathType.REL_MANY & allowed_path_types + ): raise ValueError( - f"{error_header}: cannot use attributes of related node in constraint, only the relationship" + f"{error_header}: cannot use {schema_attribute_path.relationship_schema.name} relationship," + " relationship must be of cardinality one" ) - if ( - schema_attribute_path.attribute_property_name - and schema_attribute_path.attribute_property_name not in allowed_leaf_properties - ): - raise ValueError( - f"{error_header}: attribute property must be one of {allowed_leaf_properties}, not {schema_attribute_path.attribute_property_name}" - ) + if schema_attribute_path.has_property and not SchemaElementPathType.RELS_ATTR & allowed_path_types: + raise ValueError(f"{error_header}: cannot use attributes of related node, only the relationship") + if not schema_attribute_path.has_property and not SchemaElementPathType.RELS_NO_ATTR & allowed_path_types: + raise ValueError(f"{error_header}: Must use attributes of related node") + return schema_attribute_path def validate_uniqueness_constraints(self) -> None: - full_schema_objects = self.to_dict_schema_object() - schema_map = full_schema_objects["nodes"] | full_schema_objects["generics"] for name in self.all_names: node_schema = self.get(name=name, duplicate=False) @@ -600,24 +625,34 @@ def validate_uniqueness_constraints(self) -> None: for constraint_paths in node_schema.uniqueness_constraints: for constraint_path in constraint_paths: - self._validate_attribute_path( - node_schema, - constraint_path, - schema_map, - schema_attribute_name="uniqueness_constraints", - relationship_allowed=True, + schema_path = self.validate_schema_path( + node_schema=node_schema, + path=constraint_path, + allowed_path_types=SchemaElementPathType.ATTR | SchemaElementPathType.REL_ONE_NO_ATTR, + element_name="uniqueness_constraints", ) + if schema_path.is_type_relationship and schema_path.relationship_schema: + if schema_path.relationship_schema.optional and not ( + schema_path.relationship_schema.name == "ip_namespace" + and isinstance(node_schema, NodeSchema) + and (node_schema.is_ip_address() or node_schema.is_ip_prefix) + ): + raise ValueError( + f"Only mandatory relation of cardinality one can be used in uniqueness_constraints," + f" {schema_path.relationship_schema.name} is not mandatory. ({constraint_path})" + ) def validate_display_labels(self) -> None: - full_schema_objects = self.to_dict_schema_object() - schema_map = full_schema_objects["nodes"] | full_schema_objects["generics"] for name in self.all_names: node_schema = self.get(name=name, duplicate=False) if node_schema.display_labels: - for display_label_path in node_schema.display_labels: - self._validate_attribute_path( - node_schema, display_label_path, schema_map, schema_attribute_name="display_labels" + for path in node_schema.display_labels: + self.validate_schema_path( + node_schema=node_schema, + path=path, + allowed_path_types=SchemaElementPathType.ATTR, + element_name="display_labels", ) elif isinstance(node_schema, NodeSchema): generic_display_labels = [] @@ -631,37 +666,88 @@ def validate_display_labels(self) -> None: node_schema.display_labels = generic_display_labels[0] def validate_order_by(self) -> None: - full_schema_objects = self.to_dict_schema_object() - schema_map = full_schema_objects["nodes"] | full_schema_objects["generics"] for name in self.all_names: node_schema = self.get(name=name, duplicate=False) if not node_schema.order_by: continue + allowed_types = SchemaElementPathType.ATTR | SchemaElementPathType.REL_ONE for order_by_path in node_schema.order_by: - self._validate_attribute_path( - node_schema, - order_by_path, - schema_map, - relationship_allowed=True, - relationship_attribute_allowed=True, - schema_attribute_name="order_by", + self.validate_schema_path( + node_schema=node_schema, + path=order_by_path, + allowed_path_types=allowed_types, + element_name="order_by", ) def validate_default_filters(self) -> None: - full_schema_objects = self.to_dict_schema_object() - schema_map = full_schema_objects["nodes"] | full_schema_objects["generics"] for name in self.all_names: node_schema = self.get(name=name, duplicate=False) if not node_schema.default_filter: continue - self._validate_attribute_path( - node_schema, node_schema.default_filter, schema_map, schema_attribute_name="default_filter" + self.validate_schema_path( + node_schema=node_schema, + path=node_schema.default_filter, + allowed_path_types=SchemaElementPathType.ATTR, + element_name="default_filter", ) + def validate_human_friendly_id(self): + for name in self.generic_names + self.node_names: + node_schema = self.get(name=name, duplicate=False) + + if not node_schema.human_friendly_id: + continue + + has_unique_item = False + allowed_types = SchemaElementPathType.ATTR | SchemaElementPathType.REL_ONE_ATTR + for item in node_schema.human_friendly_id: + schema_path = self.validate_schema_path( + node_schema=node_schema, + path=item, + allowed_path_types=allowed_types, + element_name="human_friendly_id", + ) + + if schema_path.attribute_schema.unique: + has_unique_item = True + + if schema_path.is_type_relationship and schema_path.relationship_schema: + if schema_path.relationship_schema.optional and not ( + schema_path.relationship_schema.name == "ip_namespace" + and isinstance(node_schema, NodeSchema) + and (node_schema.is_ip_address() or node_schema.is_ip_prefix) + ): + raise ValueError( + f"Only mandatory relationship of cardinality one can be used in human_friendly_id, " + f"{schema_path.relationship_schema.name} is not mandatory on {schema_path.relationship_schema.kind} for " + f"{node_schema.kind}. ({item})" + ) + # if not schema_path.attribute_schema.unique: + # raise ValueError( + # f"Only unique attribute on related node can be used used in human_friendly_id, " + # f"{schema_path.attribute_schema.name} is not unique on {schema_path.relationship_schema.kind} for " + # f"{node_schema.kind}. ({item})" + # ) + + # if ( + # schema_path.is_type_attribute + # and len(node_schema.human_friendly_id) == 1 + # and not schema_path.attribute_schema.unique + # ): + # raise ValueError( + # f"Only unique attribute can be used on their own in human_friendly_id, " + # f"{schema_path.attribute_schema.name} is not unique for {node_schema.kind}. ({item})" + # ) + + if not has_unique_item: + raise ValueError( + f"At least one attribute must be unique in the human_friendly_id for {node_schema.kind}." + ) + def validate_parent_component(self) -> None: # {parent_kind: {component_kind_1, component_kind_2, ...}} dependency_map: dict[str, set[str]] = defaultdict(set) @@ -891,6 +977,34 @@ def process_relationships(self) -> None: if schema_to_update: self.set(name=schema_to_update.kind, schema=schema_to_update) + def process_human_friendly_id(self) -> None: + for name in self.generic_names + self.node_names: + node = self.get(name=name, duplicate=False) + + # If human_friendly_id IS NOT defined + # but some the model has some unique attribute, we generate a human_friendly_id + # If human_friendly_id IS defined + # but no unique attributes and no uniquess constraints, we add a uniqueness_constraint + if not node.human_friendly_id and node.unique_attributes: + for attr in node.unique_attributes: + node = self.get(name=name, duplicate=True) + node.human_friendly_id = [f"{attr.name}__value"] + self.set(name=node.kind, schema=node) + break + continue + + if node.human_friendly_id and not node.unique_attributes and not node.uniqueness_constraints: + uniqueness_constraints: list[str] = [] + for item in node.human_friendly_id: + schema_attribute_path = node.parse_schema_path(path=item, schema=self) + if schema_attribute_path.is_type_attribute: + uniqueness_constraints.append(item) + elif schema_attribute_path.is_type_relationship: + uniqueness_constraints.append(schema_attribute_path.relationship_schema.name) + + node.uniqueness_constraints = [uniqueness_constraints] + self.set(name=node.kind, schema=node) + def process_hierarchy(self) -> None: for name in self.nodes.keys(): node = self.get(name=name, duplicate=False) @@ -1270,6 +1384,7 @@ def add_profile_schemas(self): self.set(name=core_profile_schema.kind, schema=core_profile_schema) else: core_profile_schema = self.get(name=InfrahubKind.PROFILE, duplicate=False) + profile_schema_kinds = set() for node_name in self.nodes.keys(): node = self.get_node(name=node_name, duplicate=False) @@ -1281,14 +1396,27 @@ def add_profile_schemas(self): profile_schema_kinds.add(profile.kind) if not profile_schema_kinds: return + + # Update used_by list for CoreProfile and CoreNode core_profile_schema = self.get(name=InfrahubKind.PROFILE, duplicate=False) - current_used_by = set(core_profile_schema.used_by) - new_used_by = profile_schema_kinds - current_used_by - if not new_used_by: - return - core_profile_schema = self.get(name=InfrahubKind.PROFILE, duplicate=True) - core_profile_schema.used_by = sorted(list(profile_schema_kinds)) - self.set(name=core_profile_schema.kind, schema=core_profile_schema) + current_used_by_profile = set(core_profile_schema.used_by) + new_used_by_profile = profile_schema_kinds - current_used_by_profile + + if new_used_by_profile: + core_profile_schema = self.get(name=InfrahubKind.PROFILE, duplicate=True) + core_profile_schema.used_by = sorted(list(profile_schema_kinds)) + self.set(name=InfrahubKind.PROFILE, schema=core_profile_schema) + + if self.has(name=InfrahubKind.NODE): + core_node_schema = self.get(name=InfrahubKind.NODE, duplicate=False) + current_used_by_node = set(core_node_schema.used_by) + new_used_by_node = profile_schema_kinds - current_used_by_node + + if new_used_by_node: + core_node_schema = self.get(name=InfrahubKind.NODE, duplicate=True) + updated_used_by_node = set(chain(profile_schema_kinds, set(core_node_schema.used_by))) + core_node_schema.used_by = sorted(list(updated_used_by_node)) + self.set(name=InfrahubKind.NODE, schema=core_node_schema) def add_profile_relationships(self): for node_name in self.nodes.keys(): @@ -1335,7 +1463,7 @@ def generate_profile_from_node(self, node: NodeSchema) -> ProfileSchema: branch=node.branch, include_in_menu=False, display_labels=["profile_name__value"], - inherit_from=[InfrahubKind.LINEAGESOURCE, InfrahubKind.PROFILE], + inherit_from=[InfrahubKind.LINEAGESOURCE, InfrahubKind.PROFILE, InfrahubKind.NODE], default_filter="profile_name__value", attributes=[profile_name_attr, profile_priority_attr], relationships=[ diff --git a/backend/infrahub/core/utils.py b/backend/infrahub/core/utils.py index 9ee5717814..cb2c990909 100644 --- a/backend/infrahub/core/utils.py +++ b/backend/infrahub/core/utils.py @@ -121,10 +121,13 @@ async def get_paths_between_nodes( return await db.execute_query(query=query, params=params, name="get_paths_between_nodes") -async def count_relationships(db: InfrahubDatabase) -> int: +async def count_relationships(db: InfrahubDatabase, label: Optional[str] = None) -> int: """Return the total number of relationships in the database.""" - query = """ - MATCH ()-[r]->() + + label_str = f":{label}" if label else "" + + query = f""" + MATCH ()-[r{label_str}]->() RETURN count(r) as count """ @@ -146,11 +149,13 @@ async def get_nodes(db: InfrahubDatabase, label: str) -> List[Neo4jNode]: return [result[0] for result in results] -async def count_nodes(db: InfrahubDatabase, label: str) -> int: +async def count_nodes(db: InfrahubDatabase, label: Optional[str] = None) -> int: """Return the total number of nodes of a given label in the database.""" - query = """ - MATCH (node) - WHERE $label IN LABELS(node) + + label_str = f":{label}" if label else "" + + query = f""" + MATCH (node{label_str}) RETURN count(node) as count """ params: dict = {"label": label} diff --git a/backend/infrahub/core/validators/relationship/peer.py b/backend/infrahub/core/validators/relationship/peer.py index 77f3dddc3e..028d57bd2d 100644 --- a/backend/infrahub/core/validators/relationship/peer.py +++ b/backend/infrahub/core/validators/relationship/peer.py @@ -2,7 +2,6 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional -from infrahub.core import registry from infrahub.core.constants import PathType from infrahub.core.path import DataPath, GroupedDataPaths from infrahub.core.schema import GenericSchema @@ -23,7 +22,7 @@ class RelationshipPeerUpdateValidatorQuery(RelationshipSchemaValidatorQuery): name = "relationship_constraints_peer_validator" async def query_init(self, db: InfrahubDatabase, *args: Any, **kwargs: Dict[str, Any]) -> None: - peer_schema = registry.schema.get(name=self.relationship_schema.peer, branch=self.branch) + peer_schema = db.schema.get(name=self.relationship_schema.peer, branch=self.branch) allowed_peer_kinds = [peer_schema.kind] if isinstance(peer_schema, GenericSchema): allowed_peer_kinds += peer_schema.used_by diff --git a/backend/infrahub/core/validators/uniqueness/checker.py b/backend/infrahub/core/validators/uniqueness/checker.py index 1436ac66e8..8bb058d81e 100644 --- a/backend/infrahub/core/validators/uniqueness/checker.py +++ b/backend/infrahub/core/validators/uniqueness/checker.py @@ -127,8 +127,11 @@ async def _parse_results(self, schema: MainSchemaTypes, query_results: list[Quer relationship_schema_by_identifier = {rel.identifier: rel for rel in schema.relationships} all_non_unique_nodes: list[NonUniqueNode] = [] results_index = UniquenessQueryResultsIndex(query_results=query_results) + + branch = await self.get_branch() + schema_branch = self.db.schema.get_schema_branch(name=branch.name) path_groups = schema.get_unique_constraint_schema_attribute_paths( - include_unique_attributes=True, branch=await self.get_branch() + include_unique_attributes=True, schema_branch=schema_branch ) for constraint_group in path_groups: non_unique_nodes_by_id: dict[str, NonUniqueNode] = {} diff --git a/backend/infrahub/database/__init__.py b/backend/infrahub/database/__init__.py index f5556dc721..8e4d3ab021 100644 --- a/backend/infrahub/database/__init__.py +++ b/backend/infrahub/database/__init__.py @@ -2,7 +2,7 @@ import asyncio import random -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union from neo4j import ( READ_ACCESS, @@ -13,12 +13,16 @@ AsyncSession, AsyncTransaction, Record, + TrustAll, + TrustCustomCAs, + TrustSystemCAs, ) from neo4j.exceptions import ClientError, Neo4jError, ServiceUnavailable, TransientError from opentelemetry import trace from typing_extensions import Self -from infrahub import config +from infrahub import config, lock +from infrahub.core import registry from infrahub.exceptions import DatabaseError from infrahub.log import get_logger from infrahub.utils import InfrahubStringEnum @@ -31,6 +35,10 @@ if TYPE_CHECKING: from types import TracebackType + from infrahub.core.branch import Branch + from infrahub.core.schema import MainSchemaTypes, NodeSchema + from infrahub.core.schema_manager import SchemaBranch + from .manager import DatabaseManager validated_database = {} @@ -49,6 +57,66 @@ class InfrahubDatabaseSessionMode(InfrahubStringEnum): WRITE = "write" +def get_branch_name(branch: Optional[Union[Branch, str]] = None) -> str: + if not branch: + return registry.default_branch + if isinstance(branch, str): + return branch + + return branch.name + + +class DatabaseSchemaManager: + def __init__(self, db: InfrahubDatabase): + self._db = db + + def get(self, name: str, branch: Optional[Union[Branch, str]] = None, duplicate: bool = True) -> MainSchemaTypes: + branch_name = get_branch_name(branch=branch) + if branch_name not in self._db._schemas: + return registry.schema.get(name=name, branch=branch, duplicate=duplicate) + return self._db._schemas[branch_name].get(name=name, duplicate=duplicate) + + def get_node_schema( + self, name: str, branch: Optional[Union[Branch, str]] = None, duplicate: bool = True + ) -> NodeSchema: + schema = self.get(name=name, branch=branch, duplicate=duplicate) + if schema.is_node_schema: + return schema + + raise ValueError("The selected node is not of type NodeSchema") + + def set(self, name: str, schema: MainSchemaTypes, branch: Optional[str] = None) -> int: + branch_name = get_branch_name(branch=branch) + if branch_name not in self._db._schemas: + return registry.schema.set(name=name, schema=schema, branch=branch) + return self._db._schemas[branch_name].set(name=name, schema=schema) + + def has(self, name: str, branch: Optional[Union[Branch, str]] = None) -> bool: + branch_name = get_branch_name(branch=branch) + if branch_name not in self._db._schemas: + return registry.schema.has(name=name, branch=branch) + return self._db._schemas[branch_name].has(name=name) + + def get_full( + self, branch: Optional[Union[Branch, str]] = None, duplicate: bool = True + ) -> Dict[str, MainSchemaTypes]: + branch_name = get_branch_name(branch=branch) + if branch_name not in self._db._schemas: + return registry.schema.get_full(branch=branch) + return self._db._schemas[branch_name].get_all(duplicate=duplicate) + + async def get_full_safe( + self, branch: Optional[Union[Branch, str]] = None, duplicate: bool = True + ) -> Dict[str, MainSchemaTypes]: + await lock.registry.local_schema_wait() + return self.get_full(branch=branch, duplicate=duplicate) + + def get_schema_branch(self, name: str) -> SchemaBranch: + if name not in self._db._schemas: + return registry.schema.get_schema_branch(name=name) + return self._db._schemas[name] + + class InfrahubDatabase: """Base class for database access""" @@ -58,16 +126,24 @@ def __init__( mode: InfrahubDatabaseMode = InfrahubDatabaseMode.DRIVER, db_type: Optional[DatabaseType] = None, db_manager: Optional[DatabaseManager] = None, + schemas: Optional[List[SchemaBranch]] = None, session: Optional[AsyncSession] = None, session_mode: InfrahubDatabaseSessionMode = InfrahubDatabaseSessionMode.WRITE, transaction: Optional[AsyncTransaction] = None, ): - self._mode = mode - self._driver = driver - self._session = session - self._session_mode = session_mode - self._is_session_local = False - self._transaction = transaction + self._mode: InfrahubDatabaseMode = mode + self._driver: AsyncDriver = driver + self._session: Optional[AsyncSession] = session + self._session_mode: InfrahubDatabaseSessionMode = session_mode + self._is_session_local: bool = False + self._transaction: Optional[AsyncTransaction] = transaction + + if schemas: + self._schemas: Dict[str, SchemaBranch] = {schema.name: schema for schema in schemas} + else: + self._schemas = {} + self.schema: DatabaseSchemaManager = DatabaseSchemaManager(db=self) + if db_type and isinstance(db_type, DatabaseType): self.db_type = db_type else: @@ -93,7 +169,10 @@ def is_transaction(self): return True return False - def start_session(self, read_only: bool = False) -> InfrahubDatabase: + def add_schema(self, schema: SchemaBranch, name: Optional[str] = None) -> None: + self._schemas[name or schema.name] = schema + + def start_session(self, read_only: bool = False, schemas: Optional[List[SchemaBranch]] = None) -> InfrahubDatabase: """Create a new InfrahubDatabase object in Session mode.""" session_mode = InfrahubDatabaseSessionMode.WRITE if read_only: @@ -102,15 +181,17 @@ def start_session(self, read_only: bool = False) -> InfrahubDatabase: return self.__class__( mode=InfrahubDatabaseMode.SESSION, db_type=self.db_type, + schemas=schemas or self._schemas.values(), db_manager=self.manager, driver=self._driver, session_mode=session_mode, ) - def start_transaction(self) -> InfrahubDatabase: + def start_transaction(self, schemas: Optional[List[SchemaBranch]] = None) -> InfrahubDatabase: return self.__class__( mode=InfrahubDatabaseMode.TRANSACTION, db_type=self.db_type, + schemas=schemas or self._schemas.values(), db_manager=self.manager, driver=self._driver, session=self._session, @@ -190,7 +271,7 @@ async def execute_query( with trace.get_tracer(__name__).start_as_current_span("execute_db_query") as span: span.set_attribute("query", query) - with QUERY_EXECUTION_METRICS.labels(str(self._session_mode), name).time(): + with QUERY_EXECUTION_METRICS.labels(self._session_mode.value, name).time(): response = await self.run_query(query=query, params=params) return [item async for item in response] @@ -200,7 +281,7 @@ async def execute_query_with_metadata( with trace.get_tracer(__name__).start_as_current_span("execute_db_query_with_metadata") as span: span.set_attribute("query", query) - with QUERY_EXECUTION_METRICS.labels(str(self._session_mode), name).time(): + with QUERY_EXECUTION_METRICS.labels(self._session_mode.value, name).time(): response = await self.run_query(query=query, params=params) results = [item async for item in response] return results, response._metadata or {} @@ -277,7 +358,19 @@ async def validate_database( async def get_db(retry: int = 0) -> AsyncDriver: URI = f"{config.SETTINGS.database.protocol}://{config.SETTINGS.database.address}:{config.SETTINGS.database.port}" - driver = AsyncGraphDatabase.driver(URI, auth=(config.SETTINGS.database.username, config.SETTINGS.database.password)) + + trusted_certificates = TrustSystemCAs() + if config.SETTINGS.database.tls_insecure: + trusted_certificates = TrustAll() + elif config.SETTINGS.database.tls_ca_file: + trusted_certificates = TrustCustomCAs(config.SETTINGS.database.tls_ca_file) + + driver = AsyncGraphDatabase.driver( + URI, + auth=(config.SETTINGS.database.username, config.SETTINGS.database.password), + encrypted=config.SETTINGS.database.tls_enabled, + trusted_certificates=trusted_certificates, + ) if config.SETTINGS.database.database_name not in validated_database: await validate_database( diff --git a/backend/infrahub/dependencies/builder/constraint/grouped/node_runner.py b/backend/infrahub/dependencies/builder/constraint/grouped/node_runner.py index 7bdc66e9bd..fddb032133 100644 --- a/backend/infrahub/dependencies/builder/constraint/grouped/node_runner.py +++ b/backend/infrahub/dependencies/builder/constraint/grouped/node_runner.py @@ -4,6 +4,7 @@ from ..node.grouped_uniqueness import NodeGroupedUniquenessConstraintDependency from ..node.uniqueness import NodeAttributeUniquenessConstraintDependency from ..relationship_manager.count import RelationshipCountConstraintDependency +from ..relationship_manager.peer_kind import RelationshipPeerKindConstraintDependency class NodeConstraintRunnerDependency(DependencyBuilder[NodeConstraintRunner]): @@ -16,5 +17,8 @@ def build(cls, context: DependencyBuilderContext) -> NodeConstraintRunner: NodeAttributeUniquenessConstraintDependency.build(context=context), NodeGroupedUniquenessConstraintDependency.build(context=context), ], - relationship_manager_constraints=[RelationshipCountConstraintDependency.build(context=context)], + relationship_manager_constraints=[ + RelationshipPeerKindConstraintDependency.build(context=context), + RelationshipCountConstraintDependency.build(context=context), + ], ) diff --git a/backend/infrahub/dependencies/builder/constraint/relationship_manager/peer_kind.py b/backend/infrahub/dependencies/builder/constraint/relationship_manager/peer_kind.py new file mode 100644 index 0000000000..21740d19e9 --- /dev/null +++ b/backend/infrahub/dependencies/builder/constraint/relationship_manager/peer_kind.py @@ -0,0 +1,8 @@ +from infrahub.core.relationship.constraints.peer_kind import RelationshipPeerKindConstraint +from infrahub.dependencies.interface import DependencyBuilder, DependencyBuilderContext + + +class RelationshipPeerKindConstraintDependency(DependencyBuilder[RelationshipPeerKindConstraint]): + @classmethod + def build(cls, context: DependencyBuilderContext) -> RelationshipPeerKindConstraint: + return RelationshipPeerKindConstraint(db=context.db, branch=context.branch) diff --git a/backend/infrahub/dependencies/registry.py b/backend/infrahub/dependencies/registry.py index c584aa2821..0f1f8799f6 100644 --- a/backend/infrahub/dependencies/registry.py +++ b/backend/infrahub/dependencies/registry.py @@ -2,6 +2,7 @@ from .builder.constraint.node.grouped_uniqueness import NodeGroupedUniquenessConstraintDependency from .builder.constraint.node.uniqueness import NodeAttributeUniquenessConstraintDependency from .builder.constraint.relationship_manager.count import RelationshipCountConstraintDependency +from .builder.constraint.relationship_manager.peer_kind import RelationshipPeerKindConstraintDependency from .builder.constraint.schema.aggregated import AggregatedSchemaConstraintsDependency from .builder.constraint.schema.attribute_regex import SchemaAttributeRegexConstraintDependency from .builder.constraint.schema.attribute_uniqueness import SchemaAttributeUniqueConstraintDependency @@ -21,6 +22,7 @@ def build_component_registry() -> ComponentDependencyRegistry: component_registry.track_dependency(NodeAttributeUniquenessConstraintDependency) component_registry.track_dependency(NodeGroupedUniquenessConstraintDependency) component_registry.track_dependency(RelationshipCountConstraintDependency) + component_registry.track_dependency(RelationshipPeerKindConstraintDependency) component_registry.track_dependency(NodeConstraintRunnerDependency) component_registry.track_dependency(NodeDeleteValidatorDependency) return component_registry diff --git a/backend/infrahub/exceptions.py b/backend/infrahub/exceptions.py index 635174dbe3..b32851f0d0 100644 --- a/backend/infrahub/exceptions.py +++ b/backend/infrahub/exceptions.py @@ -183,6 +183,7 @@ def __init__(self, message: Optional[str] = None): class ProcessingError(Error): + HTTP_CODE: int = 400 message: str = "Unable to process the request" def __init__(self, message: Optional[str] = None): @@ -190,6 +191,15 @@ def __init__(self, message: Optional[str] = None): super().__init__(self.message) +class PoolExhaustedError(Error): + HTTP_CODE: int = 409 + message: str = "No more resources available in the pool" + + def __init__(self, message: Optional[str] = None): + self.message = message or self.message + super().__init__(self.message) + + class SchemaNotFoundError(Error): HTTP_CODE: int = 422 diff --git a/backend/infrahub/graphql/app.py b/backend/infrahub/graphql/app.py index 02cfd0a344..b9579ae204 100644 --- a/backend/infrahub/graphql/app.py +++ b/backend/infrahub/graphql/app.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio +import time from inspect import isawaitable from typing import ( TYPE_CHECKING, @@ -184,6 +185,10 @@ async def _get_on_get(self, request: Request) -> Optional[Response]: async def _handle_http_request( self, request: Request, db: InfrahubDatabase, branch: Branch, account_session: AccountSession ) -> JSONResponse: + if request.app.state.response_delay: + self.logger.info(f"Adding response delay of {request.app.state.response_delay} seconds") + time.sleep(request.app.state.response_delay) + try: operations = await _get_operation_from_request(request) except ValueError as exc: @@ -208,6 +213,9 @@ async def _handle_http_request( # if the query contains some mutation, it's not currently supported to set AT manually if analyzed_query.contains_mutation: graphql_params.context.at = Timestamp() + elif at and branch.schema_changed_at and Timestamp(branch.schema_changed_at) > Timestamp(at): + schema_branch = await registry.schema.load_schema_from_db(db=db, branch=branch, at=Timestamp(at)) + db.add_schema(name=branch.name, schema=schema_branch) if operation_name == "IntrospectionQuery": nbr_object_in_schema = len(graphql_params.schema.type_map) diff --git a/backend/infrahub/graphql/manager.py b/backend/infrahub/graphql/manager.py index 5c1c786126..2c458b64dc 100644 --- a/backend/infrahub/graphql/manager.py +++ b/backend/infrahub/graphql/manager.py @@ -8,7 +8,14 @@ from infrahub import config from infrahub.core.attribute import String from infrahub.core.constants import InfrahubKind, RelationshipKind -from infrahub.core.schema import AttributeSchema, GenericSchema, MainSchemaTypes, NodeSchema, ProfileSchema +from infrahub.core.schema import ( + AttributeSchema, + GenericSchema, + MainSchemaTypes, + NodeSchema, + ProfileSchema, + RelationshipSchema, +) from infrahub.graphql.mutations.attribute import BaseAttributeCreate, BaseAttributeUpdate from infrahub.graphql.mutations.graphql_query import InfrahubGraphQLQueryMutation from infrahub.types import ATTRIBUTE_TYPES, InfrahubDataType, get_attribute_type @@ -39,7 +46,13 @@ ) from .schema import InfrahubBaseMutation, InfrahubBaseQuery, account_resolver, default_paginated_list_resolver from .subscription import InfrahubBaseSubscription -from .types import InfrahubInterface, InfrahubObject, RelatedNodeInput +from .types import ( + InfrahubInterface, + InfrahubObject, + RelatedIPAddressNodeInput, + RelatedNodeInput, + RelatedPrefixNodeInput, +) from .types.attribute import BaseAttribute as BaseAttributeType from .types.attribute import TextAttributeType @@ -50,7 +63,8 @@ class DeleteInput(graphene.InputObjectType): - id = graphene.String(required=True) + id = graphene.String(required=False) + hfid = graphene.List(of_type=graphene.String, required=False) GraphQLTypes = Union[ @@ -217,6 +231,20 @@ def _load_enum_type(self, node_schema: MainSchemaTypes) -> None: ) ATTRIBUTE_TYPES[base_enum_name] = data_type_class + def _get_related_input_type(self, relationship: RelationshipSchema) -> type[RelatedNodeInput]: + peer_schema = self.schema.get(name=relationship.peer, duplicate=False) + if (isinstance(peer_schema, NodeSchema) and peer_schema.is_ip_prefix()) or ( + isinstance(peer_schema, GenericSchema) and InfrahubKind.IPPREFIX == relationship.peer + ): + return RelatedPrefixNodeInput + + if (isinstance(peer_schema, NodeSchema) and peer_schema.is_ip_address()) or ( + isinstance(peer_schema, GenericSchema) and InfrahubKind.IPADDRESS == relationship.peer + ): + return RelatedIPAddressNodeInput + + return RelatedNodeInput + def generate_object_types(self) -> None: # pylint: disable=too-many-branches,too-many-statements """Generate all GraphQL objects for the schema and store them in the internal registry.""" @@ -429,7 +457,10 @@ def generate_graphql_object( } main_attrs = { - "id": graphene.String(required=True), + "id": graphene.Field(graphene.String, required=True, description="Unique identifier"), + "hfid": graphene.Field( + graphene.List(of_type=graphene.String), required=False, description="Human friendly identifier" + ), "_updated_at": graphene.DateTime(required=False), "display_label": graphene.String(required=False), "Meta": type("Meta", (object,), meta_attrs), @@ -456,6 +487,10 @@ def generate_interface_object( } main_attrs = { + "id": graphene.Field(graphene.String, required=False, description="Unique identifier"), + "hfid": graphene.Field( + graphene.List(of_type=graphene.String), required=False, description="Human friendly identifier" + ), "display_label": graphene.String(required=False), "Meta": type("Meta", (object,), meta_attrs), } @@ -465,8 +500,6 @@ def generate_interface_object( attr_type = self.get_type(name=get_attribute_type(kind=attr_kind).get_graphql_type_name()) main_attrs[attr.name] = graphene.Field(attr_type, required=not attr.optional, description=attr.description) - main_attrs["id"] = graphene.Field(graphene.String, required=False, description="Unique identifier") - interface_object = type(schema.kind, (InfrahubInterface,), main_attrs) if populate_cache: @@ -523,8 +556,8 @@ def generate_graphql_mutations( return GraphqlMutations(create=create, update=update, upsert=upsert, delete=delete) - @staticmethod def generate_graphql_mutation_create_input( + self, schema: Union[NodeSchema, ProfileSchema], ) -> Type[graphene.InputObjectType]: """Generate an InputObjectType Object from a Infrahub NodeSchema @@ -553,31 +586,38 @@ class StatusCreateInput(InputObjectType): for rel in schema.relationships: if rel.internal_peer or rel.read_only: continue + + input_type = self._get_related_input_type(relationship=rel) + required = not rel.optional if rel.cardinality == "one": - attrs[rel.name] = graphene.InputField(RelatedNodeInput, required=required, description=rel.description) + attrs[rel.name] = graphene.InputField(input_type, required=required, description=rel.description) elif rel.cardinality == "many": attrs[rel.name] = graphene.InputField( - graphene.List(RelatedNodeInput), required=required, description=rel.description + graphene.List(input_type), required=required, description=rel.description ) return type(f"{schema.kind}CreateInput", (graphene.InputObjectType,), attrs) - @staticmethod def generate_graphql_mutation_update_input( + self, schema: Union[NodeSchema, ProfileSchema], ) -> Type[graphene.InputObjectType]: """Generate an InputObjectType Object from a Infrahub NodeSchema Example of Object Generated by this function: class StatusUpdateInput(InputObjectType): - id = String(required=True) + id = String(required=False) + hfid = InputField(List(of_type=String), required=False) label = InputField(StringAttributeUpdate, required=False) slug = InputField(StringAttributeUpdate, required=False) description = InputField(StringAttributeUpdate, required=False) """ - attrs: Dict[str, Union[graphene.String, graphene.InputField]] = {"id": graphene.String(required=True)} + attrs: Dict[str, Union[graphene.String, graphene.InputField]] = { + "id": graphene.String(required=False), + "hfid": graphene.List(of_type=graphene.String, required=False), + } for attr in schema.attributes: if attr.read_only: @@ -589,18 +629,21 @@ class StatusUpdateInput(InputObjectType): for rel in schema.relationships: if rel.internal_peer or rel.read_only: continue + + input_type = self._get_related_input_type(relationship=rel) + if rel.cardinality == "one": - attrs[rel.name] = graphene.InputField(RelatedNodeInput, required=False, description=rel.description) + attrs[rel.name] = graphene.InputField(input_type, required=False, description=rel.description) elif rel.cardinality == "many": attrs[rel.name] = graphene.InputField( - graphene.List(RelatedNodeInput), required=False, description=rel.description + graphene.List(input_type), required=False, description=rel.description ) return type(f"{schema.kind}UpdateInput", (graphene.InputObjectType,), attrs) - @staticmethod def generate_graphql_mutation_upsert_input( + self, schema: Union[NodeSchema, ProfileSchema], ) -> Type[graphene.InputObjectType]: """Generate an InputObjectType Object from a Infrahub NodeSchema @@ -608,11 +651,15 @@ def generate_graphql_mutation_upsert_input( Example of Object Generated by this function: class StatusUpsertInput(InputObjectType): id = String(required=False) + hfid = InputField(List(of_type=String), required=False) label = InputField(StringAttributeUpdate, required=True) slug = InputField(StringAttributeUpdate, required=True) description = InputField(StringAttributeUpdate, required=False) """ - attrs: Dict[str, Union[graphene.String, graphene.InputField]] = {"id": graphene.String(required=False)} + attrs: Dict[str, Union[graphene.String, graphene.InputField]] = { + "id": graphene.String(required=False), + "hfid": graphene.List(of_type=graphene.String, required=False), + } for attr in schema.attributes: if attr.read_only: @@ -629,13 +676,16 @@ class StatusUpsertInput(InputObjectType): for rel in schema.relationships: if rel.internal_peer or rel.read_only: continue + + input_type = self._get_related_input_type(relationship=rel) + required = not rel.optional if rel.cardinality == "one": - attrs[rel.name] = graphene.InputField(RelatedNodeInput, required=required, description=rel.description) + attrs[rel.name] = graphene.InputField(input_type, required=required, description=rel.description) elif rel.cardinality == "many": attrs[rel.name] = graphene.InputField( - graphene.List(RelatedNodeInput), required=required, description=rel.description + graphene.List(input_type), required=required, description=rel.description ) return type(f"{schema.kind}UpsertInput", (graphene.InputObjectType,), attrs) diff --git a/backend/infrahub/graphql/mutations/__init__.py b/backend/infrahub/graphql/mutations/__init__.py index f888d53411..67178e7584 100644 --- a/backend/infrahub/graphql/mutations/__init__.py +++ b/backend/infrahub/graphql/mutations/__init__.py @@ -1,4 +1,4 @@ -from .account import CoreAccountSelfUpdate, CoreAccountTokenCreate +from .account import CoreAccountSelfUpdate, CoreAccountTokenCreate, CoreAccountTokenDelete from .artifact_definition import InfrahubArtifactDefinitionMutation from .attribute import ( AnyAttributeCreate, @@ -36,6 +36,7 @@ ) from .relationship import RelationshipAdd, RelationshipRemove from .repository import InfrahubRepositoryMutation +from .resource_manager import IPAddressPoolGetResource, IPPrefixPoolGetResource from .schema import SchemaDropdownAdd, SchemaDropdownRemove, SchemaEnumAdd, SchemaEnumRemove from .task import TaskCreate, TaskUpdate @@ -56,6 +57,9 @@ "CheckboxAttributeUpdate", "CoreAccountSelfUpdate", "CoreAccountTokenCreate", + "CoreAccountTokenDelete", + "IPPrefixPoolGetResource", + "IPAddressPoolGetResource", "InfrahubArtifactDefinitionMutation", "InfrahubIPAddressMutation", "InfrahubIPNamespaceMutation", diff --git a/backend/infrahub/graphql/mutations/account.py b/backend/infrahub/graphql/mutations/account.py index bb78c7d99c..dbb8ce2e4a 100644 --- a/backend/infrahub/graphql/mutations/account.py +++ b/backend/infrahub/graphql/mutations/account.py @@ -28,6 +28,10 @@ class CoreAccountTokenCreateInput(InputObjectType): expiration = InputField(String(required=False), description="Timestamp when the token expires") +class CoreAccountTokenDeleteInput(InputObjectType): + id = InputField(String(required=True), description="The id of the token to delete") + + class CoreAccountUpdateSelfInput(InputObjectType): password = InputField(String(required=False), description="The new password") description = InputField(String(required=False), description="The new description") @@ -38,6 +42,7 @@ class ValueType(InfrahubObjectType): class CoreAccountTokenType(InfrahubObjectType): + id = String(required=True) token = Field(ValueType) @@ -65,7 +70,11 @@ async def mutate( account = results[0] - mutation_map = {"CoreAccountTokenCreate": cls.create_token, "CoreAccountSelfUpdate": cls.update_self} + mutation_map = { + "CoreAccountTokenCreate": cls.create_token, + "CoreAccountTokenDelete": cls.delete_token, + "CoreAccountSelfUpdate": cls.update_self, + } response = await mutation_map[cls.__name__](db=context.db, account=account, data=data, info=info) # Reset the time of the query to guarantee that all resolvers executed after this point will account for the changes @@ -94,6 +103,25 @@ async def create_token( fields = await extract_fields(info.field_nodes[0].selection_set) return cls(object=await obj.to_graphql(db=db, fields=fields.get("object", {})), ok=True) # type: ignore[call-arg] + @classmethod + @retry_db_transaction(name="account_token_delete") + async def delete_token( + cls, db: InfrahubDatabase, account: Node, data: Dict[str, Any], info: GraphQLResolveInfo + ) -> Self: + token_id = str(data.get("id")) + + results = await NodeManager.query( + schema=InfrahubKind.ACCOUNTTOKEN, filters={"account_ids": [account.id], "ids": [token_id]}, db=db + ) + + if not results: + raise NodeNotFoundError(node_type="AccountToken", identifier=token_id) + + async with db.start_transaction() as dbt: + await results[0].delete(db=dbt) + + return cls(ok=True) # type: ignore[call-arg] + @classmethod @retry_db_transaction(name="account_update_self") async def update_self( @@ -117,6 +145,13 @@ class Arguments: object = Field(CoreAccountTokenType) +class CoreAccountTokenDelete(AccountMixin, Mutation): + class Arguments: + data = CoreAccountTokenDeleteInput(required=True) + + ok = Boolean() + + class CoreAccountSelfUpdate(AccountMixin, Mutation): class Arguments: data = CoreAccountUpdateSelfInput(required=True) diff --git a/backend/infrahub/graphql/mutations/branch.py b/backend/infrahub/graphql/mutations/branch.py index 43142f86c2..b5611ec53c 100644 --- a/backend/infrahub/graphql/mutations/branch.py +++ b/backend/infrahub/graphql/mutations/branch.py @@ -1,9 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Any, Optional import pydantic -from graphene import Boolean, Field, InputObjectType, List, Mutation, String +from graphene import Boolean, Field, InputField, InputObjectType, List, Mutation, String from infrahub_sdk.utils import extract_fields, extract_fields_first_node from opentelemetry import trace from typing_extensions import Self @@ -44,7 +44,7 @@ class BranchCreateInput(InputObjectType): origin_branch = String(required=False) branched_from = String(required=False) sync_with_git = Boolean(required=False) - is_isolated = Boolean(required=False) + is_isolated = InputField(Boolean(required=False), deprecation_reason="Non isolated mode is not supported anymore") class BranchCreate(Mutation): @@ -71,8 +71,12 @@ async def mutate( except BranchNotFoundError: pass + data_dict: dict[str, Any] = dict(data) + if "is_isolated" in data_dict: + del data_dict["is_isolated"] + try: - obj = Branch(**data) + obj = Branch(**data_dict) except pydantic.ValidationError as exc: error_msgs = [f"invalid field {error['loc'][0]}: {error['msg']}" for error in exc.errors()] raise ValueError("\n".join(error_msgs)) from exc @@ -115,7 +119,7 @@ class BranchNameInput(InputObjectType): class BranchUpdateInput(InputObjectType): name = String(required=True) description = String(required=False) - is_isolated = Boolean(required=False) + is_isolated = InputField(Boolean(required=False), deprecation_reason="Non isolated mode is not supported anymore") class BranchDelete(Mutation): @@ -160,17 +164,7 @@ async def mutate(cls, root: dict, info: GraphQLResolveInfo, data: BranchNameInpu obj = await Branch.get_by_name(db=context.db, name=data["name"]) - if ( - obj.is_isolated is True - and "is_isolated" in data - and data["is_isolated"] is False - and obj.has_schema_changes - ): - raise ValueError( - f"Unsupported: Can't convert {obj.name} to non-isolated mode because it currently has some schema changes." - ) - - to_extract = ["description", "is_isolated"] + to_extract = ["description"] for field_name in to_extract: if field_name in data and data.get(field_name) is not None: setattr(obj, field_name, data[field_name]) diff --git a/backend/infrahub/graphql/mutations/ipam.py b/backend/infrahub/graphql/mutations/ipam.py index 91b8e8db19..552630c666 100644 --- a/backend/infrahub/graphql/mutations/ipam.py +++ b/backend/infrahub/graphql/mutations/ipam.py @@ -136,7 +136,7 @@ async def mutate_update( address = node or await NodeManager.get_one_by_id_or_default_filter( db=db, - schema_name=cls._meta.schema.kind, + kind=cls._meta.schema.kind, id=data.get("id"), branch=branch, at=at, @@ -253,7 +253,7 @@ async def mutate_update( prefix = node or await NodeManager.get_one_by_id_or_default_filter( db=db, - schema_name=cls._meta.schema.kind, + kind=cls._meta.schema.kind, id=data.get("id"), branch=branch, at=at, diff --git a/backend/infrahub/graphql/mutations/main.py b/backend/infrahub/graphql/mutations/main.py index 0d5aac3199..fcda71cc4a 100644 --- a/backend/infrahub/graphql/mutations/main.py +++ b/backend/infrahub/graphql/mutations/main.py @@ -23,13 +23,14 @@ from infrahub.core.timestamp import Timestamp from infrahub.database import retry_db_transaction from infrahub.dependencies.registry import get_component_registry -from infrahub.exceptions import NodeNotFoundError, ValidationError +from infrahub.exceptions import ValidationError from infrahub.log import get_log_data, get_logger from infrahub.message_bus import Meta, messages from infrahub.services import services from infrahub.worker import WORKER_IDENTITY from .node_getter.by_default_filter import MutationNodeGetterByDefaultFilter +from .node_getter.by_hfid import MutationNodeGetterByHfid from .node_getter.by_id import MutationNodeGetterById if TYPE_CHECKING: @@ -76,8 +77,9 @@ async def mutate(cls, root: dict, info: GraphQLResolveInfo, *args, **kwargs): elif "Upsert" in cls.__name__: node_manager = NodeManager() node_getters = [ - MutationNodeGetterById(context.db, node_manager), - MutationNodeGetterByDefaultFilter(context.db, node_manager), + MutationNodeGetterById(db=context.db, node_manager=node_manager), + MutationNodeGetterByHfid(db=context.db, node_manager=node_manager), + MutationNodeGetterByDefaultFilter(db=context.db, node_manager=node_manager), ] obj, mutation, created = await cls.mutate_upsert( root=root, info=info, branch=context.branch, at=context.at, node_getters=node_getters, *args, **kwargs @@ -134,7 +136,7 @@ async def _refresh_for_profile_update( if previous_profile_ids is None or previous_profile_ids != current_profile_ids: return await NodeManager.get_one_by_id_or_default_filter( db=db, - schema_name=cls._meta.schema.kind, + kind=cls._meta.schema.kind, id=obj.get_id(), branch=branch, include_owner=True, @@ -178,7 +180,6 @@ async def mutate_create_object( await obj.new(db=db, **data) fields_to_validate = list(data) await node_constraint_runner.check(node=obj, field_filters=fields_to_validate) - if db.is_transaction: await obj.save(db=db) else: @@ -216,15 +217,10 @@ async def mutate_update( context: GraphqlContext = info.context db = database or context.db - obj = node or await NodeManager.get_one_by_id_or_default_filter( - db=db, - schema_name=cls._meta.schema.kind, - id=data.get("id"), - branch=branch, - at=at, - include_owner=True, - include_source=True, + obj = node or await NodeManager.find_object( + db=db, kind=cls._meta.schema.kind, id=data.get("id"), hfid=data.get("hfid"), branch=branch, at=at ) + try: if db.is_transaction: obj = await cls.mutate_update_object(db=db, info=info, data=data, branch=branch, obj=obj) @@ -259,6 +255,8 @@ async def mutate_update_object( fields = list(data.keys()) if "id" in fields: fields.remove("id") + if "hfid" in fields: + fields.remove("hfid") validate_mutation_permissions_update_node( operation=cls.__name__, node_id=node_id, account_session=context.account_session, fields=fields ) @@ -296,7 +294,11 @@ async def mutate_upsert( database: Optional[InfrahubDatabase] = None, ) -> Tuple[Node, Self, bool]: schema_name = cls._meta.schema.kind - node_schema = registry.schema.get(name=schema_name, branch=branch) + + context: GraphqlContext = info.context + db = database or context.db + + node_schema = db.schema.get(name=schema_name, branch=branch) node = None for getter in node_getters: @@ -306,10 +308,14 @@ async def mutate_upsert( if node: updated_obj, mutation = await cls.mutate_update( - root=root, info=info, data=data, branch=branch, at=at, database=database, node=node + root=root, info=info, data=data, branch=branch, at=at, database=db, node=node ) return updated_obj, mutation, False - created_obj, mutation = await cls.mutate_create(root=root, info=info, data=data, branch=branch, at=at) + # We need to convert the InputObjectType into a dict in order to remove hfid that isn't a valid input when creating the object + data_dict = dict(data) + if "hfid" in data: + del data_dict["hfid"] + created_obj, mutation = await cls.mutate_create(root=root, info=info, data=data_dict, branch=branch, at=at) return created_obj, mutation, True @classmethod @@ -324,8 +330,9 @@ async def mutate_delete( ): context: GraphqlContext = info.context - if not (obj := await NodeManager.get_one(db=context.db, id=data.get("id"), branch=branch, at=at)): - raise NodeNotFoundError(branch, cls._meta.schema.kind, data.get("id")) + obj = await NodeManager.find_object( + db=context.db, kind=cls._meta.schema.kind, id=data.get("id"), hfid=data.get("hfid"), branch=branch, at=at + ) try: async with context.db.start_transaction() as db: diff --git a/backend/infrahub/graphql/mutations/node_getter/by_default_filter.py b/backend/infrahub/graphql/mutations/node_getter/by_default_filter.py index cb46037884..fc4c675418 100644 --- a/backend/infrahub/graphql/mutations/node_getter/by_default_filter.py +++ b/backend/infrahub/graphql/mutations/node_getter/by_default_filter.py @@ -41,7 +41,7 @@ async def get_node( return await self.node_manager.get_one_by_default_filter( db=self.db, id=default_filter_value, - schema_name=node_schema.kind, + kind=node_schema.kind, branch=branch, at=at, ) diff --git a/backend/infrahub/graphql/mutations/node_getter/by_hfid.py b/backend/infrahub/graphql/mutations/node_getter/by_hfid.py new file mode 100644 index 0000000000..2819be07ee --- /dev/null +++ b/backend/infrahub/graphql/mutations/node_getter/by_hfid.py @@ -0,0 +1,36 @@ +from typing import Optional + +from graphene import InputObjectType + +from infrahub.core.branch import Branch +from infrahub.core.manager import NodeManager +from infrahub.core.node import Node +from infrahub.core.schema import MainSchemaTypes +from infrahub.database import InfrahubDatabase + +from .interface import MutationNodeGetterInterface + + +class MutationNodeGetterByHfid(MutationNodeGetterInterface): + def __init__(self, db: InfrahubDatabase, node_manager: NodeManager): + self.db = db + self.node_manager = node_manager + + async def get_node( + self, + node_schema: MainSchemaTypes, + data: InputObjectType, + branch: Branch, + at: str, + ) -> Optional[Node]: + node = None + if not node_schema.human_friendly_id or "hfid" not in data: + return node + + return await self.node_manager.get_one_by_hfid( + db=self.db, + hfid=data["hfid"], + kind=node_schema.kind, + branch=branch, + at=at, + ) diff --git a/backend/infrahub/graphql/mutations/proposed_change.py b/backend/infrahub/graphql/mutations/proposed_change.py index f0aa710257..8842dfabac 100644 --- a/backend/infrahub/graphql/mutations/proposed_change.py +++ b/backend/infrahub/graphql/mutations/proposed_change.py @@ -95,7 +95,7 @@ async def mutate_update( obj = await NodeManager.get_one_by_id_or_default_filter( db=context.db, - schema_name=cls._meta.schema.kind, + kind=cls._meta.schema.kind, id=data.get("id"), branch=branch, at=at, @@ -201,7 +201,7 @@ async def mutate( identifier = data.get("id", "") proposed_change = await NodeManager.get_one_by_id_or_default_filter( - id=identifier, schema_name=InfrahubKind.PROPOSEDCHANGE, db=context.db + id=identifier, kind=InfrahubKind.PROPOSEDCHANGE, db=context.db ) state = ProposedChangeState(proposed_change.state.value.value) state.validate_state_check_run() diff --git a/backend/infrahub/graphql/mutations/repository.py b/backend/infrahub/graphql/mutations/repository.py index fb5e832923..f001e72cfd 100644 --- a/backend/infrahub/graphql/mutations/repository.py +++ b/backend/infrahub/graphql/mutations/repository.py @@ -94,7 +94,7 @@ async def mutate_update( if not node: node = await NodeManager.get_one_by_id_or_default_filter( db=context.db, - schema_name=cls._meta.schema.kind, + kind=cls._meta.schema.kind, id=data.get("id"), branch=branch, at=at, diff --git a/backend/infrahub/graphql/mutations/resource_manager.py b/backend/infrahub/graphql/mutations/resource_manager.py new file mode 100644 index 0000000000..eb2065ba35 --- /dev/null +++ b/backend/infrahub/graphql/mutations/resource_manager.py @@ -0,0 +1,135 @@ +from typing import TYPE_CHECKING, Any, Dict + +from graphene import Boolean, Field, InputField, InputObjectType, Int, Mutation, String +from graphene.types.generic import GenericScalar +from graphql import GraphQLResolveInfo +from typing_extensions import Self + +from infrahub.core import registry +from infrahub.core.constants import InfrahubKind + +from ..queries.resource_manager import PoolAllocatedNode + +if TYPE_CHECKING: + from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool + from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool + + from .. import GraphqlContext + + +class IPPrefixPoolGetResourceInput(InputObjectType): + id = InputField(String(required=False), description="ID of the pool to allocate from") + hfid = InputField(String(required=False), description="HFID of the pool to allocate from") + identifier = InputField(String(required=False), description="Identifier for the allocated resource") + size = InputField(Int(required=False), description="Size of the prefix to allocate") + member_type = InputField(String(required=False), description="member_type of the newly created prefix") + prefix_type = InputField(String(required=False), description="kind of prefix to allocate") + data = InputField(GenericScalar(required=False), description="Additional data to pass to the newly created prefix") + + +class IPAddressPoolGetResourceInput(InputObjectType): + id = InputField(String(required=False), description="ID of the pool to allocate from") + hfid = InputField(String(required=False), description="HFID of the pool to allocate from") + identifier = InputField(String(required=False), description="Identifier for the allocated resource") + prefixlen = InputField( + String(required=False), description="size of the prefix mask to allocate on the new ip address" + ) + address_type = InputField(String(required=False), description="kind of ip address to allocate") + data = InputField( + GenericScalar(required=False), description="Additional data to pass to the newly created ip address" + ) + + +class IPPrefixPoolGetResource(Mutation): + class Arguments: + data = IPPrefixPoolGetResourceInput(required=True) + + ok = Boolean() + node = Field(PoolAllocatedNode) + + @classmethod + async def mutate( + cls, + root: dict, # pylint: disable=unused-argument + info: GraphQLResolveInfo, + data: InputObjectType, + ) -> Self: + context: GraphqlContext = info.context + + obj: CoreIPPrefixPool = await registry.manager.find_object( # type: ignore[assignment] + db=context.db, + kind=InfrahubKind.IPPREFIXPOOL, + id=data.get("id"), + hfid=data.get("hfid"), + branch=context.branch, + at=context.at, + ) + resource = await obj.get_resource( + db=context.db, + branch=context.branch, + identifier=data.get("identifier", None), + prefixlen=data.get("prefixlen", None), + member_type=data.get("member_type", None), + prefix_type=data.get("prefix_type", None), + data=data.get("data", None), + ) + + result = { + "ok": True, + "node": { + "id": resource.id, + "kind": resource.get_kind(), + "identifier": data.get("identifier", None), + "display_label": await resource.render_display_label(db=context.db), + "branch": context.branch.name, + }, + } + + return cls(**result) + + +class IPAddressPoolGetResource(Mutation): + class Arguments: + data = IPAddressPoolGetResourceInput(required=True) + + ok = Boolean() + node = Field(PoolAllocatedNode) + + @classmethod + async def mutate( + cls, + root: dict, # pylint: disable=unused-argument + info: GraphQLResolveInfo, + data: Dict[str, Any], + ) -> Self: + context: GraphqlContext = info.context + + obj: CoreIPAddressPool = await registry.manager.find_object( # type: ignore[assignment] + db=context.db, + kind=InfrahubKind.IPADDRESSPOOL, + id=data.get("id"), + hfid=data.get("hfid"), + branch=context.branch, + at=context.at, + ) + resource = await obj.get_resource( + db=context.db, + branch=context.branch, + identifier=data.get("identifier", None), + prefixlen=data.get("prefixlen", None), + address_type=data.get("address_type", None), + data=data.get("data", None), + ) + + result = { + "ok": True, + "node": { + "id": resource.id, + "kind": resource.get_kind(), + "identifier": data.get("identifier", None), + "display_label": await resource.render_display_label(db=context.db), + "branch": context.branch.name, + }, + } + + return cls(**result) diff --git a/backend/infrahub/graphql/mutations/schema.py b/backend/infrahub/graphql/mutations/schema.py index 5f2c2a5a97..ba00fc1a58 100644 --- a/backend/infrahub/graphql/mutations/schema.py +++ b/backend/infrahub/graphql/mutations/schema.py @@ -59,7 +59,7 @@ async def mutate( ): context: GraphqlContext = info.context - kind = registry.schema.get(name=str(data.kind), branch=context.branch.name) + kind = context.db.schema.get(name=str(data.kind), branch=context.branch.name) attribute = str(data.attribute) validate_kind_dropdown(kind=kind, attribute=attribute) dropdown = str(data.dropdown) @@ -75,7 +75,7 @@ async def mutate( await update_registry(kind=kind, branch=context.branch, db=context.db) - kind = registry.schema.get(name=str(data.kind), branch=context.branch.name) + kind = context.db.schema.get(name=str(data.kind), branch=context.branch.name) attrib = kind.get_attribute(attribute) dropdown_entry = {} success = False @@ -109,7 +109,7 @@ async def mutate( ) -> Dict[str, bool]: context: GraphqlContext = info.context - kind = registry.schema.get(name=str(data.kind), branch=context.branch.name) + kind = context.db.schema.get(name=str(data.kind), branch=context.branch.name) attribute = str(data.attribute) validate_kind_dropdown(kind=kind, attribute=attribute) @@ -151,7 +151,7 @@ async def mutate( ) -> Dict[str, bool]: context: GraphqlContext = info.context - kind = registry.schema.get(name=str(data.kind), branch=context.branch.name) + kind = context.db.schema.get(name=str(data.kind), branch=context.branch.name) attribute = str(data.attribute) enum = str(data.enum) @@ -187,7 +187,7 @@ async def mutate( context: GraphqlContext = info.context db = context.db branch = context.branch - kind = registry.schema.get(name=str(data.kind), branch=branch.name) + kind = db.schema.get(name=str(data.kind), branch=branch.name) attribute = str(data.attribute) enum = str(data.enum) diff --git a/backend/infrahub/graphql/queries/__init__.py b/backend/infrahub/graphql/queries/__init__.py index da0851182b..ae22c77d5f 100644 --- a/backend/infrahub/graphql/queries/__init__.py +++ b/backend/infrahub/graphql/queries/__init__.py @@ -1,9 +1,25 @@ +from .account import AccountToken from .branch import BranchQueryList from .diff.diff import DiffSummary from .diff.old import DiffSummaryOld from .internal import InfrahubInfo +from .ipam import InfrahubIPAddressGetNextAvailable, InfrahubIPPrefixGetNextAvailable from .relationship import Relationship +from .resource_manager import InfrahubResourcePoolAllocated, InfrahubResourcePoolUtilization from .status import InfrahubStatus from .task import Task -__all__ = ["BranchQueryList", "DiffSummary", "DiffSummaryOld", "InfrahubInfo", "InfrahubStatus", "Relationship", "Task"] +__all__ = [ + "AccountToken", + "BranchQueryList", + "DiffSummary", + "DiffSummaryOld", + "InfrahubInfo", + "InfrahubStatus", + "InfrahubIPAddressGetNextAvailable", + "InfrahubIPPrefixGetNextAvailable", + "InfrahubResourcePoolAllocated", + "InfrahubResourcePoolUtilization", + "Relationship", + "Task", +] diff --git a/backend/infrahub/graphql/queries/account.py b/backend/infrahub/graphql/queries/account.py new file mode 100644 index 0000000000..26a977a3e1 --- /dev/null +++ b/backend/infrahub/graphql/queries/account.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from graphene import Field, Int, List, ObjectType, String +from infrahub_sdk.utils import extract_fields_first_node + +from infrahub.core.constants import InfrahubKind +from infrahub.core.manager import NodeManager +from infrahub.core.registry import registry +from infrahub.exceptions import PermissionDeniedError + +if TYPE_CHECKING: + from graphql import GraphQLResolveInfo + + from infrahub.graphql import GraphqlContext + + +class AccountTokenNode(ObjectType): + id = Field(String, required=True) + name = Field(String, required=False) + expiration = Field(String, required=False) + + +class AccountTokenEdge(ObjectType): + node = Field(AccountTokenNode, required=True) + + +class AccountTokenEdges(ObjectType): + count = Field(Int, required=True) + edges = Field(List(of_type=AccountTokenEdge, required=True), required=True) + + +async def resolve_account_tokens( + root: dict, # pylint: disable=unused-argument + info: GraphQLResolveInfo, + limit: int = 10, + offset: int = 0, +) -> dict: + context: GraphqlContext = info.context + + if not context.account_session: + raise ValueError("An account_session is mandatory to execute this query") + + if not context.account_session.authenticated_by_jwt: + raise PermissionDeniedError("This operation requires authentication with a JWT token") + + node_schema = registry.get_node_schema(name=InfrahubKind.ACCOUNTTOKEN) + fields = await extract_fields_first_node(info) + + filters = {"account__ids": [context.account_session.account_id]} + response: dict[str, Any] = {} + if "count" in fields: + response["count"] = await NodeManager.count( + db=context.db, + schema=node_schema, + filters=filters, + ) + if "edges" in fields: + objs = await NodeManager.query( + db=context.db, + schema=node_schema, + filters=filters, + limit=limit, + offset=offset, + ) + + if objs: + objects = [ + { + "node": { + "id": obj.id, + "name": obj.name.value, # type: ignore[attr-defined] + "expiration": obj.expiration.value, # type: ignore[attr-defined] + } + } + for obj in objs + ] + response["edges"] = objects + + return response + + +AccountToken = Field( + AccountTokenEdges, + resolver=resolve_account_tokens, + limit=Int(required=False), + offset=Int(required=False), +) diff --git a/backend/infrahub/graphql/queries/ipam.py b/backend/infrahub/graphql/queries/ipam.py new file mode 100644 index 0000000000..c2b8e9a4b7 --- /dev/null +++ b/backend/infrahub/graphql/queries/ipam.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import ipaddress +from typing import TYPE_CHECKING, Optional + +from graphene import Field, Int, ObjectType, String + +from infrahub.core.constants import InfrahubKind +from infrahub.core.manager import NodeManager +from infrahub.core.query.ipam import get_ip_addresses, get_subnets +from infrahub.exceptions import NodeNotFoundError, ValidationError +from infrahub.pools.address import get_available +from infrahub.pools.prefix import PrefixPool + +if TYPE_CHECKING: + from graphql import GraphQLResolveInfo + + from infrahub.graphql import GraphqlContext + + +class IPAddressGetNextAvailable(ObjectType): + address = String(required=True) + + @staticmethod + async def resolve( + root: dict, # pylint: disable=unused-argument + info: GraphQLResolveInfo, + prefix_id: str, + prefix_length: Optional[int] = None, + ) -> dict[str, str]: + context: GraphqlContext = info.context + + prefix = await NodeManager.get_one(id=prefix_id, db=context.db, branch=context.branch) + + if not prefix: + raise NodeNotFoundError( + branch_name=context.branch.name, node_type=InfrahubKind.IPPREFIX, identifier=prefix_id + ) + + ip_prefix = ipaddress.ip_network(prefix.prefix.value) # type: ignore[attr-defined] + prefix_length = prefix_length or ip_prefix.prefixlen + + if not ip_prefix.prefixlen <= prefix_length <= ip_prefix.max_prefixlen: + raise ValidationError(input_value="Invalid prefix length for current selected prefix") + + namespace = await prefix.ip_namespace.get_peer(db=context.db) # type: ignore[attr-defined] + addresses = await get_ip_addresses( + db=context.db, + ip_prefix=ip_prefix, + namespace=namespace, + branch=context.branch, + ) + + available = get_available( + network=ip_prefix, + addresses=[ip.address for ip in addresses], + is_pool=prefix.is_pool.value, # type: ignore[attr-defined] + ) + + if not available: + raise IndexError("No addresses available in prefix") + + next_address = available.iter_cidrs()[0] + + return {"address": f"{next_address.ip}/{prefix_length}"} + + +class IPPrefixGetNextAvailable(ObjectType): + prefix = String(required=True) + + @staticmethod + async def resolve( + root: dict, # pylint: disable=unused-argument + info: GraphQLResolveInfo, + prefix_id: str, + prefix_length: int, + ) -> dict[str, str]: + context: GraphqlContext = info.context + + prefix = await NodeManager.get_one(id=prefix_id, db=context.db, branch=context.branch) + + if not prefix: + raise NodeNotFoundError( + branch_name=context.branch.name, node_type=InfrahubKind.IPPREFIX, identifier=prefix_id + ) + + namespace = await prefix.ip_namespace.get_peer(db=context.db) # type: ignore[attr-defined] + subnets = await get_subnets( + db=context.db, + ip_prefix=ipaddress.ip_network(prefix.prefix.value), # type: ignore[attr-defined] + namespace=namespace, + branch=context.branch, + ) + + pool = PrefixPool(prefix.prefix.value) # type: ignore[attr-defined] + for subnet in subnets: + pool.reserve(subnet=str(subnet.prefix)) + + next_available = pool.get(prefixlen=prefix_length) + return {"prefix": str(next_available)} + + +InfrahubIPAddressGetNextAvailable = Field( + IPAddressGetNextAvailable, + prefix_id=String(required=True), + prefix_length=Int(required=False), + resolver=IPAddressGetNextAvailable.resolve, +) + + +InfrahubIPPrefixGetNextAvailable = Field( + IPPrefixGetNextAvailable, + prefix_id=String(required=True), + prefix_length=Int(required=False), + resolver=IPPrefixGetNextAvailable.resolve, +) diff --git a/backend/infrahub/graphql/queries/resource_manager.py b/backend/infrahub/graphql/queries/resource_manager.py new file mode 100644 index 0000000000..9cc45047cc --- /dev/null +++ b/backend/infrahub/graphql/queries/resource_manager.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from graphene import Field, Float, Int, List, ObjectType, String +from infrahub_sdk.utils import extract_fields_first_node + +from infrahub.core import registry +from infrahub.core.constants import InfrahubKind +from infrahub.core.ipam.utilization import PrefixUtilizationGetter +from infrahub.core.manager import NodeManager +from infrahub.core.query.ipam import IPPrefixUtilization +from infrahub.core.query.resource_manager import IPAddressPoolGetIdentifiers, PrefixPoolGetIdentifiers +from infrahub.exceptions import NodeNotFoundError, ValidationError + +if TYPE_CHECKING: + from graphql import GraphQLResolveInfo + + from infrahub.core.node import Node + from infrahub.database import InfrahubDatabase + from infrahub.graphql import GraphqlContext + + +class IPPoolUtilizationResource(ObjectType): + id = Field(String, required=True, description="The ID of the current resource") + display_label = Field(String, required=True, description="The common name of the resource") + kind = Field(String, required=True, description="The resource kind") + weight = Field(Int, required=True, description="The relative weight of this resource.") + utilization = Field(Float, required=True, description="The overall utilization of the resource.") + utilization_branches = Field( + Float, required=True, description="The utilization of the resource on all non default branches." + ) + utilization_default_branch = Field( + Float, required=True, description="The overall utilization of the resource isolated to the default branch." + ) + + +class IPPrefixUtilizationEdge(ObjectType): + node = Field(IPPoolUtilizationResource, required=True) + + +class PoolAllocatedNode(ObjectType): + id = Field(String, required=True, description="The ID of the allocated node") + display_label = Field(String, required=True, description="The common name of the resource") + kind = Field(String, required=True, description="The node kind") + branch = Field(String, required=True, description="The branch where the node is allocated") + identifier = Field(String, required=False, description="Identifier used for the allocation") + + +class PoolAllocatedEdge(ObjectType): + node = Field(PoolAllocatedNode, required=True) + + +def _validate_pool_type(pool_id: str, pool: Optional[Node] = None) -> Node: + if not pool or pool._schema.kind not in [InfrahubKind.IPADDRESSPOOL, InfrahubKind.IPPREFIXPOOL]: + raise NodeNotFoundError(node_type="ResourcePool", identifier=pool_id) + return pool + + +class PoolAllocated(ObjectType): + count = Field(Int, required=True, description="The number of allocations within the selected pool.") + edges = Field(List(of_type=PoolAllocatedEdge, required=True), required=True) + + @staticmethod + async def resolve( # pylint: disable=unused-argument + root: dict, + info: GraphQLResolveInfo, + pool_id: str, + resource_id: str, + offset: int = 0, + limit: int = 10, + ) -> dict: + context: GraphqlContext = info.context + pool = await NodeManager.get_one(id=pool_id, db=context.db, branch=context.branch) + + pool = _validate_pool_type(pool_id=pool_id, pool=pool) + resources = await pool.resources.get_peers(db=context.db) # type: ignore[attr-defined,union-attr] + if resource_id not in resources: + raise ValidationError( + input_value=f"The selected pool_id={pool_id} doesn't contain the requested resource_id={resource_id}" + ) + + resource = resources[resource_id] + + query = await IPPrefixUtilization.init( + db=context.db, at=context.at, ip_prefixes=[resource], offset=offset, limit=limit + ) + fields = await extract_fields_first_node(info=info) + response: dict[str, Any] = {} + if "count" in fields: + response["count"] = await query.count(db=context.db) + + if edges := fields.get("edges"): + await query.execute(db=context.db) + + node_fields = edges.get("node", {}) + + nodes = [] + for result in query.get_results(): + child_node = result.get_node("child") + child_value_node = result.get_node("av") + node_id = str(child_node.get("uuid")) + + child_ip_value = child_value_node.get("value") + kind = child_node.get("kind") + branch_name = str(result.get("branch")) + + nodes.append( + {"node": {"id": node_id, "kind": kind, "branch": branch_name, "display_label": child_ip_value}} + ) + + if "identifier" in node_fields: + allocated_ids = [node["node"]["id"] for node in nodes] + identifier_query_map = { + InfrahubKind.IPADDRESSPOOL: IPAddressPoolGetIdentifiers, + InfrahubKind.IPPREFIXPOOL: PrefixPoolGetIdentifiers, + } + identifier_query_class = identifier_query_map.get(pool.get_kind()) + if not identifier_query_class: + raise ValidationError(input_value=f"This query doesn't get support {pool.get_kind()}") + identifier_query = await identifier_query_class.init( + db=context.db, at=context.at, pool_id=pool_id, allocated=allocated_ids + ) + await identifier_query.execute(db=context.db) + + reservations = {} + for result in identifier_query.get_results(): + reservation = result.get_rel("reservation") + allocated = result.get_node("allocated") + reservations[allocated.get("uuid")] = reservation.get("identifier") + + for node in nodes: + node["node"]["identifier"] = reservations.get(node["node"]["id"]) + + response["edges"] = nodes + + return response + + +class PoolUtilization(ObjectType): + count = Field(Int, required=True, description="The number of resources within the selected pool.") + utilization = Field(Float, required=True, description="The overall utilization of the pool.") + utilization_branches = Field(Float, required=True, description="The utilization in all non default branches.") + utilization_default_branch = Field( + Float, required=True, description="The overall utilization of the pool isolated to the default branch." + ) + edges = Field(List(of_type=IPPrefixUtilizationEdge, required=True), required=True) + + @staticmethod + async def resolve( # pylint: disable=unused-argument,too-many-branches + root: dict, + info: GraphQLResolveInfo, + pool_id: str, + ) -> dict: + context: GraphqlContext = info.context + db: InfrahubDatabase = context.db + pool = await NodeManager.get_one(id=pool_id, db=db, branch=context.branch) + _validate_pool_type(pool_id=pool_id, pool=pool) + resources_map: dict[str, Node] = await pool.resources.get_peers(db=db, branch_agnostic=True) # type: ignore[attr-defined,union-attr] + utilization_getter = PrefixUtilizationGetter(db=db, ip_prefixes=list(resources_map.values()), at=context.at) + fields = await extract_fields_first_node(info=info) + response: dict[str, Any] = {} + total_utilization = None + default_branch_utilization = None + if "count" in fields: + response["count"] = len(resources_map) + if "utilization" in fields: + response["utilization"] = total_utilization = await utilization_getter.get_use_percentage() + if "utilization_default_branch" in fields: + response["utilization_default_branch"] = ( + default_branch_utilization + ) = await utilization_getter.get_use_percentage(branch_names=[registry.default_branch]) + if "utilization_branches" in fields: + total_utilization = ( + total_utilization if total_utilization is not None else await utilization_getter.get_use_percentage() + ) + default_branch_utilization = ( + default_branch_utilization + if default_branch_utilization is not None + else await utilization_getter.get_use_percentage(branch_names=[registry.default_branch]) + ) + response["utilization_branches"] = total_utilization - default_branch_utilization + if "edges" in fields: + response["edges"] = [] + if "node" in fields["edges"]: + node_fields = fields["edges"]["node"] + for resource_id, resource_node in resources_map.items(): + resource_total = None + default_branch_total = None + node_response: dict[str, Union[str, float, int]] = {} + if "id" in node_fields: + node_response["id"] = resource_id + if "kind" in node_fields: + node_response["kind"] = resource_node.get_kind() + if "display_label" in node_fields: + node_response["display_label"] = await resource_node.render_display_label(db=db) + if "weight" in node_fields: + node_response["weight"] = await resource_node.get_resource_weight(db=db) # type: ignore[attr-defined] + if "utilization" in node_fields: + node_response["utilization"] = resource_total = await utilization_getter.get_use_percentage( + ip_prefixes=[resource_node] + ) + if "utilization_default_branch" in node_fields: + node_response["utilization_default_branch"] = ( + default_branch_total + ) = await utilization_getter.get_use_percentage( + ip_prefixes=[resource_node], branch_names=[registry.default_branch] + ) + if "utilization_branches" in node_fields: + resource_total = ( + resource_total + if resource_total is not None + else await utilization_getter.get_use_percentage(ip_prefixes=[resource_node]) + ) + default_branch_total = ( + default_branch_total + if default_branch_total is not None + else await utilization_getter.get_use_percentage( + ip_prefixes=[resource_node], branch_names=[registry.default_branch] + ) + ) + node_response["utilization_branches"] = resource_total - default_branch_total + response["edges"].append({"node": node_response}) + + return response + + +InfrahubResourcePoolAllocated = Field( + PoolAllocated, + pool_id=String(required=True), + resource_id=String(required=True), + limit=Int(required=False), + offset=Int(required=False), + resolver=PoolAllocated.resolve, +) + + +InfrahubResourcePoolUtilization = Field( + PoolUtilization, + pool_id=String(required=True), + resolver=PoolUtilization.resolve, +) diff --git a/backend/infrahub/graphql/queries/status.py b/backend/infrahub/graphql/queries/status.py index 5a01326266..d1f7c94093 100644 --- a/backend/infrahub/graphql/queries/status.py +++ b/backend/infrahub/graphql/queries/status.py @@ -46,7 +46,9 @@ async def resolve_status( service = context.service or services.service fields = await extract_fields_first_node(info) response: dict[str, Any] = {} - workers = await service.component.list_workers(branch=context.branch.name, schema_hash=True) + workers = await service.component.list_workers( + branch=context.branch.id if context.branch.id else context.branch.name, schema_hash=True + ) if summary := fields.get("summary"): response["summary"] = {} diff --git a/backend/infrahub/graphql/query.py b/backend/infrahub/graphql/query.py index a4db942453..29c77d7c90 100644 --- a/backend/infrahub/graphql/query.py +++ b/backend/infrahub/graphql/query.py @@ -31,7 +31,7 @@ async def execute_query( at = Timestamp(at) graphql_query = await NodeManager.get_one_by_default_filter( - db=db, id=name, schema_name=InfrahubKind.GRAPHQLQUERY, branch=branch, at=at + db=db, id=name, kind=InfrahubKind.GRAPHQLQUERY, branch=branch, at=at ) if not graphql_query: raise ValueError(f"Unable to find the {InfrahubKind.GRAPHQLQUERY} {name}") diff --git a/backend/infrahub/graphql/schema.py b/backend/infrahub/graphql/schema.py index 859fdd5d1e..992bf2e2bf 100644 --- a/backend/infrahub/graphql/schema.py +++ b/backend/infrahub/graphql/schema.py @@ -18,6 +18,9 @@ BranchValidate, CoreAccountSelfUpdate, CoreAccountTokenCreate, + CoreAccountTokenDelete, + IPAddressPoolGetResource, + IPPrefixPoolGetResource, ProposedChangeRequestRunCheck, RelationshipAdd, RelationshipRemove, @@ -29,7 +32,20 @@ TaskUpdate, ) from .parser import extract_selection -from .queries import BranchQueryList, DiffSummary, DiffSummaryOld, InfrahubInfo, InfrahubStatus, Relationship, Task +from .queries import ( + AccountToken, + BranchQueryList, + DiffSummary, + DiffSummaryOld, + InfrahubInfo, + InfrahubIPAddressGetNextAvailable, + InfrahubIPPrefixGetNextAvailable, + InfrahubResourcePoolAllocated, + InfrahubResourcePoolUtilization, + InfrahubStatus, + Relationship, + Task, +) if TYPE_CHECKING: from graphql import GraphQLResolveInfo @@ -66,6 +82,7 @@ async def account_resolver(root, info: GraphQLResolveInfo): class InfrahubBaseQuery(ObjectType): Branch = BranchQueryList + CoreAccountToken = AccountToken DiffSummary = DiffSummary DiffSummaryOld = DiffSummaryOld @@ -77,12 +94,21 @@ class InfrahubBaseQuery(ObjectType): InfrahubTask = Task + IPAddressGetNextAvailable = InfrahubIPAddressGetNextAvailable + IPPrefixGetNextAvailable = InfrahubIPPrefixGetNextAvailable + InfrahubResourcePoolAllocated = InfrahubResourcePoolAllocated + InfrahubResourcePoolUtilization = InfrahubResourcePoolUtilization + class InfrahubBaseMutation(ObjectType): CoreAccountTokenCreate = CoreAccountTokenCreate.Field() CoreAccountSelfUpdate = CoreAccountSelfUpdate.Field() + CoreAccountTokenDelete = CoreAccountTokenDelete.Field() CoreProposedChangeRunCheck = ProposedChangeRequestRunCheck.Field() + IPPrefixPoolGetResource = IPPrefixPoolGetResource.Field() + IPAddressPoolGetResource = IPAddressPoolGetResource.Field() + BranchCreate = BranchCreate.Field() BranchDelete = BranchDelete.Field() BranchRebase = BranchRebase.Field() diff --git a/backend/infrahub/graphql/subscription/graphql_query.py b/backend/infrahub/graphql/subscription/graphql_query.py index 05c4e441bb..94cd880fa6 100644 --- a/backend/infrahub/graphql/subscription/graphql_query.py +++ b/backend/infrahub/graphql/subscription/graphql_query.py @@ -30,7 +30,7 @@ async def resolver_graphql_query( async with context.db.start_session() as db: # Find the GraphQLQuery and the GraphQL Schema graphql_query = await NodeManager.get_one_by_default_filter( - db=db, id=name, schema_name=InfrahubKind.GRAPHQLQUERY, branch=context.branch, at=at + db=db, id=name, kind=InfrahubKind.GRAPHQLQUERY, branch=context.branch, at=at ) if not graphql_query: raise ValueError(f"Unable to find the {InfrahubKind.GRAPHQLQUERY} {name}") diff --git a/backend/infrahub/graphql/types/__init__.py b/backend/infrahub/graphql/types/__init__.py index 304ea79a5c..85a13d472a 100644 --- a/backend/infrahub/graphql/types/__init__.py +++ b/backend/infrahub/graphql/types/__init__.py @@ -16,7 +16,9 @@ JSONAttributeType, ListAttributeType, NumberAttributeType, + RelatedIPAddressNodeInput, RelatedNodeInput, + RelatedPrefixNodeInput, StrAttributeType, TextAttributeType, ) @@ -30,7 +32,6 @@ from .task_log import TaskLog, TaskLogEdge, TaskLogNodes __all__ = [ - "RelatedNodeInput", "AttributeInterface", "BaseAttribute", "DropdownFields", @@ -51,6 +52,9 @@ "GetListMixin", "InfrahubObject", "InfrahubObjectType", + "RelatedIPAddressNodeInput", + "RelatedNodeInput", + "RelatedPrefixNodeInput", "RelationshipNode", "TaskLog", "TaskLogEdge", diff --git a/backend/infrahub/graphql/types/attribute.py b/backend/infrahub/graphql/types/attribute.py index 2694d97bec..04157f6c47 100644 --- a/backend/infrahub/graphql/types/attribute.py +++ b/backend/infrahub/graphql/types/attribute.py @@ -1,6 +1,6 @@ from __future__ import annotations -from graphene import Boolean, DateTime, Field, InputObjectType, Int, ObjectType, String +from graphene import Boolean, DateTime, Field, InputObjectType, Int, List, ObjectType, String from graphene.types.generic import GenericScalar from infrahub.core import registry @@ -9,7 +9,43 @@ class RelatedNodeInput(InputObjectType): + id = String(required=False) + hfid = Field(List(of_type=String), required=False) + _relation__is_visible = Boolean(required=False) + _relation__is_protected = Boolean(required=False) + _relation__owner = String(required=False) + _relation__source = String(required=False) + + +class IPAddressPoolInput(InputObjectType): + id = String(required=True) + prefixlen = Int(required=False) + identifier = String(required=False) + data = GenericScalar(required=False) + + +class PrefixPoolInput(InputObjectType): id = String(required=True) + size = Int(required=False) + identifier = String(required=False) + member_type = String(required=False) + prefix_type = String(required=False) + data = GenericScalar(required=False) + + +class RelatedIPAddressNodeInput(InputObjectType): + id = String(required=False) + from_pool = Field(IPAddressPoolInput, required=False) + _relation__is_visible = Boolean(required=False) + _relation__is_protected = Boolean(required=False) + _relation__owner = String(required=False) + _relation__source = String(required=False) + + +class RelatedPrefixNodeInput(InputObjectType): + id = String(required=False) + hfid = Field(List(of_type=String), required=False) + from_pool = Field(PrefixPoolInput, required=False) _relation__is_visible = Boolean(required=False) _relation__is_protected = Boolean(required=False) _relation__owner = String(required=False) diff --git a/backend/infrahub/graphql/types/branch.py b/backend/infrahub/graphql/types/branch.py index a8315b1c24..296b05c927 100644 --- a/backend/infrahub/graphql/types/branch.py +++ b/backend/infrahub/graphql/types/branch.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Any -from graphene import Boolean, String +from graphene import Boolean, Field, String from infrahub.core.branch import Branch from infrahub.core.constants import GLOBAL_BRANCH_NAME @@ -22,7 +22,7 @@ class BranchType(InfrahubObjectType): created_at = String(required=False) sync_with_git = Boolean(required=False) is_default = Boolean(required=False) - is_isolated = Boolean(required=False) + is_isolated = Field(Boolean(required=False), deprecation_reason="non isolated mode is not supported anymore") has_schema_changes = Boolean(required=False) class Meta: diff --git a/backend/infrahub/lock.py b/backend/infrahub/lock.py index d3f01b5c0b..2cf765bb8d 100644 --- a/backend/infrahub/lock.py +++ b/backend/infrahub/lock.py @@ -4,7 +4,7 @@ import uuid from asyncio import Lock as LocalLock from asyncio import sleep -from typing import TYPE_CHECKING, Dict, List, Optional, Type +from typing import TYPE_CHECKING, Dict, List, Optional, Type, Union import redis.asyncio as redis from prometheus_client import Histogram @@ -15,6 +15,8 @@ if TYPE_CHECKING: from types import TracebackType + from infrahub.services import InfrahubServices + registry: InfrahubLockRegistry = None @@ -67,6 +69,40 @@ async def release(self) -> None: await self.registry.get(name=lock).release() +class NATSLock: + """Context manager to lock using NATS""" + + def __init__(self, service: InfrahubServices, name: str): + self.name = name + self.token = None + self.service = service + + async def __aenter__(self): + await self.acquire() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ): + await self.release() + + async def acquire(self) -> None: + token = uuid.uuid1().hex + while True: + if await self.do_acquire(token): + self.token = token + return True + await sleep(0.1) # default Redis GlobalLock value + + async def do_acquire(self, token: str) -> bool: + return await self.service.cache.set(key=self.name, value=token, not_exists=True) + + async def release(self) -> None: + await self.service.cache.delete(key=self.name) + + class InfrahubLock: """InfrahubLock object to provide a unified interface for both Local and Distributed locks. @@ -74,7 +110,11 @@ class InfrahubLock: """ def __init__( - self, name: str, connection: Optional[redis.Redis] = None, local: Optional[bool] = None, in_multi: bool = False + self, + name: str, + connection: Optional[Union[redis.Redis, InfrahubServices]] = None, + local: Optional[bool] = None, + in_multi: bool = False, ): self.use_local: bool = local self.local: LocalLock = None @@ -90,8 +130,10 @@ def __init__( if self.use_local: self.local = LocalLock() - else: + elif config.SETTINGS.cache.driver == config.CacheDriver.Redis: self.remote = GlobalLock(redis=self.connection, name=self.name) + else: + self.remote = NATSLock(service=self.connection, name=self.name) async def __aenter__(self): await self.acquire() @@ -128,13 +170,22 @@ async def locked(self) -> bool: class InfrahubLockRegistry: - def __init__(self, token: Optional[str] = None, local_only: bool = False): + def __init__( + self, token: Optional[str] = None, local_only: bool = False, service: Optional[InfrahubServices] = None + ): if config.SETTINGS.cache.enable and not local_only: - self.connection = redis.Redis( - host=config.SETTINGS.cache.address, - port=config.SETTINGS.cache.service_port, - db=config.SETTINGS.cache.database, - ) + if config.SETTINGS.cache.driver == config.CacheDriver.Redis: + self.connection = redis.Redis( + host=config.SETTINGS.cache.address, + port=config.SETTINGS.cache.service_port, + db=config.SETTINGS.cache.database, + ssl=config.SETTINGS.cache.tls_enabled, + ssl_cert_reqs="optional" if not config.SETTINGS.cache.tls_insecure else "none", + ssl_check_hostname=not config.SETTINGS.cache.tls_insecure, + ssl_ca_certs=config.SETTINGS.cache.tls_ca_file, + ) + else: + self.connection = service else: self.connection = None @@ -191,6 +242,6 @@ async def wait_until_available(self, name: str) -> None: await sleep(0.1) -def initialize_lock(local_only: bool = False): +def initialize_lock(local_only: bool = False, service: Optional[InfrahubServices] = None): global registry # pylint: disable=global-statement - registry = InfrahubLockRegistry(local_only=local_only) + registry = InfrahubLockRegistry(local_only=local_only, service=service) diff --git a/backend/infrahub/message_bus/messages/__init__.py b/backend/infrahub/message_bus/messages/__init__.py index 13124a8eca..d949d028b8 100644 --- a/backend/infrahub/message_bus/messages/__init__.py +++ b/backend/infrahub/message_bus/messages/__init__.py @@ -47,6 +47,7 @@ from .schema_migration_path import SchemaMigrationPath, SchemaMigrationPathResponse from .schema_validator_path import SchemaValidatorPath, SchemaValidatorPathResponse from .send_echo_request import SendEchoRequest, SendEchoRequestResponse +from .send_telemetry_push import SendTelemetryPush from .send_webhook_event import SendWebhookEvent from .transform_jinja_template import TransformJinjaTemplate, TransformJinjaTemplateResponse from .transform_python_data import TransformPythonData, TransformPythonDataResponse @@ -103,6 +104,7 @@ "request.repository.user_checks": RequestRepositoryUserChecks, "send.echo.request": SendEchoRequest, "send.webhook.event": SendWebhookEvent, + "send.telemetry.push": SendTelemetryPush, "transform.jinja.template": TransformJinjaTemplate, "transform.python.data": TransformPythonData, "trigger.artifact_definition.generate": TriggerArtifactDefinitionGenerate, diff --git a/backend/infrahub/message_bus/messages/schema_validator_path.py b/backend/infrahub/message_bus/messages/schema_validator_path.py index 2cd99bb472..68a22de2ca 100644 --- a/backend/infrahub/message_bus/messages/schema_validator_path.py +++ b/backend/infrahub/message_bus/messages/schema_validator_path.py @@ -1,12 +1,12 @@ from __future__ import annotations -from typing import List, Optional, Union +from typing import List, Optional from pydantic import Field from infrahub.core.branch import Branch # noqa: TCH001 from infrahub.core.path import SchemaPath # noqa: TCH001 -from infrahub.core.schema import GenericSchema, NodeSchema # noqa: TCH001 +from infrahub.core.schema import MainSchemaTypes # noqa: TCH001 from infrahub.core.validators.model import SchemaViolation # noqa: TCH001 from infrahub.message_bus import InfrahubMessage, InfrahubResponse, InfrahubResponseData @@ -16,7 +16,7 @@ class SchemaValidatorPath(InfrahubMessage): branch: Branch = Field(..., description="The name of the branch to target") constraint_name: str = Field(..., description="The name of the constraint to validate") - node_schema: Union[NodeSchema, GenericSchema] = Field(..., description="Schema of Node or Generic to validate") + node_schema: MainSchemaTypes = Field(..., description="Schema of Node or Generic to validate") schema_path: SchemaPath = Field(..., description="SchemaPath to the element of the schema to validate") diff --git a/backend/infrahub/message_bus/messages/send_telemetry_push.py b/backend/infrahub/message_bus/messages/send_telemetry_push.py new file mode 100644 index 0000000000..0f2b148780 --- /dev/null +++ b/backend/infrahub/message_bus/messages/send_telemetry_push.py @@ -0,0 +1,5 @@ +from infrahub.message_bus import InfrahubMessage + + +class SendTelemetryPush(InfrahubMessage): + """Push usage telemetry.""" diff --git a/backend/infrahub/message_bus/operations/__init__.py b/backend/infrahub/message_bus/operations/__init__.py index 6b4f0ed155..e8914d4b04 100644 --- a/backend/infrahub/message_bus/operations/__init__.py +++ b/backend/infrahub/message_bus/operations/__init__.py @@ -1,3 +1,5 @@ +from typing import Optional + import ujson from infrahub.message_bus import RPCErrorResponse, messages @@ -62,6 +64,7 @@ "request.repository.user_checks": requests.repository.user_checks, "send.echo.request": send.echo.request, "send.webhook.event": send.webhook.event, + "send.telemetry.push": send.telemetry.push, "schema.migration.path": schema.migration.path, "schema.validator.path": schema.validator.path, "transform.jinja.template": transform.jinja.template, @@ -74,7 +77,7 @@ } -async def execute_message(routing_key: str, message_body: bytes, service: InfrahubServices): +async def execute_message(routing_key: str, message_body: bytes, service: InfrahubServices) -> Optional[MessageTTL]: message_data = ujson.loads(message_body) message = messages.MESSAGE_MAP[routing_key](**message_data) message.set_log_data(routing_key=routing_key) @@ -84,10 +87,11 @@ async def execute_message(routing_key: str, message_body: bytes, service: Infrah if message.reply_requested: response = RPCErrorResponse(errors=[str(exc)], initial_message=message.model_dump()) await service.reply(message=response, initiator=message) - return + return None if message.reached_max_retries: service.log.exception("Message failed after maximum number of retries", error=exc) await set_check_status(message, conclusion="failure", service=service) - return + return None message.increase_retry_count() - await service.send(message, delay=MessageTTL.FIVE) + await service.send(message, delay=MessageTTL.FIVE, is_retry=True) + return MessageTTL.FIVE diff --git a/backend/infrahub/message_bus/operations/check/repository.py b/backend/infrahub/message_bus/operations/check/repository.py index ef747bcaae..535e4f44ca 100644 --- a/backend/infrahub/message_bus/operations/check/repository.py +++ b/backend/infrahub/message_bus/operations/check/repository.py @@ -10,6 +10,7 @@ from infrahub.git.repository import InfrahubRepository from infrahub.log import get_logger from infrahub.message_bus import InfrahubMessage, messages +from infrahub.message_bus.types import KVTTL from infrahub.services import InfrahubServices log = get_logger() @@ -120,7 +121,9 @@ async def check_definition(message: messages.CheckRepositoryCheckDefinition, ser checks_in_execution = ",".join(check_execution_ids) log.info("Checks in execution", checks=checks_in_execution) await service.cache.set( - key=f"validator_execution_id:{validator_execution_id}:checks", value=checks_in_execution, expires=7200 + key=f"validator_execution_id:{validator_execution_id}:checks", + value=checks_in_execution, + expires=KVTTL.TWO_HOURS, ) events.append( messages.FinalizeValidatorExecution( @@ -213,7 +216,7 @@ async def merge_conflicts(message: messages.CheckRepositoryMergeConflicts, servi await service.cache.set( key=f"validator_execution_id:{message.validator_execution_id}:check_execution_id:{message.check_execution_id}", value=validator_conclusion, - expires=7200, + expires=KVTTL.TWO_HOURS, ) @@ -280,5 +283,5 @@ async def user_check(message: messages.CheckRepositoryUserCheck, service: Infrah await service.cache.set( key=f"validator_execution_id:{message.validator_execution_id}:check_execution_id:{message.check_execution_id}", value=conclusion, - expires=7200, + expires=KVTTL.TWO_HOURS, ) diff --git a/backend/infrahub/message_bus/operations/finalize/validator.py b/backend/infrahub/message_bus/operations/finalize/validator.py index 575295f0e9..50a206fed1 100644 --- a/backend/infrahub/message_bus/operations/finalize/validator.py +++ b/backend/infrahub/message_bus/operations/finalize/validator.py @@ -2,7 +2,7 @@ from infrahub.core.timestamp import Timestamp from infrahub.log import get_logger from infrahub.message_bus import messages -from infrahub.message_bus.types import MessageTTL +from infrahub.message_bus.types import KVTTL, MessageTTL from infrahub.services import InfrahubServices log = get_logger() @@ -53,7 +53,7 @@ async def execution(message: messages.FinalizeValidatorExecution, service: Infra if missing_checks: remaining_checks = ",".join(missing_checks) - await service.cache.set(key=checks_key, value=remaining_checks, expires=7200) + await service.cache.set(key=checks_key, value=remaining_checks, expires=KVTTL.TWO_HOURS) current_time = Timestamp() starting_time = Timestamp(message.start_time) deadline = starting_time.add_delta(seconds=config.SETTINGS.miscellaneous.maximum_validator_execution_time) diff --git a/backend/infrahub/message_bus/operations/requests/artifact_definition.py b/backend/infrahub/message_bus/operations/requests/artifact_definition.py index 439496c95b..4624826970 100644 --- a/backend/infrahub/message_bus/operations/requests/artifact_definition.py +++ b/backend/infrahub/message_bus/operations/requests/artifact_definition.py @@ -6,6 +6,7 @@ from infrahub.core.timestamp import Timestamp from infrahub.log import get_logger from infrahub.message_bus import InfrahubMessage, Meta, messages +from infrahub.message_bus.types import KVTTL from infrahub.services import InfrahubServices log = get_logger() @@ -115,7 +116,9 @@ async def check(message: messages.RequestArtifactDefinitionCheck, service: Infra checks_in_execution = ",".join(check_execution_ids) await service.cache.set( - key=f"validator_execution_id:{validator_execution_id}:checks", value=checks_in_execution, expires=7200 + key=f"validator_execution_id:{validator_execution_id}:checks", + value=checks_in_execution, + expires=KVTTL.TWO_HOURS, ) events.append( messages.FinalizeValidatorExecution( @@ -215,7 +218,7 @@ def _render_artifact(artifact_id: Optional[str], managed_branch: bool, impacted_ Will return true if: * The artifact_id wasn't set which could be that it's a new object that doesn't have a previous artifact * The source brance is not data only which would indicate that it could contain updates in git to the transform - * The artifact_id exists in the impaced_artifacts list + * The artifact_id exists in the impacted_artifacts list Will return false if: * The source branch is a data only branch and the artifact_id exists and is not in the impacted list """ diff --git a/backend/infrahub/message_bus/operations/requests/generator_definition.py b/backend/infrahub/message_bus/operations/requests/generator_definition.py index 54d3b500ba..a6459e54f6 100644 --- a/backend/infrahub/message_bus/operations/requests/generator_definition.py +++ b/backend/infrahub/message_bus/operations/requests/generator_definition.py @@ -5,6 +5,7 @@ from infrahub.core.constants import InfrahubKind, ValidatorConclusion, ValidatorState from infrahub.core.timestamp import Timestamp from infrahub.message_bus import InfrahubMessage, Meta, messages +from infrahub.message_bus.types import KVTTL from infrahub.services import InfrahubServices @@ -108,7 +109,9 @@ async def check(message: messages.RequestGeneratorDefinitionCheck, service: Infr checks_in_execution = ",".join(check_execution_ids) await service.cache.set( - key=f"validator_execution_id:{validator_execution_id}:checks", value=checks_in_execution, expires=7200 + key=f"validator_execution_id:{validator_execution_id}:checks", + value=checks_in_execution, + expires=KVTTL.TWO_HOURS, ) events.append( messages.FinalizeValidatorExecution( diff --git a/backend/infrahub/message_bus/operations/requests/proposed_change.py b/backend/infrahub/message_bus/operations/requests/proposed_change.py index 1a7104d370..02343dcdd4 100644 --- a/backend/infrahub/message_bus/operations/requests/proposed_change.py +++ b/backend/infrahub/message_bus/operations/requests/proposed_change.py @@ -360,10 +360,17 @@ async def refresh_artifacts(message: messages.RequestProposedChangeRefreshArtifa ) for changed_model in message.branch_diff.modified_kinds(branch=message.source_branch): + condition = False + if (changed_model in artifact_definition.query_models) or ( + changed_model.startswith("Profile") + and changed_model.replace("Profile", "", 1) in artifact_definition.query_models + ): + condition = True + select = select.add_flag( current=select, flag=DefinitionSelect.MODIFIED_KINDS, - condition=changed_model in artifact_definition.query_models, + condition=condition, ) await task_report.info(f"{artifact_definition.definition_name}: {select.log_line}") diff --git a/backend/infrahub/message_bus/operations/requests/repository.py b/backend/infrahub/message_bus/operations/requests/repository.py index 1605ac8d9f..872196a2f8 100644 --- a/backend/infrahub/message_bus/operations/requests/repository.py +++ b/backend/infrahub/message_bus/operations/requests/repository.py @@ -6,6 +6,7 @@ from infrahub.core.timestamp import Timestamp from infrahub.log import get_logger from infrahub.message_bus import InfrahubMessage, messages +from infrahub.message_bus.types import KVTTL from infrahub.services import InfrahubServices log = get_logger() @@ -75,7 +76,9 @@ async def checks(message: messages.RequestRepositoryChecks, service: InfrahubSer checks_in_execution = ",".join(check_execution_ids) log.info("Checks in execution", checks=checks_in_execution) await service.cache.set( - key=f"validator_execution_id:{validator_execution_id}:checks", value=checks_in_execution, expires=7200 + key=f"validator_execution_id:{validator_execution_id}:checks", + value=checks_in_execution, + expires=KVTTL.TWO_HOURS, ) events.append( messages.FinalizeValidatorExecution( diff --git a/backend/infrahub/message_bus/operations/send/__init__.py b/backend/infrahub/message_bus/operations/send/__init__.py index b66de2de85..fb6b746f43 100644 --- a/backend/infrahub/message_bus/operations/send/__init__.py +++ b/backend/infrahub/message_bus/operations/send/__init__.py @@ -1,3 +1,3 @@ -from . import echo, webhook +from . import echo, telemetry, webhook -__all__ = ["echo", "webhook"] +__all__ = ["echo", "telemetry", "webhook"] diff --git a/backend/infrahub/message_bus/operations/send/telemetry.py b/backend/infrahub/message_bus/operations/send/telemetry.py new file mode 100644 index 0000000000..ad4ccc9997 --- /dev/null +++ b/backend/infrahub/message_bus/operations/send/telemetry.py @@ -0,0 +1,113 @@ +import hashlib +import json +import platform +import time + +import httpx + +from infrahub import __version__, config +from infrahub.core import registry, utils +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.graph.schema import GRAPH_SCHEMA +from infrahub.message_bus import messages +from infrahub.services import InfrahubServices + +TELEMETRY_KIND: str = "community" +TELEMETRY_VERSION: str = "20240524" + + +async def gather_database_information(service: InfrahubServices, branch: Branch) -> dict: # pylint: disable=unused-argument + data = { + "database_type": service.database.db_type.value, + "relationship_count": {"total": await utils.count_relationships(db=service.database)}, + "node_count": {"total": await utils.count_nodes(db=service.database)}, + } + + for name in GRAPH_SCHEMA["relationships"]: + data["relationship_count"][name] = await utils.count_relationships(db=service.database, label=name) + + for name in GRAPH_SCHEMA["nodes"]: + data["node_count"][name] = await utils.count_nodes(db=service.database, label=name) + + return data + + +async def gather_schema_information(service: InfrahubServices, branch: Branch) -> dict: # pylint: disable=unused-argument + data = {} + main_schema = registry.schema.get_schema_branch(name=branch.name) + data["node_count"] = len(main_schema.node_names) + data["generic_count"] = len(main_schema.generic_names) + data["last_update"] = branch.schema_changed_at + + return data + + +async def gather_feature_information(service: InfrahubServices, branch: Branch) -> dict: # pylint: disable=unused-argument + data = {} + features_to_count = [ + InfrahubKind.ARTIFACT, + InfrahubKind.RESOURCEPOOL, + InfrahubKind.REPOSITORY, + InfrahubKind.GENERICGROUP, + InfrahubKind.PROFILE, + InfrahubKind.PROPOSEDCHANGE, + InfrahubKind.TRANSFORM, + ] + for kind in features_to_count: + data[kind] = await utils.count_nodes(db=service.database, label=kind) + + return data + + +async def gather_anonymous_telemetry_data(service: InfrahubServices) -> dict: + start_time = time.time() + + default_branch = registry.get_branch_from_registry() + workers = await service.component.list_workers(branch=default_branch.name, schema_hash=False) + + data = { + "deployment_id": registry.id, + "execution_time": None, + "infrahub_version": __version__, + "python_version": platform.python_version(), + "platform": platform.machine(), + "workers": { + "total": len(workers), + "active": len([w for w in workers if w.active]), + }, + "branches": { + "total": len(registry.branch), + }, + "features": await gather_feature_information(service=service, branch=default_branch), + "schema": await gather_schema_information(service=service, branch=default_branch), + "database": await gather_database_information(service=service, branch=default_branch), + } + + data["execution_time"] = time.time() - start_time + + return data + + +async def push( + message: messages.SendTelemetryPush, # pylint: disable=unused-argument + service: InfrahubServices, +) -> None: + service.log.debug("Received telemetry push message...") + + data = await gather_anonymous_telemetry_data(service=service) + service.log.debug(f"Anonymous usage telemetry gathered in {data['execution_time']} seconds.") + + payload = { + "kind": TELEMETRY_KIND, + "payload_format": TELEMETRY_VERSION, + "data": data, + "checksum": hashlib.sha256(json.dumps(data).encode()).hexdigest(), + } + + async with httpx.AsyncClient(timeout=5.0) as client: + try: + response = await client.post(config.SETTINGS.main.telemetry_endpoint, json=payload) + response.raise_for_status() + except httpx.HTTPError as exc: + service.log.debug(f"HTTP exception while pushing anonymous telemetry: {exc}") diff --git a/backend/infrahub/message_bus/types.py b/backend/infrahub/message_bus/types.py index 11fa7f1b35..8f588e02d7 100644 --- a/backend/infrahub/message_bus/types.py +++ b/backend/infrahub/message_bus/types.py @@ -26,6 +26,20 @@ def variations(cls) -> List[MessageTTL]: return [cls(cls.__members__[member].value) for member in list(cls.__members__)] +class KVTTL(int, Enum): + """Defines the KV TTL in seconds.""" + + ONE = 1 + TEN = 10 + FIFTEEN = 15 + TWO_HOURS = 7200 + + @classmethod + def variations(cls) -> List[KVTTL]: + """Return available variations of KV time to live.""" + return [cls(cls.__members__[member].value) for member in list(cls.__members__)] + + class ProposedChangeRepository(BaseModel): repository_id: str repository_name: str diff --git a/backend/infrahub/pools/__init__.py b/backend/infrahub/pools/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/infrahub/pools/address.py b/backend/infrahub/pools/address.py new file mode 100644 index 0000000000..6c5892c389 --- /dev/null +++ b/backend/infrahub/pools/address.py @@ -0,0 +1,16 @@ +from netaddr import IPNetwork, IPSet + +from infrahub.core.ipam.constants import IPAddressType, IPNetworkType + + +def get_available(network: IPNetworkType, addresses: list[IPAddressType], is_pool: bool) -> IPSet: + pool = IPSet(IPNetwork(str(network))) + reserved = [IPNetwork(f"{str(address.ip)}/{address.max_prefixlen}") for address in addresses] + if not is_pool: + # If the specified network is not a pool we remove the network address and + # optionally the broadcast address in case of IPv4 + reserved.append(IPNetwork(f"{str(network.network_address)}/{network.max_prefixlen}")) + if network.version == 4: + reserved.append(IPNetwork(f"{str(network.broadcast_address)}/{network.max_prefixlen}")) + + return pool - IPSet(reserved) diff --git a/backend/infrahub/pools/prefix.py b/backend/infrahub/pools/prefix.py new file mode 100644 index 0000000000..374acef6d4 --- /dev/null +++ b/backend/infrahub/pools/prefix.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import ipaddress +from collections import OrderedDict, defaultdict +from ipaddress import IPv4Network, IPv6Network +from typing import Optional, Union + + +class PrefixPool: + """ + Class to automatically manage Prefixes and help to carve out sub-prefixes + """ + + def __init__(self, network: str): + self.network = ipaddress.ip_network(network) + + # Define biggest and smallest possible masks + self.mask_biggest = self.network.prefixlen + 1 + if self.network.version == 4: + self.mask_smallest = 32 + else: + self.mask_smallest = 128 + + self.available_subnets = defaultdict(list) + self.sub_by_key: dict[str, Optional[str]] = OrderedDict() + self.sub_by_id: dict[str, str] = OrderedDict() + + # Save the top level available subnet + for subnet in list(self.network.subnets(new_prefix=self.mask_biggest)): + self.available_subnets[self.mask_biggest].append(str(subnet)) + + def reserve(self, subnet: str, identifier: Optional[str] = None) -> bool: + """ + Indicate that a specific subnet is already reserved/used + """ + + # TODO Add check to make sure the subnet provided has the right size + sub = ipaddress.ip_network(subnet) + + if int(sub.prefixlen) <= int(self.network.prefixlen): + raise ValueError(f"{subnet} do not have the right size ({sub.prefixlen},{self.network.prefixlen})") + + if sub.supernet(new_prefix=self.network.prefixlen) != self.network: + raise ValueError(f"{subnet} is not part of this network") + + # Check first if this ID as already done a reservation + if identifier and identifier in self.sub_by_id.keys(): + if self.sub_by_id[identifier] == str(sub): + return True + raise ValueError( + f"this identifier ({identifier}) is already used but for a different resource ({self.sub_by_id[identifier]})" + ) + + if identifier and str(sub) in self.sub_by_key.keys(): + raise ValueError(f"this subnet is already reserved but not with this identifier ({identifier})") + + if str(sub) in self.sub_by_key.keys(): + self.remove_subnet_from_available_list(sub) + return True + + # Check if the subnet itself is available + # if available reserve and return + if subnet in self.available_subnets[sub.prefixlen]: + if identifier: + self.sub_by_id[identifier] = subnet + self.sub_by_key[subnet] = identifier + else: + self.sub_by_key[subnet] = None + + self.remove_subnet_from_available_list(sub) + return True + + # If not reserved already, check if the subnet is available + # start at sublen and check all available subnet + # increase 1 by 1 until we find the closer supernet available + # break it down and keep track of the other available subnets + + for sublen in range(sub.prefixlen - 1, self.network.prefixlen, -1): + supernet = sub.supernet(new_prefix=sublen) + if str(supernet) in self.available_subnets[sublen]: + self.split_supernet(supernet=supernet, subnet=sub) + return self.reserve(subnet=subnet, identifier=identifier) + + return False + + def get(self, prefixlen: int, identifier: Optional[str] = None) -> Union[IPv4Network, IPv6Network]: + """Return the next available Subnet.""" + + clean_prefixlen = int(prefixlen) + + if identifier and identifier in self.sub_by_id.keys(): + net = ipaddress.ip_network(self.sub_by_id[identifier]) + if net.prefixlen == clean_prefixlen: + return net + raise ValueError() + + if len(self.available_subnets[clean_prefixlen]) != 0: + sub = self.available_subnets[clean_prefixlen][0] + self.reserve(subnet=sub, identifier=identifier) + return ipaddress.ip_network(sub) + + # if a subnet of this size is not available + # we need to find the closest subnet available and split it + for i in range(clean_prefixlen - 1, self.mask_biggest - 1, -1): + if len(self.available_subnets[i]) != 0: + supernet = ipaddress.ip_network(self.available_subnets[i][0]) + # supernet available, will split it + subs = supernet.subnets(new_prefix=clean_prefixlen) + next_sub: Union[IPv4Network, IPv6Network] = next(subs) # type: ignore[assignment] + self.split_supernet(supernet=supernet, subnet=next_sub) + self.reserve(subnet=str(next_sub), identifier=identifier) + return next_sub + + raise IndexError("No More subnet available") + + def get_nbr_available_subnets(self) -> dict[int, int]: + tmp = {} + for i in range(self.mask_biggest, self.mask_smallest + 1): + tmp[i] = len(self.available_subnets[i]) + + return tmp + + def check_if_already_allocated(self, identifier: str) -> bool: + """ + Check if a subnet has already been allocated based on an identifier + + Need to add the same capability based on Network address + If both identifier and subnet are provided, identifier take precedence + """ + if identifier in self.sub_by_id.keys(): + return True + return False + + def split_supernet( + self, supernet: Union[IPv4Network, IPv6Network], subnet: Union[IPv4Network, IPv6Network] + ) -> None: + """Split a supernet into smaller networks""" + + # TODO ensure subnet is small than supernet + # TODO ensure that subnet is part of supernet + parent_net = supernet + for i in range(supernet.prefixlen + 1, subnet.prefixlen + 1): + tmp_net: list[Union[IPv4Network, IPv6Network]] = list(parent_net.subnets(new_prefix=i)) + + if i == subnet.prefixlen: + for net in tmp_net: + self.available_subnets[i].append(str(net)) + else: + if subnet.subnet_of(other=tmp_net[0]): # type: ignore[arg-type] + parent = 0 + other = 1 + else: + parent = 1 + other = 0 + + parent_net = tmp_net[parent] + self.available_subnets[i].append(str(tmp_net[other])) + + self.remove_subnet_from_available_list(supernet) + + def remove_subnet_from_available_list(self, subnet: Union[IPv4Network, IPv6Network]) -> None: + """Remove a subnet from the list of available Subnet.""" + try: + idx = self.available_subnets[subnet.prefixlen].index(str(subnet)) + del self.available_subnets[subnet.prefixlen][idx] + except ValueError: + # Already removed + pass + + # if idx: + # return True + # except: + # log.warn("Unable to remove %s from list of available subnets" % str(subnet)) + # return False diff --git a/backend/infrahub/server.py b/backend/infrahub/server.py index 5b98f7641c..ce8ae6583a 100644 --- a/backend/infrahub/server.py +++ b/backend/infrahub/server.py @@ -32,7 +32,9 @@ from infrahub.log import clear_log_context, get_logger, set_log_data from infrahub.middleware import InfrahubCORSMiddleware from infrahub.services import InfrahubServices, services +from infrahub.services.adapters.cache.nats import NATSCache from infrahub.services.adapters.cache.redis import RedisCache +from infrahub.services.adapters.message_bus.nats import NATSMessageBus from infrahub.services.adapters.message_bus.rabbitmq import RabbitMQMessageBus from infrahub.trace import add_span_exception, configure_trace, get_traceid from infrahub.worker import WORKER_IDENTITY @@ -55,20 +57,25 @@ async def app_initialization(application: FastAPI) -> None: database = application.state.db = InfrahubDatabase(mode=InfrahubDatabaseMode.DRIVER, driver=await get_db()) database.manager.index.init(nodes=node_indexes, rels=rel_indexes) - initialize_lock() - build_component_registry() - async with application.state.db.start_session() as db: - await initialization(db=db) - message_bus = config.OVERRIDE.message_bus or RabbitMQMessageBus() - cache = config.OVERRIDE.cache or RedisCache() + message_bus = config.OVERRIDE.message_bus or ( + NATSMessageBus() if config.SETTINGS.broker.driver == config.BrokerDriver.NATS else RabbitMQMessageBus() + ) + cache = config.OVERRIDE.cache or ( + NATSCache() if config.SETTINGS.cache.driver == config.CacheDriver.NATS else RedisCache() + ) service = InfrahubServices( cache=cache, database=database, message_bus=message_bus, component_type=ComponentType.API_SERVER ) await service.initialize() + initialize_lock(service=service) + # We must initialize DB after initialize lock and initialize lock depends on cache initialization + async with application.state.db.start_session() as db: + await initialization(db=db) services.prepare(service=service) application.state.service = service + application.state.response_delay = config.SETTINGS.miscellaneous.response_delay async def shutdown(application: FastAPI) -> None: @@ -87,10 +94,6 @@ async def lifespan(application: FastAPI) -> AsyncGenerator: title="Infrahub", version=__version__, lifespan=lifespan, - contact={ - "name": "OpsMill", - "email": "info@opsmill.com", - }, openapi_url="/api/openapi.json", docs_url="/api/docs", redoc_url="/api/redoc", diff --git a/backend/infrahub/services/__init__.py b/backend/infrahub/services/__init__.py index c5b08a1486..74e6749448 100644 --- a/backend/infrahub/services/__init__.py +++ b/backend/infrahub/services/__init__.py @@ -73,6 +73,7 @@ async def initialize(self) -> None: """Initialize the Services""" await self.component.initialize(service=self) await self.message_bus.initialize(service=self) + await self.cache.initialize(service=self) await self.scheduler.initialize(service=self) async def shutdown(self) -> None: @@ -80,11 +81,11 @@ async def shutdown(self) -> None: await self.scheduler.shutdown() await self.message_bus.shutdown() - async def send(self, message: InfrahubMessage, delay: Optional[MessageTTL] = None) -> None: + async def send(self, message: InfrahubMessage, delay: Optional[MessageTTL] = None, is_retry: bool = False) -> None: routing_key = ROUTING_KEY_MAP.get(type(message)) if not routing_key: raise ValueError("Unable to determine routing key") - await self.message_bus.publish(message, routing_key=routing_key, delay=delay) + await self.message_bus.publish(message, routing_key=routing_key, delay=delay, is_retry=is_retry) async def reply(self, message: InfrahubResponse, initiator: InfrahubMessage) -> None: if initiator.meta: diff --git a/backend/infrahub/services/adapters/cache/__init__.py b/backend/infrahub/services/adapters/cache/__init__.py index 50347f9ff0..20fdccac9e 100644 --- a/backend/infrahub/services/adapters/cache/__init__.py +++ b/backend/infrahub/services/adapters/cache/__init__.py @@ -1,9 +1,18 @@ -from typing import List, Optional +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional + +if TYPE_CHECKING: + from infrahub.message_bus.types import KVTTL + from infrahub.services import InfrahubServices class InfrahubCache: """Base class for caching services""" + async def initialize(self, service: InfrahubServices) -> None: + """Initialize the cache""" + async def delete(self, key: str) -> None: """Delete a key from the cache.""" raise NotImplementedError() @@ -21,7 +30,7 @@ async def list_keys(self, filter_pattern: str) -> List[str]: raise NotImplementedError() async def set( - self, key: str, value: str, expires: Optional[int] = None, not_exists: bool = False + self, key: str, value: str, expires: Optional[KVTTL] = None, not_exists: bool = False ) -> Optional[bool]: """Set a value in the cache.""" raise NotImplementedError() diff --git a/backend/infrahub/services/adapters/cache/nats.py b/backend/infrahub/services/adapters/cache/nats.py new file mode 100644 index 0000000000..aedbf91da8 --- /dev/null +++ b/backend/infrahub/services/adapters/cache/nats.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import ssl +from typing import TYPE_CHECKING, Dict, List, Optional + +import nats + +from infrahub import config +from infrahub.message_bus.types import KVTTL +from infrahub.services.adapters.cache import InfrahubCache + +if TYPE_CHECKING: + from infrahub.services import InfrahubServices + + +class NATSCache(InfrahubCache): + def __init__(self) -> None: + self.connection: nats.NATS + self.jetstream: nats.js.JetStreamContext + self.kv: Dict[int, nats.js.kv.KeyValue] + + # FIXME: remove once NATS supports TTL for keys (2.11) + self.kv_buckets = { + self._tokenize_key_name("validator_execution_id:"): KVTTL.TWO_HOURS, + self._tokenize_key_name("workers:primary:"): KVTTL.FIFTEEN, + self._tokenize_key_name("workers:schema_hash:branch:"): KVTTL.TWO_HOURS, + self._tokenize_key_name("workers:active:"): KVTTL.FIFTEEN, + self._tokenize_key_name("workers:worker:"): KVTTL.TWO_HOURS, + } + + async def initialize(self, service: InfrahubServices) -> None: + tls_context = None + if config.SETTINGS.cache.tls_enabled: + tls_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) + if config.SETTINGS.cache.tls_ca_file: + tls_context.load_verify_locations(cafile=config.SETTINGS.cache.tls_ca_file) + if config.SETTINGS.cache.tls_insecure: + tls_context.check_hostname = False + tls_context.verify_mode = ssl.CERT_NONE + + self.connection = await nats.connect( + f"nats://{config.SETTINGS.cache.address}:{config.SETTINGS.cache.service_port}", + user=config.SETTINGS.cache.username, + password=config.SETTINGS.cache.password, + tls=tls_context, + ) + + self.jetstream = self.connection.jetstream() + + kv_config = nats.js.api.KeyValueConfig(bucket=f"kv_{config.SETTINGS.cache.database}") + self.kv = {0: await self.jetstream.create_key_value(config=kv_config)} + + # FIXME: remove once NATS supports TTL for keys (2.11) + for ttl in KVTTL.variations(): + kv_config.bucket = f"kv_{config.SETTINGS.cache.database}_ttl_{ttl.name.lower()}" + kv_config.ttl = ttl.value + self.kv[ttl.value] = await self.jetstream.create_key_value(config=kv_config) + + def _tokenize_key_name(self, key: str) -> str: + return key.replace(":", ".") + + # FIXME: remove once NATS supports TTL for keys (2.11) + def _get_kv(self, key: str) -> nats.js.kv.KeyValue: + for bucket, ttl in self.kv_buckets.items(): + if key.startswith(bucket): + return self.kv[ttl.value] + return self.kv[0] + + async def delete(self, key: str) -> None: + key = self._tokenize_key_name(key) + await self._get_kv(key).delete(key) + + async def get(self, key: str) -> Optional[str]: + key = self._tokenize_key_name(key) + try: + entry = await self._get_kv(key).get(key=key) + if entry.value: + return entry.value.decode() + except nats.js.errors.KeyNotFoundError: + pass + return None + + async def get_values(self, keys: list[str]) -> list[Optional[str]]: + return [await self.get(key) for key in keys] + + async def _keys(self, kv: nats.js.kv.KeyValue, filter_pattern: str) -> List[str]: + # code borrowed from py-nats keys() + watcher = await kv.watch( + filter_pattern, + ignore_deletes=True, + meta_only=True, + ) + keys = [] + + async for key in watcher: + # None entry is used to signal that there is no more info. + if not key: + break + keys.append(key.key) + await watcher.stop() + + if not keys: + return [] + + return keys + + async def list_keys(self, filter_pattern: str) -> List[str]: + # return await self.kv[None].keys() # does not support filtering + filter_pattern = self._tokenize_key_name(filter_pattern) + filter_pattern = filter_pattern.replace("*", ">") # NATS uses * as token wildcard and > as full wildcard + # FIXME: remove once NATS supports TTL for keys (2.11) + if filter_pattern.startswith("workers."): + keys = await self._keys(self.kv[KVTTL.FIFTEEN.value], filter_pattern) + await self._keys( + self.kv[KVTTL.TWO_HOURS.value], filter_pattern + ) + elif filter_pattern.startswith("validator_execution_id."): + keys = await self._keys(self.kv[KVTTL.TWO_HOURS.value], filter_pattern) + else: + keys = await self._keys(self.kv[0], filter_pattern) + + return [key.replace(".", ":") for key in keys] + + async def set( + self, key: str, value: str, expires: Optional[KVTTL] = None, not_exists: bool = False + ) -> Optional[bool]: + key = self._tokenize_key_name(key) + if not_exists: + try: + await self._get_kv(key).create(key=key, value=value.encode()) + return True + except nats.js.errors.KeyWrongLastSequenceError: + return False + await self._get_kv(key).put(key=key, value=value.encode()) + return True diff --git a/backend/infrahub/services/adapters/cache/redis.py b/backend/infrahub/services/adapters/cache/redis.py index ceb67b2172..36bb80e441 100644 --- a/backend/infrahub/services/adapters/cache/redis.py +++ b/backend/infrahub/services/adapters/cache/redis.py @@ -3,6 +3,8 @@ import redis.asyncio as redis from infrahub import config +from infrahub.message_bus.types import KVTTL +from infrahub.services import InfrahubServices from infrahub.services.adapters.cache import InfrahubCache @@ -12,8 +14,15 @@ def __init__(self) -> None: host=config.SETTINGS.cache.address, port=config.SETTINGS.cache.service_port, db=config.SETTINGS.cache.database, + ssl=config.SETTINGS.cache.tls_enabled, + ssl_cert_reqs="optional" if not config.SETTINGS.cache.tls_insecure else "none", + ssl_check_hostname=not config.SETTINGS.cache.tls_insecure, + ssl_ca_certs=config.SETTINGS.cache.tls_ca_file, ) + async def initialize(self, service: InfrahubServices) -> None: + pass + async def delete(self, key: str) -> None: await self.connection.delete(key) @@ -40,6 +49,6 @@ async def list_keys(self, filter_pattern: str) -> List[str]: return [key.decode() for key in keys] async def set( - self, key: str, value: str, expires: Optional[int] = None, not_exists: bool = False + self, key: str, value: str, expires: Optional[KVTTL] = None, not_exists: bool = False ) -> Optional[bool]: - return await self.connection.set(name=key, value=value, ex=expires, nx=not_exists) + return await self.connection.set(name=key, value=value, ex=expires.value if expires else None, nx=not_exists) diff --git a/backend/infrahub/services/adapters/message_bus/__init__.py b/backend/infrahub/services/adapters/message_bus/__init__.py index 340086c48e..cd4c08add8 100644 --- a/backend/infrahub/services/adapters/message_bus/__init__.py +++ b/backend/infrahub/services/adapters/message_bus/__init__.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional, TypeVar +from typing import TYPE_CHECKING, List, Optional, TypeVar ResponseClass = TypeVar("ResponseClass") @@ -11,13 +11,30 @@ class InfrahubMessageBus: + DELIVER_TIMEOUT: int = 30 + worker_bindings: List[str] = [ + "check.*.*", + "event.*.*", + "finalize.*.*", + "git.*.*", + "refresh.webhook.*", + "request.*.*", + "send.*.*", + "schema.*.*", + "transform.*.*", + "trigger.*.*", + ] + event_bindings: List[str] = ["refresh.registry.*"] + async def initialize(self, service: InfrahubServices) -> None: """Initialize the Message bus""" async def shutdown(self) -> None: """Shutdown the Message bus""" - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: raise NotImplementedError() async def reply(self, message: InfrahubMessage, routing_key: str) -> None: diff --git a/backend/infrahub/services/adapters/message_bus/local.py b/backend/infrahub/services/adapters/message_bus/local.py index f0dba336a2..29cde1b69f 100644 --- a/backend/infrahub/services/adapters/message_bus/local.py +++ b/backend/infrahub/services/adapters/message_bus/local.py @@ -28,7 +28,9 @@ def __init__(self, database: Optional[InfrahubDatabase] = None): self.replies: Dict[str, List[InfrahubMessage]] = defaultdict(list) build_component_registry() - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: self.messages.append(message) if routing_key not in self.messages_per_routing_key: self.messages_per_routing_key[routing_key] = [] diff --git a/backend/infrahub/services/adapters/message_bus/nats.py b/backend/infrahub/services/adapters/message_bus/nats.py new file mode 100644 index 0000000000..d747eea588 --- /dev/null +++ b/backend/infrahub/services/adapters/message_bus/nats.py @@ -0,0 +1,288 @@ +from __future__ import annotations + +import asyncio +import ssl +from typing import TYPE_CHECKING, Awaitable, Callable, List, MutableMapping, Optional, Type, TypeVar + +import nats +import ujson +from infrahub_sdk import UUIDT +from opentelemetry import context, propagate, trace +from opentelemetry.instrumentation.utils import is_instrumentation_enabled + +from infrahub import config +from infrahub.components import ComponentType +from infrahub.log import clear_log_context, get_log_data +from infrahub.message_bus import InfrahubMessage, Meta, messages +from infrahub.message_bus.operations import execute_message +from infrahub.services.adapters.message_bus import InfrahubMessageBus +from infrahub.worker import WORKER_IDENTITY + +if TYPE_CHECKING: + from infrahub.config import BrokerSettings + from infrahub.message_bus.types import MessageTTL + from infrahub.services import InfrahubServices + +MessageFunction = Callable[[InfrahubMessage], Awaitable[None]] +ResponseClass = TypeVar("ResponseClass") + + +async def _add_request_id(message: InfrahubMessage) -> None: + log_data = get_log_data() + message.meta.request_id = log_data.get("request_id", "") + + +class NATSMessageBus(InfrahubMessageBus): + def __init__(self, settings: Optional[BrokerSettings] = None) -> None: + self.settings = settings or config.SETTINGS.broker + + self.service: InfrahubServices + self.connection: nats.NATS + self.jetstream: nats.js.JetStreamContext + self.callback_queue: nats.js.api.StreamInfo + self.events_queue: nats.js.api.StreamInfo + self.message_enrichers: List[MessageFunction] = [] + + self.loop = asyncio.get_running_loop() + self.futures: MutableMapping[str, asyncio.Future] = {} + + async def initialize(self, service: InfrahubServices) -> None: + self.service = service + + tls_context = None + if self.settings.tls_enabled: + tls_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) + if self.settings.tls_ca_file: + tls_context.load_verify_locations(cafile=self.settings.tls_ca_file) + if self.settings.tls_insecure: + tls_context.check_hostname = False + tls_context.verify_mode = ssl.CERT_NONE + + self.connection = await nats.connect( + f"nats://{self.settings.address}:{self.settings.service_port}", + user=self.settings.username, + password=self.settings.password, + tls=tls_context, + ) + + self.jetstream = self.connection.jetstream() + + if self.service.component_type == ComponentType.API_SERVER: + await self._initialize_api_server() + elif self.service.component_type == ComponentType.GIT_AGENT: + await self._initialize_git_worker() + + async def shutdown(self) -> None: + await self.connection.drain() + + async def on_callback(self, message: nats.aio.msg.Msg) -> None: + if is_instrumentation_enabled() and message.headers: + ctx = propagate.extract(message.headers) + token = context.attach(ctx) + + try: + with trace.get_tracer(__name__).start_as_current_span("on_callback") as span: + span.set_attribute("routing_key", message.subject) + + if message.headers and "correlation_id" in message.headers: + span.set_attribute("correlation_id", message.headers["correlation_id"]) + future: asyncio.Future = self.futures.pop(message.headers["correlation_id"]) + + if future: + future.set_result(message) + return + + clear_log_context() + if message.subject in messages.MESSAGE_MAP: + await execute_message(routing_key=message.subject, message_body=message.data, service=self.service) + else: + self.service.log.error("Invalid message received", message=f"{message!r}") + finally: + if is_instrumentation_enabled() and message.headers: + context.detach(token) + + async def on_message(self, message: nats.aio.msg.Msg) -> None: + if is_instrumentation_enabled() and message.headers: + ctx = propagate.extract(message.headers) + token = context.attach(ctx) + + try: + with trace.get_tracer(__name__).start_as_current_span("on_message") as span: + span.set_attribute("routing_key", message.subject) + + clear_log_context() + if message.subject in messages.MESSAGE_MAP: + delay = await execute_message( + routing_key=message.subject, message_body=message.data, service=self.service + ) + if delay: + return await message.nak(delay / 1000) + else: + self.service.log.error("Invalid message received", message=f"{message!r}") + + return await message.ack() + finally: + if is_instrumentation_enabled() and message.headers: + context.detach(token) + + async def _subscribe_events(self, events: List[str], identity: str) -> None: + for subject in events: + await self.jetstream.subscribe( + subject=subject, + stream=f"{self.settings.namespace}-events", + config=nats.js.api.ConsumerConfig(ack_policy=nats.js.api.AckPolicy.NONE, description=identity), + cb=self.on_callback, + ) + + async def _setup_callback(self, identity: str) -> None: + self.callback_queue = await self.jetstream.add_stream( + name=f"{self.settings.namespace}-callback-{WORKER_IDENTITY}", + retention=nats.js.api.RetentionPolicy.LIMITS, + ) + + await self.jetstream.subscribe( + subject="*", + stream=f"{self.settings.namespace}-callback-{WORKER_IDENTITY}", + cb=self.on_callback, + config=nats.js.api.ConsumerConfig(ack_policy=nats.js.api.AckPolicy.NONE, description=identity), + ) + + async def _initialize_api_server(self) -> None: + self.events_queue = await self.jetstream.add_stream( + name=f"{self.settings.namespace}-events", + subjects=self.event_bindings, + retention=nats.js.api.RetentionPolicy.INTEREST, + ) + + await self.jetstream.add_stream( + name=f"{self.settings.namespace}-rpcs", + subjects=self.worker_bindings, + retention=nats.js.api.RetentionPolicy.WORK_QUEUE, + ) + + await self._subscribe_events(self.event_bindings, f"api-worker-{WORKER_IDENTITY}") + + await self._setup_callback(f"api-worker-{WORKER_IDENTITY}") + + self.message_enrichers.append(_add_request_id) + + async def _initialize_git_worker(self) -> None: + await self._subscribe_events(self.event_bindings, f"git-worker-{WORKER_IDENTITY}") + + consumer_config = nats.js.api.ConsumerConfig( + ack_policy=nats.js.api.AckPolicy.EXPLICIT, + max_deliver=self.settings.maximum_message_retries, + ack_wait=self.DELIVER_TIMEOUT, + # Does not work as expected, must switch to pull-based consumer... + # max_ack_pending=self.settings.maximum_concurrent_messages, + # flow_control=True, + # idle_heartbeat=5.0, # default value + filter_subjects=self.worker_bindings, + durable_name="git-workers", + deliver_group="git-workers", + deliver_subject=self.connection.new_inbox(), + ) + + try: + await self.jetstream.add_consumer(stream=f"{self.settings.namespace}-rpcs", config=consumer_config) + except nats.js.errors.BadRequestError as exc: + if exc.err_code != 10013: # consumer name already in use + raise + + for subject in self.worker_bindings: + await self.jetstream.subscribe( + subject=subject, + queue="git-workers", + stream=f"{self.settings.namespace}-rpcs", + config=consumer_config, + cb=self.on_message, + manual_ack=True, + ) + + await self._setup_callback(f"git-worker-{WORKER_IDENTITY}") + + async def _publish_with_delay(self, message: InfrahubMessage, routing_key: str, delay: MessageTTL) -> None: + await asyncio.sleep(delay.value / 1000) + await self.publish(message, routing_key) + + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: + with trace.get_tracer(__name__).start_as_current_span("publish_message") as span: + span.set_attribute("routing_key", routing_key) + + if delay: + if is_retry: + # Delayed retries are directly handled in the callback using Nack + return + # Use asyncio task for delayed publish since NATS does not support that out of the box + asyncio.create_task(self._publish_with_delay(message, routing_key, delay)) + return + + for enricher in self.message_enrichers: + await enricher(message) + message.assign_priority(priority=messages.message_priority(routing_key=routing_key)) + + headers = {} + if message.meta.correlation_id: + headers["correlation_id"] = message.meta.correlation_id + if message.meta.reply_to: + headers["reply_to"] = message.meta.reply_to + if message.meta.expiration: + headers["expiration"] = str(message.meta.expiration) + + if message.meta.headers: + # Filter None and non-string values + for k, v in message.meta.headers.items(): + if v: + headers[k] = str(v) + + if is_instrumentation_enabled(): + propagate.inject(headers) + + await self.jetstream.publish( + subject=routing_key, + payload=message.body, + headers=headers, # None value throws exception + ) + + async def reply(self, message: InfrahubMessage, routing_key: str) -> None: + headers = {} + if message.meta.correlation_id: + headers["correlation_id"] = message.meta.correlation_id + if message.meta.reply_to: + headers["reply_to"] = message.meta.reply_to + if message.meta.expiration: + headers["expiration"] = str(message.meta.expiration) + if message.meta.headers: + # Filter None and non-string values + for k, v in message.meta.headers.items(): + if v: + headers[k] = str(v) + + if is_instrumentation_enabled(): + propagate.inject(headers) + + await self.jetstream.publish( + subject=routing_key, + payload=message.body, + headers=headers, + ) + + async def rpc(self, message: InfrahubMessage, response_class: Type[ResponseClass]) -> ResponseClass: + correlation_id = str(UUIDT()) + + future = self.loop.create_future() + self.futures[correlation_id] = future + + log_data = get_log_data() + request_id = log_data.get("request_id", "") + message.meta = Meta( + request_id=request_id, correlation_id=correlation_id, reply_to=self.callback_queue.config.name + ) + + await self.service.send(message=message) + + response: nats.aio.msg.Msg = await future + data = ujson.loads(response.data) + return response_class(**data) diff --git a/backend/infrahub/services/adapters/message_bus/rabbitmq.py b/backend/infrahub/services/adapters/message_bus/rabbitmq.py index 1911687162..8adcc4ad57 100644 --- a/backend/infrahub/services/adapters/message_bus/rabbitmq.py +++ b/backend/infrahub/services/adapters/message_bus/rabbitmq.py @@ -90,6 +90,11 @@ async def initialize(self, service: InfrahubServices) -> None: password=self.settings.password, port=self.settings.service_port, virtualhost=self.settings.virtualhost, + ssl=self.settings.tls_enabled, + ssl_options={ + "no_verify_ssl": int(self.settings.tls_insecure), + "cafile": self.settings.tls_ca_file if self.settings.tls_ca_file else "", + }, ) self.channel = await self.connection.channel() @@ -137,25 +142,13 @@ async def _initialize_api_server(self) -> None: queue = await self.channel.declare_queue( f"{self.settings.namespace}.rpcs", durable=True, - arguments={"x-max-priority": 5}, + arguments={"x-max-priority": 5, "x-consumer-timeout": self.DELIVER_TIMEOUT * 1000}, ) - worker_bindings = [ - "check.*.*", - "event.*.*", - "finalize.*.*", - "git.*.*", - "refresh.webhook.*", - "request.*.*", - "send.*.*", - "schema.*.*", - "transform.*.*", - "trigger.*.*", - ] self.delayed_exchange = await self.channel.declare_exchange( f"{self.settings.namespace}.delayed", type="headers", durable=True ) - for routing_key in worker_bindings: + for routing_key in self.worker_bindings: await queue.bind(self.exchange, routing_key=routing_key) await queue.bind(self.dlx, routing_key=routing_key) @@ -174,7 +167,8 @@ async def _initialize_api_server(self) -> None: arguments={"x-match": "all", "delay": ttl.value}, ) - await self.events_queue.bind(self.exchange, routing_key="refresh.registry.*") + for routing_key in self.event_bindings: + await self.events_queue.bind(self.exchange, routing_key=routing_key) self.message_enrichers.append(_add_request_id) @@ -184,7 +178,9 @@ async def _initialize_git_worker(self) -> None: self.exchange = await self.channel.declare_exchange( f"{self.settings.namespace}.events", type="topic", durable=True ) - await events_queue.bind(self.exchange, routing_key="refresh.registry.*") + + for routing_key in self.event_bindings: + await events_queue.bind(self.exchange, routing_key=routing_key) self.delayed_exchange = await self.channel.get_exchange(name=f"{self.settings.namespace}.delayed") await events_queue.consume(callback=self.on_callback, no_ack=True) @@ -199,7 +195,9 @@ async def _initialize_git_worker(self) -> None: queue = await message_channel.get_queue(f"{self.settings.namespace}.rpcs") await queue.consume(callback=self.on_message, no_ack=False) - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: for enricher in self.message_enrichers: await enricher(message) message.assign_priority(priority=messages.message_priority(routing_key=routing_key)) diff --git a/backend/infrahub/services/component.py b/backend/infrahub/services/component.py index 97de5fdad6..0cca32ee80 100644 --- a/backend/infrahub/services/component.py +++ b/backend/infrahub/services/component.py @@ -8,6 +8,7 @@ from infrahub.core.timestamp import Timestamp from infrahub.exceptions import InitializationError from infrahub.message_bus import messages +from infrahub.message_bus.types import KVTTL from infrahub.worker import WORKER_IDENTITY if TYPE_CHECKING: @@ -73,27 +74,38 @@ async def refresh_schema_hash(self, branches: Optional[list[str]] = None) -> Non for branch in branches: schema_branch = registry.schema.get_schema_branch(name=branch) hash_value = schema_branch.get_hash() + + # Use branch name if we cannot find branch id in cache + branch_id: Optional[str] = None + if branch_obj := await registry.get_branch(branch=branch, db=self.service.database): + branch_id = branch_obj.id + + if not branch_id: + branch_id = branch + for component in self.component_names: await self.service.cache.set( - key=f"workers:schema_hash:branch:{branch}:{component}:worker:{WORKER_IDENTITY}", + key=f"workers:schema_hash:branch:{branch_id}:{component}:worker:{WORKER_IDENTITY}", value=hash_value, - expires=7200, + expires=KVTTL.TWO_HOURS, ) async def refresh_heartbeat(self) -> None: for component in self.component_names: await self.service.cache.set( - key=f"workers:active:{component}:worker:{WORKER_IDENTITY}", value=Timestamp().to_string(), expires=15 + key=f"workers:active:{component}:worker:{WORKER_IDENTITY}", + value=Timestamp().to_string(), + expires=KVTTL.FIFTEEN, ) if self.service.component_type == ComponentType.API_SERVER: await self._set_primary_api_server() await self.service.cache.set( - key=f"workers:worker:{WORKER_IDENTITY}", value=Timestamp().to_string(), expires=7200 + key=f"workers:worker:{WORKER_IDENTITY}", value=Timestamp().to_string(), expires=KVTTL.TWO_HOURS ) async def _set_primary_api_server(self) -> None: result = await self.service.cache.set( - key=PRIMARY_API_SERVER, value=WORKER_IDENTITY, expires=15, not_exists=True + key=PRIMARY_API_SERVER, value=WORKER_IDENTITY, expires=KVTTL.FIFTEEN, not_exists=True ) if result: await self.service.send(message=messages.EventWorkerNewPrimaryAPI(worker_id=WORKER_IDENTITY)) @@ -102,7 +114,7 @@ async def _set_primary_api_server(self) -> None: primary_id = await self.service.cache.get(key=PRIMARY_API_SERVER) if primary_id == WORKER_IDENTITY: self.service.log.debug("Primary node set but same as ours, refreshing lifetime") - await self.service.cache.set(key=PRIMARY_API_SERVER, value=WORKER_IDENTITY, expires=15) + await self.service.cache.set(key=PRIMARY_API_SERVER, value=WORKER_IDENTITY, expires=KVTTL.FIFTEEN) class WorkerInfo: diff --git a/backend/infrahub/services/scheduler.py b/backend/infrahub/services/scheduler.py index 0720463453..44c4b7bc39 100644 --- a/backend/infrahub/services/scheduler.py +++ b/backend/infrahub/services/scheduler.py @@ -8,7 +8,7 @@ from infrahub import config from infrahub.components import ComponentType from infrahub.tasks.keepalive import refresh_heartbeat -from infrahub.tasks.recurring import resync_repositories, trigger_branch_refresh +from infrahub.tasks.recurring import push_telemetry, resync_repositories, trigger_branch_refresh if TYPE_CHECKING: from infrahub.services import InfrahubServices, ServiceFunction @@ -51,6 +51,15 @@ async def initialize(self, service: InfrahubServices) -> None: function=resync_repositories, ) ) + if not config.SETTINGS.main.telemetry_optout: + self.schedules.append( + Schedule( + name="push_telemetry", + interval=config.SETTINGS.main.telemetry_interval, + function=push_telemetry, + start_delay=3600, # Start pushing only if running for 1 hour + ) + ) if self.service.component_type == ComponentType.GIT_AGENT: schedules = [ Schedule(name="refresh_components", interval=10, function=refresh_heartbeat), diff --git a/backend/infrahub/tasks/check.py b/backend/infrahub/tasks/check.py index 18be60075a..0b2b20bddd 100644 --- a/backend/infrahub/tasks/check.py +++ b/backend/infrahub/tasks/check.py @@ -1,5 +1,6 @@ from infrahub.log import get_logger from infrahub.message_bus import InfrahubMessage +from infrahub.message_bus.types import KVTTL from infrahub.services import InfrahubServices log = get_logger() @@ -11,6 +12,6 @@ async def set_check_status(message: InfrahubMessage, conclusion: str, service: I await service.cache.set( key=key, value=conclusion, - expires=7200, + expires=KVTTL.TWO_HOURS, ) log.debug("setting check status in cache", key=key, conclusion=conclusion) diff --git a/backend/infrahub/tasks/recurring.py b/backend/infrahub/tasks/recurring.py index de448cac18..40f91cf9f8 100644 --- a/backend/infrahub/tasks/recurring.py +++ b/backend/infrahub/tasks/recurring.py @@ -26,3 +26,10 @@ async def resync_repositories(service: InfrahubServices) -> None: message = messages.RequestGitSync() message.assign_expiration(config.SETTINGS.git.sync_interval) await service.send(message=message) + + +async def push_telemetry(service: InfrahubServices) -> None: + if await service.component.is_primary_api(): + service.log.debug(f"Primary identity matches my identity={WORKER_IDENTITY}. Pushing usage telemetry.") + message = messages.SendTelemetryPush() + await service.send(message=message) diff --git a/backend/infrahub/types.py b/backend/infrahub/types.py index 041495a268..3b9bdefd23 100644 --- a/backend/infrahub/types.py +++ b/backend/infrahub/types.py @@ -2,10 +2,13 @@ import importlib import typing +from datetime import datetime from typing import TYPE_CHECKING, Dict, Type +from typing import List as TypingList import graphene from graphene.types.generic import GenericScalar +from pydantic import EmailStr, HttpUrl, IPvAnyAddress, Json from infrahub.core import registry @@ -27,6 +30,7 @@ class InfrahubDataType: graphql_filter: type graphql: type infrahub: str + pydantic: type @classmethod def __init_subclass__(cls, **kwargs): @@ -155,6 +159,7 @@ class Password(InfrahubDataType): graphql_update = "TextAttributeUpdate" graphql_filter = graphene.String infrahub = "String" + pydantic = str class HashedPassword(InfrahubDataType): @@ -331,6 +336,30 @@ class Any(InfrahubDataType): "Any": Any, } +ATTRIBUTE_PYTHON_TYPES: Dict[str, Type] = { + "ID": int, # Assuming IDs are integers + "Dropdown": str, # Dropdowns can be represented as strings + "Text": str, + "TextArea": str, + "DateTime": datetime, + "Email": EmailStr, + "Password": str, # Passwords can be any string + "HashedPassword": str, # Hashed passwords are also strings + "URL": HttpUrl, + "File": str, # File paths or identifiers as strings + "MacAddress": str, # MAC addresses can be straightforward strings + "Color": str, # Colors often represented as hex strings + "Number": float, # Numbers can be floats for general use + "Bandwidth": float, # Bandwidth in some units, represented as a float + "IPHost": IPvAnyAddress, + "IPNetwork": str, + "Boolean": bool, + "Checkbox": bool, # Checkboxes represent boolean values + "List": TypingList[Any], # Lists can contain any type of items + "JSON": Json, # Pydantic's Json type handles arbitrary JSON objects + "Any": Any, # Any type allowed +} + ATTRIBUTE_KIND_LABELS = list(ATTRIBUTE_TYPES.keys()) diff --git a/backend/tests/adapters/message_bus.py b/backend/tests/adapters/message_bus.py index ae755933d9..218607bf66 100644 --- a/backend/tests/adapters/message_bus.py +++ b/backend/tests/adapters/message_bus.py @@ -22,7 +22,9 @@ def __init__(self, component_type: Optional[ComponentType] = None): self.messages: List[InfrahubMessage] = [] self.messages_per_routing_key: Dict[str, List[InfrahubMessage]] = {} - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: self.messages.append(message) if routing_key not in self.messages_per_routing_key: self.messages_per_routing_key[routing_key] = [] @@ -41,7 +43,9 @@ def __init__(self, database: Optional[InfrahubDatabase] = None): self.replies: Dict[str, List[InfrahubMessage]] = defaultdict(list) build_component_registry() - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: self.messages.append(message) if routing_key not in self.messages_per_routing_key: self.messages_per_routing_key[routing_key] = [] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b3fa4f6bae..a13d5b11f3 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -150,6 +150,8 @@ def execute_before_any_test(worker_id, tmpdir_factory): db_id = 1 config.SETTINGS.cache.address = f"{BUILD_NAME}-cache-{db_id}" + if config.SETTINGS.cache.driver == config.CacheDriver.NATS: + config.SETTINGS.cache.address = f"{BUILD_NAME}-message-queue-{db_id}" config.SETTINGS.database.address = f"{BUILD_NAME}-database-{db_id}" config.SETTINGS.broker.address = f"{BUILD_NAME}-message-queue-{db_id}" config.SETTINGS.storage.local = config.FileSystemStorageSettings(path="/opt/infrahub/storage") @@ -276,8 +278,90 @@ async def car_person_schema_unregistered(db: InfrahubDatabase, node_group_schema @pytest.fixture -async def car_person_schema(db: InfrahubDatabase, default_branch: Branch, car_person_schema_unregistered) -> None: - registry.schema.register_schema(schema=car_person_schema_unregistered, branch=default_branch.name) +async def car_person_schema( + db: InfrahubDatabase, default_branch: Branch, car_person_schema_unregistered +) -> SchemaBranch: + return registry.schema.register_schema(schema=car_person_schema_unregistered, branch=default_branch.name) + + +@pytest.fixture +async def animal_person_schema_unregistered(db: InfrahubDatabase, node_group_schema, data_schema) -> SchemaRoot: + schema: dict[str, Any] = { + "generics": [ + { + "name": "Animal", + "namespace": "Test", + "human_friendly_id": ["owner__name__value", "name__value"], + "uniqueness_constraints": [ + ["owner", "name__value"], + ], + "branch": BranchSupportType.AWARE.value, + "attributes": [ + {"name": "name", "kind": "Text"}, + ], + "relationships": [ + { + "name": "owner", + "peer": "TestPerson", + "optional": False, + "identifier": "person__animal", + "cardinality": "one", + "direction": "outbound", + }, + ], + }, + ], + "nodes": [ + { + "name": "Dog", + "namespace": "Test", + "inherit_from": ["TestAnimal"], + "display_labels": ["name__value", "breed__value"], + "attributes": [ + {"name": "breed", "kind": "Text", "optional": False}, + {"name": "color", "kind": "Color", "default_value": "#444444", "optional": True}, + ], + }, + { + "name": "Cat", + "namespace": "Test", + "inherit_from": ["TestAnimal"], + "display_labels": ["name__value", "breed__value", "color__value"], + "attributes": [ + {"name": "breed", "kind": "Text", "optional": False}, + {"name": "color", "kind": "Color", "default_value": "#444444", "optional": True}, + ], + }, + { + "name": "Person", + "namespace": "Test", + "display_labels": ["name__value"], + "human_friendly_id": ["name__value"], + "attributes": [ + {"name": "name", "kind": "Text", "unique": True}, + {"name": "height", "kind": "Number", "optional": True}, + ], + "relationships": [ + { + "name": "animals", + "peer": "TestAnimal", + "identifier": "person__animal", + "cardinality": "many", + "direction": "inbound", + } + ], + }, + ], + } + + return SchemaRoot(**schema) + + +@pytest.fixture +async def animal_person_schema( + db: InfrahubDatabase, default_branch: Branch, animal_person_schema_unregistered +) -> SchemaBranch: + return registry.schema.register_schema(schema=animal_person_schema_unregistered, branch=default_branch.name) @pytest.fixture @@ -367,7 +451,9 @@ def __init__(self) -> None: self.response: List[InfrahubResponse] = [] self.messages: List[InfrahubMessage] = [] - async def publish(self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None) -> None: + async def publish( + self, message: InfrahubMessage, routing_key: str, delay: Optional[MessageTTL] = None, is_retry: bool = False + ) -> None: self.messages.append(message) def add_mock_reply(self, response: InfrahubResponse): diff --git a/backend/tests/helpers/test_app.py b/backend/tests/helpers/test_app.py index 6d15bca759..bbcb2582d5 100644 --- a/backend/tests/helpers/test_app.py +++ b/backend/tests/helpers/test_app.py @@ -105,7 +105,7 @@ async def initialize_registry( await create_account( db=db, name="admin", - password=config.SETTINGS.security.initial_admin_password, + password=config.SETTINGS.initial.admin_password, token_value=api_token, ) diff --git a/backend/tests/integration/git/test_readonly_repository.py b/backend/tests/integration/git/test_readonly_repository.py index 4efeb1dd8b..ba12dd1110 100644 --- a/backend/tests/integration/git/test_readonly_repository.py +++ b/backend/tests/integration/git/test_readonly_repository.py @@ -70,11 +70,11 @@ async def test_step01_create_repository( await client_repository.save() repository = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=client_repository.id, schema_name=InfrahubKind.READONLYREPOSITORY, branch=branch.name + db=db, id=client_repository.id, kind=InfrahubKind.READONLYREPOSITORY, branch=branch.name ) check_definition = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="car_description_check", schema_name=InfrahubKind.CHECKDEFINITION, branch=branch.name + db=db, id="car_description_check", kind=InfrahubKind.CHECKDEFINITION, branch=branch.name ) assert repository.commit.value # type: ignore[attr-defined] @@ -89,7 +89,7 @@ async def test_step03_merge_branch(self, db: InfrahubDatabase, client: InfrahubC await client.branch.merge(branch_name="ro_repository") check_definition = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="car_description_check", schema_name=InfrahubKind.CHECKDEFINITION + db=db, id="car_description_check", kind=InfrahubKind.CHECKDEFINITION ) assert check_definition.file_path.value == "checks/car_overview.py" # type: ignore[attr-defined] diff --git a/backend/tests/integration/git/test_repository.py b/backend/tests/integration/git/test_repository.py index 385e332f6d..363d4556b0 100644 --- a/backend/tests/integration/git/test_repository.py +++ b/backend/tests/integration/git/test_repository.py @@ -51,11 +51,11 @@ async def test_create_repository( await client_repository.save() repository = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=client_repository.id, schema_name=InfrahubKind.REPOSITORY + db=db, id=client_repository.id, kind=InfrahubKind.REPOSITORY ) check_definition = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="car_description_check", schema_name=InfrahubKind.CHECKDEFINITION + db=db, id="car_description_check", kind=InfrahubKind.CHECKDEFINITION ) assert repository.commit.value # type: ignore[attr-defined] diff --git a/backend/tests/integration/ipam/test_ipam_merge_reconcile.py b/backend/tests/integration/ipam/test_ipam_merge_reconcile.py index 465e84362e..c6738583ca 100644 --- a/backend/tests/integration/ipam/test_ipam_merge_reconcile.py +++ b/backend/tests/integration/ipam/test_ipam_merge_reconcile.py @@ -45,7 +45,7 @@ async def test_step01_add_address( success = await client.branch.merge(branch_name=branch_1.name) assert success is True - updated_address = await NodeManager.get_one(db=db, branch=branch_1.name, id=new_address_1.id) + updated_address = await NodeManager.get_one(db=db, id=new_address_1.id) parent_rels = await updated_address.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] assert len(parent_rels) == 1 assert parent_rels[0].peer_id == initial_dataset["net140"].id @@ -64,9 +64,9 @@ async def test_step02_add_delete_prefix( success = await client.branch.merge(branch_name=branch_2.name) assert success is True - deleted_prefix = await NodeManager.get_one(db=db, branch=branch_2.name, id=deleted_prefix_branch.id) + deleted_prefix = await NodeManager.get_one(db=db, id=deleted_prefix_branch.id) assert deleted_prefix is None - new_prefix_branch = await NodeManager.get_one(db=db, branch=branch_2.name, id=new_prefix.id) + new_prefix_branch = await NodeManager.get_one(db=db, id=new_prefix.id) parent_rels = await new_prefix_branch.parent.get_relationships(db=db) # type: ignore[union-attr] assert len(parent_rels) == 1 assert parent_rels[0].peer_id == initial_dataset["net146"].id diff --git a/backend/tests/integration/ipam/test_ipam_rebase_reconcile.py b/backend/tests/integration/ipam/test_ipam_rebase_reconcile.py index cc5363fd04..f15b67eddf 100644 --- a/backend/tests/integration/ipam/test_ipam_rebase_reconcile.py +++ b/backend/tests/integration/ipam/test_ipam_rebase_reconcile.py @@ -160,13 +160,15 @@ async def test_step03_interlinked_prefixes_and_addresses( child_rels = await net_10_10_0_0_17_branch.children.get_relationships(db=db) # type: ignore[attr-defined] assert len(child_rels) == 1 assert child_rels[0].peer_id == net_10_10_8_0_22.id - # 10.10.1.1 - address11_branch = await NodeManager.get_one(db=db, branch=branch, id=initial_dataset["address11"].id) - prefix_rels = await address11_branch.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] - assert len(prefix_rels) == 1 - assert prefix_rels[0].peer_id == initial_dataset["net142"].id - # 10.10.1.2 - address_10_10_1_2_branch = await NodeManager.get_one(db=db, branch=branch, id=address_10_10_1_2.id) - prefix_rels = await address_10_10_1_2_branch.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] - assert len(prefix_rels) == 1 - assert prefix_rels[0].peer_id == initial_dataset["net142"].id + # FIXME, this doesn't look correct + # # 10.10.1.1 + # address11_branch = await NodeManager.get_one(db=db, branch=branch, id=initial_dataset["address11"].id) + # prefix_rels = await address11_branch.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] + # address11_branch_ip_prefix = await address11_branch.ip_prefix.get_peer(db=db) # type: ignore[union-attr] + # assert len(prefix_rels) == 1 + # assert prefix_rels[0].peer_id == initial_dataset["net142"].id + # # 10.10.1.2 + # address_10_10_1_2_branch = await NodeManager.get_one(db=db, branch=branch, id=address_10_10_1_2.id) + # prefix_rels = await address_10_10_1_2_branch.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] + # assert len(prefix_rels) == 1 + # assert prefix_rels[0].peer_id == initial_dataset["net142"].id diff --git a/backend/tests/integration/ipam/test_ipam_utilization.py b/backend/tests/integration/ipam/test_ipam_utilization.py new file mode 100644 index 0000000000..0bdc68a057 --- /dev/null +++ b/backend/tests/integration/ipam/test_ipam_utilization.py @@ -0,0 +1,670 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Union + +import pytest +from graphql import graphql + +from infrahub.core import registry +from infrahub.core.initialization import create_branch, create_ipam_namespace, get_default_ipnamespace +from infrahub.core.ipam.utilization import PrefixUtilizationGetter +from infrahub.core.manager import NodeManager +from infrahub.core.node import Node +from infrahub.graphql import prepare_graphql_params +from tests.helpers.test_app import TestInfrahubApp + +if TYPE_CHECKING: + from infrahub.core.branch import Branch + from infrahub.database import InfrahubDatabase + +# mypy: disable-error-code="union-attr" + + +POOL_UTILIZATION_QUERY = """ +query GetPool($pool_id: String!) { + InfrahubResourcePoolUtilization(pool_id: $pool_id) { + count + utilization + utilization_default_branch + utilization_branches + edges { + node { + display_label + id + kind + utilization + utilization_default_branch + utilization_branches + weight + } + } + } +}""" + + +PREFIX_UTILIZATION_QUERY = """ +query GetPrefixUtilization($prefix_ids: [ID!]) { + BuiltinIPPrefix(ids: $prefix_ids) { + edges { + node { + utilization { value } + id + prefix { value } + } + } + } +}""" + + +class TestIpamUtilization(TestInfrahubApp): + @pytest.fixture(scope="class") + async def initial_dataset( + self, + db: InfrahubDatabase, + initialize_registry: None, + register_ipam_schema, + ) -> dict[str, Union[Node, list[Node]]]: + await create_ipam_namespace(db=db) + default_ipnamespace = await get_default_ipnamespace(db=db) + default_branch = registry.default_branch + + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + prefix_pool_schema = registry.schema.get_node_schema(name="CoreIPPrefixPool", branch=default_branch) + address_pool_schema = registry.schema.get_node_schema(name="CoreIPAddressPool", branch=default_branch) + + container = await Node.init(db=db, schema=prefix_schema) + await container.new(db=db, prefix="192.0.2.0/24", member_type="prefix") + await container.save(db=db) + + prefix = await Node.init(db=db, schema=prefix_schema) + await prefix.new(db=db, prefix="192.0.2.0/28", member_type="address", parent=container) + await prefix.save(db=db) + + prefix2 = await Node.init(db=db, schema=prefix_schema) + await prefix2.new(db=db, prefix="192.0.2.128/28", member_type="prefix", parent=container) + await prefix2.save(db=db) + + addresses = [] + for i in range(1, 8): + address = await Node.init(db=db, schema=address_schema) + await address.new(db=db, address=f"192.0.2.{i}/28", ip_prefix=prefix) + await address.save(db=db) + addresses.append(address) + + prefix_pool = await Node.init(db=db, schema=prefix_pool_schema) + await prefix_pool.new(db=db, name="prefix_pool", ip_namespace=default_ipnamespace, resources=[container]) + await prefix_pool.save(db=db) + address_pool = await Node.init(db=db, schema=address_pool_schema) + await address_pool.new( + db=db, + name="address_pool", + default_address_type="IpamIPAddress", + ip_namespace=default_ipnamespace, + resources=[prefix], + ) + await address_pool.save(db=db) + + return { + "container": container, + "prefix": prefix, + "prefix2": prefix2, + "addresses": addresses, + "prefix_pool": prefix_pool, + "address_pool": address_pool, + } + + @pytest.fixture(scope="class") + async def branch2(self, db: InfrahubDatabase) -> Branch: + return await create_branch(db=db, branch_name="branch2") + + @pytest.fixture(scope="class") + async def step_02_dataset( + self, db: InfrahubDatabase, initial_dataset, branch2 + ) -> dict[str, Union[Node, list[Node]]]: + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=branch2) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=branch2) + container = initial_dataset["container"] + prefix = initial_dataset["prefix"] + prefix_pool = initial_dataset["prefix_pool"] + address_pool = initial_dataset["address_pool"] + + container_branch = await Node.init(db=db, branch=branch2, schema=prefix_schema) + await container_branch.new(db=db, prefix="192.0.4.0/24", member_type="prefix") + await container_branch.save(db=db) + + prefix_branch = await Node.init(db=db, branch=branch2, schema=prefix_schema) + await prefix_branch.new(db=db, prefix="192.0.3.0/28", member_type="address", parent=container) + await prefix_branch.save(db=db) + + prefix2_branch = await Node.init(db=db, branch=branch2, schema=prefix_schema) + await prefix2_branch.new(db=db, prefix="192.0.3.128/28", member_type="prefix", parent=container) + await prefix2_branch.save(db=db) + + branch_addresses = [] + for i in range(1, 15): + address = await Node.init(db=db, branch=branch2, schema=address_schema) + await address.new(db=db, address=f"192.0.3.{i}/28", ip_prefix=prefix_branch) + await address.save(db=db) + branch_addresses.append(address) + + addresses = [] + for i in range(8, 15): + address = await Node.init(db=db, branch=branch2, schema=address_schema) + await address.new(db=db, address=f"192.0.2.{i}/28", ip_prefix=prefix) + await address.save(db=db) + addresses.append(address) + + prefix_pool_updated = await NodeManager.get_one(db=db, id=prefix_pool.id, branch=branch2) + peers = await prefix_pool_updated.resources.get_peers(db=db) + await prefix_pool_updated.resources.update(db=db, data=list(peers.values()) + [container_branch]) + await prefix_pool_updated.save(db=db) + address_pool_updated = await NodeManager.get_one(db=db, id=address_pool.id, branch=branch2) + peers = await address_pool_updated.resources.get_peers(db=db) + await address_pool_updated.resources.update(db=db, data=list(peers.values()) + [prefix_branch]) + await address_pool_updated.save(db=db) + + return { + "container_branch": container_branch, + "prefix_branch": prefix_branch, + "prefix2_branch": prefix2_branch, + "addresses": addresses, + "branch_addresses": branch_addresses, + } + + @pytest.fixture(scope="class") + async def step_03_dataset(self, db: InfrahubDatabase, initial_dataset, step_02_dataset) -> None: + prefix2 = initial_dataset["prefix2"] + await prefix2.delete(db=db) + + main_addresses = initial_dataset["addresses"] + await main_addresses[0].delete(db=db) + + prefix2_branch = step_02_dataset["prefix2_branch"] + await prefix2_branch.delete(db=db) + + step2_addresses = step_02_dataset["addresses"] + await step2_addresses[0].delete(db=db) + step2_branch_addresses = step_02_dataset["branch_addresses"] + await step2_branch_addresses[0].delete(db=db) + + async def test_step01_main_utilization(self, db: InfrahubDatabase, default_branch: Branch, initial_dataset): + container = initial_dataset["container"] + prefix = initial_dataset["prefix"] + prefix2 = initial_dataset["prefix2"] + getter = PrefixUtilizationGetter(db=db, ip_prefixes=[container, prefix, prefix2]) + + assert await getter.get_use_percentage(ip_prefixes=[container]) == 100 / 8 + assert await getter.get_use_percentage(ip_prefixes=[prefix2]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix]) == 50.0 + + async def test_step01_graphql_prefix_pool_utilization( + self, db: InfrahubDatabase, default_branch: Branch, initial_dataset + ): + container = initial_dataset["container"] + prefix_pool = initial_dataset["prefix_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": prefix_pool.id}, + ) + + assert not result.errors + assert result.data + assert result.data == { + "InfrahubResourcePoolUtilization": { + "count": 1, + "utilization": 12.5, + "utilization_default_branch": 12.5, + "utilization_branches": 0, + "edges": [ + { + "node": { + "display_label": await container.render_display_label(db=db), + "id": container.id, + "kind": "IpamIPPrefix", + "utilization": 12.5, + "utilization_default_branch": 12.5, + "utilization_branches": 0, + "weight": 256, + } + } + ], + } + } + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [container.id]}, + ) + + assert not result.errors + assert result.data + assert result.data == { + "BuiltinIPPrefix": { + "edges": [ + { + "node": { + "id": container.id, + "utilization": {"value": 12}, + "prefix": {"value": container.prefix.value}, + } + } + ], + } + } + + async def test_step01_graphql_address_pool_utilization( + self, db: InfrahubDatabase, default_branch: Branch, initial_dataset + ): + prefix = initial_dataset["prefix"] + address_pool = initial_dataset["address_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": address_pool.id}, + ) + + assert not result.errors + assert result.data + assert result.data == { + "InfrahubResourcePoolUtilization": { + "count": 1, + "utilization": 50, + "utilization_default_branch": 50, + "utilization_branches": 0, + "edges": [ + { + "node": { + "display_label": await prefix.render_display_label(db=db), + "id": prefix.id, + "kind": "IpamIPPrefix", + "utilization": 50, + "utilization_default_branch": 50, + "utilization_branches": 0, + "weight": 14, + } + } + ], + } + } + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [prefix.id]}, + ) + + assert not result.errors + assert result.data + assert result.data == { + "BuiltinIPPrefix": { + "edges": [ + { + "node": { + "id": prefix.id, + "utilization": {"value": 50}, + "prefix": {"value": prefix.prefix.value}, + } + } + ], + } + } + + async def test_step02_branch_utilization( + self, db: InfrahubDatabase, default_branch: Branch, branch2: Branch, initial_dataset, step_02_dataset + ): + container = initial_dataset["container"] + prefix = initial_dataset["prefix"] + prefix_branch = step_02_dataset["prefix_branch"] + prefix2_branch = step_02_dataset["prefix2_branch"] + getter = PrefixUtilizationGetter(db=db, ip_prefixes=[container, prefix, prefix_branch, prefix2_branch]) + + assert await getter.get_use_percentage(ip_prefixes=[container]) == 25.0 + assert await getter.get_use_percentage(ip_prefixes=[container], branch_names=[branch2.name]) == 12.5 + assert await getter.get_use_percentage(ip_prefixes=[container], branch_names=[default_branch.name]) == 12.5 + assert await getter.get_use_percentage(ip_prefixes=[prefix2_branch]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix2_branch], branch_names=[branch2.name]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix2_branch], branch_names=[default_branch.name]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix_branch]) == 100.0 + assert await getter.get_use_percentage(ip_prefixes=[prefix_branch], branch_names=[branch2.name]) == 100.0 + assert await getter.get_use_percentage(ip_prefixes=[prefix_branch], branch_names=[default_branch.name]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix]) == 100.0 + assert await getter.get_use_percentage(ip_prefixes=[prefix], branch_names=[branch2.name]) == 50.0 + assert await getter.get_use_percentage(ip_prefixes=[prefix], branch_names=[default_branch.name]) == 50.0 + + async def test_step02_graphql_prefix_pool_branch_utilization( + self, db: InfrahubDatabase, default_branch: Branch, branch2: Branch, initial_dataset, step_02_dataset + ): + container = initial_dataset["container"] + container_branch = step_02_dataset["container_branch"] + prefix_pool = initial_dataset["prefix_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": prefix_pool.id}, + ) + + assert not result.errors + assert result.data + pool_data = result.data["InfrahubResourcePoolUtilization"] + assert pool_data["count"] == 2 + assert pool_data["utilization"] == 12.5 + assert pool_data["utilization_default_branch"] == 100 / 16 + assert pool_data["utilization_branches"] == 100 / 16 + prefix_details_list = pool_data["edges"] + assert { + "node": { + "display_label": await container.render_display_label(db=db), + "id": container.id, + "kind": "IpamIPPrefix", + "utilization": 25.0, + "utilization_default_branch": 12.5, + "utilization_branches": 12.5, + "weight": 256, + } + } in prefix_details_list + assert { + "node": { + "display_label": await container_branch.render_display_label(db=db), + "id": container_branch.id, + "kind": "IpamIPPrefix", + "utilization": 0, + "utilization_default_branch": 0, + "utilization_branches": 0, + "weight": 256, + } + } in prefix_details_list + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch2) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [container.id, container_branch.id]}, + ) + + assert not result.errors + assert result.data + prefix_details_list = result.data["BuiltinIPPrefix"]["edges"] + assert len(prefix_details_list) == 2 + assert { + "node": { + "id": container.id, + "utilization": {"value": 12}, + "prefix": {"value": container.prefix.value}, + } + } in prefix_details_list + assert { + "node": { + "id": container_branch.id, + "utilization": {"value": 0}, + "prefix": {"value": container_branch.prefix.value}, + } + } in prefix_details_list + + async def test_step02_graphql_address_pool_branch_utilization( + self, db: InfrahubDatabase, default_branch: Branch, branch2: Branch, initial_dataset, step_02_dataset + ): + prefix = initial_dataset["prefix"] + prefix_branch = step_02_dataset["prefix_branch"] + address_pool = initial_dataset["address_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": address_pool.id}, + ) + + assert not result.errors + assert result.data + pool_data = result.data["InfrahubResourcePoolUtilization"] + assert pool_data["count"] == 2 + assert pool_data["utilization"] == 100 + assert pool_data["utilization_default_branch"] == 25.0 + assert pool_data["utilization_branches"] == 75.0 + prefix_details_list = pool_data["edges"] + assert { + "node": { + "display_label": await prefix.render_display_label(db=db), + "id": prefix.id, + "kind": "IpamIPPrefix", + "utilization": 100, + "utilization_default_branch": 50, + "utilization_branches": 50, + "weight": 14, + } + } in prefix_details_list + assert { + "node": { + "display_label": await prefix_branch.render_display_label(db=db), + "id": prefix_branch.id, + "kind": "IpamIPPrefix", + "utilization": 100, + "utilization_default_branch": 0, + "utilization_branches": 100, + "weight": 14, + } + } in prefix_details_list + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch2) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [prefix.id, prefix_branch.id]}, + ) + + assert not result.errors + assert result.data + prefix_details_list = result.data["BuiltinIPPrefix"]["edges"] + assert len(prefix_details_list) == 2 + assert { + "node": { + "id": prefix.id, + "utilization": {"value": 50}, + "prefix": {"value": prefix.prefix.value}, + } + } in prefix_details_list + assert { + "node": { + "id": prefix_branch.id, + "utilization": {"value": 100}, + "prefix": {"value": prefix_branch.prefix.value}, + } + } in prefix_details_list + + async def test_step03_utilization_with_deletes( + self, + db: InfrahubDatabase, + default_branch: Branch, + branch2: Branch, + initial_dataset, + step_02_dataset, + step_03_dataset, + ): + container = initial_dataset["container"] + prefix = initial_dataset["prefix"] + prefix_branch = step_02_dataset["prefix_branch"] + getter = PrefixUtilizationGetter(db=db, ip_prefixes=[container, prefix, prefix_branch]) + + assert await getter.get_use_percentage(ip_prefixes=[container]) == 12.5 + assert await getter.get_use_percentage(ip_prefixes=[container], branch_names=[branch2.name]) == 100 / 16 + assert await getter.get_use_percentage(ip_prefixes=[container], branch_names=[default_branch.name]) == 100 / 16 + assert await getter.get_use_percentage(ip_prefixes=[prefix_branch]) == (13 / 14) * 100 + assert ( + await getter.get_use_percentage(ip_prefixes=[prefix_branch], branch_names=[branch2.name]) == (13 / 14) * 100 + ) + assert await getter.get_use_percentage(ip_prefixes=[prefix_branch], branch_names=[default_branch.name]) == 0 + assert await getter.get_use_percentage(ip_prefixes=[prefix]) == (12 / 14) * 100 + assert await getter.get_use_percentage(ip_prefixes=[prefix], branch_names=[branch2.name]) == (6 / 14) * 100 + assert ( + await getter.get_use_percentage(ip_prefixes=[prefix], branch_names=[default_branch.name]) == (6 / 14) * 100 + ) + + async def test_step03_graphql_prefix_pool_delete_utilization( + self, + db: InfrahubDatabase, + default_branch: Branch, + branch2: Branch, + initial_dataset, + step_02_dataset, + step_03_dataset, + ): + container = initial_dataset["container"] + container_branch = step_02_dataset["container_branch"] + prefix_pool = initial_dataset["prefix_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": prefix_pool.id}, + ) + + assert not result.errors + assert result.data + pool_data = result.data["InfrahubResourcePoolUtilization"] + assert pool_data["count"] == 2 + assert pool_data["utilization"] == 100 / 16 + assert pool_data["utilization_default_branch"] == 100 / 32 + assert pool_data["utilization_branches"] == 100 / 32 + prefix_details_list = pool_data["edges"] + assert { + "node": { + "display_label": await container.render_display_label(db=db), + "id": container.id, + "kind": "IpamIPPrefix", + "utilization": 12.5, + "utilization_default_branch": 100 / 16, + "utilization_branches": 100 / 16, + "weight": 256, + } + } in prefix_details_list + assert { + "node": { + "display_label": await container_branch.render_display_label(db=db), + "id": container_branch.id, + "kind": "IpamIPPrefix", + "utilization": 0, + "utilization_default_branch": 0, + "utilization_branches": 0, + "weight": 256, + } + } in prefix_details_list + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch2) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [container.id, container_branch.id]}, + ) + + assert not result.errors + assert result.data + prefix_details_list = result.data["BuiltinIPPrefix"]["edges"] + assert len(prefix_details_list) == 2 + assert { + "node": { + "id": container.id, + "utilization": {"value": 6}, + "prefix": {"value": container.prefix.value}, + } + } in prefix_details_list + assert { + "node": { + "id": container_branch.id, + "utilization": {"value": 0}, + "prefix": {"value": container_branch.prefix.value}, + } + } in prefix_details_list + + async def test_step03_graphql_address_pool_delete_utilization( + self, + db: InfrahubDatabase, + default_branch: Branch, + branch2: Branch, + initial_dataset, + step_02_dataset, + step_03_dataset, + ): + prefix = initial_dataset["prefix"] + prefix_branch = step_02_dataset["prefix_branch"] + address_pool = initial_dataset["address_pool"] + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=POOL_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"pool_id": address_pool.id}, + ) + + assert not result.errors + assert result.data + pool_data = result.data["InfrahubResourcePoolUtilization"] + assert pool_data["count"] == 2 + assert pool_data["utilization"] == (25 / 28) * 100 + assert pool_data["utilization_default_branch"] == (6 / 28) * 100 + assert pool_data["utilization_branches"] == (19 / 28) * 100 + prefix_details_list = pool_data["edges"] + assert { + "node": { + "display_label": await prefix.render_display_label(db=db), + "id": prefix.id, + "kind": "IpamIPPrefix", + "utilization": (12 / 14) * 100, + "utilization_default_branch": (6 / 14) * 100, + "utilization_branches": (6 / 14) * 100, + "weight": 14, + } + } in prefix_details_list + assert { + "node": { + "display_label": await prefix_branch.render_display_label(db=db), + "id": prefix_branch.id, + "kind": "IpamIPPrefix", + "utilization": (13 / 14) * 100, + "utilization_default_branch": 0, + "utilization_branches": (13 / 14) * 100, + "weight": 14, + } + } in prefix_details_list + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch2) + result = await graphql( + schema=gql_params.schema, + source=PREFIX_UTILIZATION_QUERY, + context_value=gql_params.context, + variable_values={"prefix_ids": [prefix.id, prefix_branch.id]}, + ) + + assert not result.errors + assert result.data + prefix_details_list = result.data["BuiltinIPPrefix"]["edges"] + assert len(prefix_details_list) == 2 + assert { + "node": { + "id": prefix.id, + "utilization": {"value": int(6 / 14 * 100)}, + "prefix": {"value": prefix.prefix.value}, + } + } in prefix_details_list + assert { + "node": { + "id": prefix_branch.id, + "utilization": {"value": int(13 / 14 * 100)}, + "prefix": {"value": prefix_branch.prefix.value}, + } + } in prefix_details_list diff --git a/backend/tests/integration/ipam/test_proposed_change_reconcile.py b/backend/tests/integration/ipam/test_proposed_change_reconcile.py index ee45e3a6d4..8ba2c85f14 100644 --- a/backend/tests/integration/ipam/test_proposed_change_reconcile.py +++ b/backend/tests/integration/ipam/test_proposed_change_reconcile.py @@ -20,7 +20,7 @@ from infrahub.database import InfrahubDatabase -class TestIpamMergeReconcile(TestIpamReconcileBase): +class TestProposedChangeReconcile(TestIpamReconcileBase): @pytest.fixture(scope="class", autouse=True) def enable_broker_settings(self): config.SETTINGS.broker.enable = True @@ -59,7 +59,7 @@ async def test_step01_add_address( proposed_change_create.state.value = "merged" # type: ignore[attr-defined] await proposed_change_create.save() - updated_address = await NodeManager.get_one(db=db, branch=branch_1.name, id=new_address_1.id) + updated_address = await NodeManager.get_one(db=db, id=new_address_1.id) parent_rels = await updated_address.ip_prefix.get_relationships(db=db) # type: ignore[union-attr] assert len(parent_rels) == 1 assert parent_rels[0].peer_id == initial_dataset["net140"].id @@ -83,9 +83,9 @@ async def test_step02_add_delete_prefix( proposed_change_create.state.value = "merged" # type: ignore[attr-defined] await proposed_change_create.save() - deleted_prefix = await NodeManager.get_one(db=db, branch=branch_2.name, id=deleted_prefix_branch.id) + deleted_prefix = await NodeManager.get_one(db=db, id=deleted_prefix_branch.id) assert deleted_prefix is None - new_prefix_branch = await NodeManager.get_one(db=db, branch=branch_2.name, id=new_prefix.id) + new_prefix_branch = await NodeManager.get_one(db=db, id=new_prefix.id) parent_rels = await new_prefix_branch.parent.get_relationships(db=db) # type: ignore[union-attr] assert len(parent_rels) == 1 assert parent_rels[0].peer_id == initial_dataset["net146"].id diff --git a/backend/tests/integration/message_bus/operations/request/test_proposed_change.py b/backend/tests/integration/message_bus/operations/request/test_proposed_change.py index cb410d3552..02bee94b23 100644 --- a/backend/tests/integration/message_bus/operations/request/test_proposed_change.py +++ b/backend/tests/integration/message_bus/operations/request/test_proposed_change.py @@ -184,6 +184,6 @@ async def test_cancel( await cancel(message=message, service=services.service) assert fake_log.info_logs == ["Canceling proposed change as the source branch was deleted"] proposed_change = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=prepare_proposed_change, schema_name=InfrahubKind.PROPOSEDCHANGE + db=db, id=prepare_proposed_change, kind=InfrahubKind.PROPOSEDCHANGE ) assert proposed_change.state.value.value == ProposedChangeState.CANCELED.value # type: ignore[attr-defined] diff --git a/backend/tests/integration/proposed_change/test_proposed_change.py b/backend/tests/integration/proposed_change/test_proposed_change_conflict.py similarity index 94% rename from backend/tests/integration/proposed_change/test_proposed_change.py rename to backend/tests/integration/proposed_change/test_proposed_change_conflict.py index a885081bd9..2cbf6ae168 100644 --- a/backend/tests/integration/proposed_change/test_proposed_change.py +++ b/backend/tests/integration/proposed_change/test_proposed_change_conflict.py @@ -22,7 +22,7 @@ from tests.adapters.message_bus import BusSimulator -class TestProposedChangePipeline(TestInfrahubApp): +class TestProposedChangePipelineConflict(TestInfrahubApp): @pytest.fixture(scope="class") async def initial_dataset( self, @@ -70,7 +70,7 @@ async def happy_dataset(self, db: InfrahubDatabase, initial_dataset: None, clien await richard.save(db=db) john = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="John", schema_name=TestKind.PERSON, branch=branch1.name + db=db, id="John", kind=TestKind.PERSON, branch=branch1.name ) john.age.value = 26 # type: ignore[attr-defined] await john.save(db=db) @@ -78,12 +78,12 @@ async def happy_dataset(self, db: InfrahubDatabase, initial_dataset: None, clien @pytest.fixture(scope="class") async def conflict_dataset(self, db: InfrahubDatabase, initial_dataset: None) -> None: branch1 = await create_branch(db=db, branch_name="conflict_data") - john = await NodeManager.get_one_by_id_or_default_filter(db=db, id="John", schema_name=TestKind.PERSON) + john = await NodeManager.get_one_by_id_or_default_filter(db=db, id="John", kind=TestKind.PERSON) john.description.value = "Who is this?" # type: ignore[attr-defined] await john.save(db=db) john_branch = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="John", schema_name=TestKind.PERSON, branch=branch1 + db=db, id="John", kind=TestKind.PERSON, branch=branch1 ) john_branch.description.value = "Oh boy" # type: ignore[attr-defined] john_branch.age.value = 30 # type: ignore[attr-defined] @@ -97,7 +97,7 @@ async def test_happy_pipeline(self, db: InfrahubDatabase, happy_dataset: None, c await proposed_change_create.save() proposed_change = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=proposed_change_create.id, schema_name=InfrahubKind.PROPOSEDCHANGE + db=db, id=proposed_change_create.id, kind=InfrahubKind.PROPOSEDCHANGE ) peers = await proposed_change.validations.get_peers(db=db) # type: ignore[attr-defined] assert peers @@ -136,7 +136,7 @@ async def test_conflict_pipeline( await proposed_change_create.save() proposed_change = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=proposed_change_create.id, schema_name=InfrahubKind.PROPOSEDCHANGE + db=db, id=proposed_change_create.id, kind=InfrahubKind.PROPOSEDCHANGE ) peers = await proposed_change.validations.get_peers(db=db) # type: ignore[attr-defined] assert peers @@ -158,7 +158,7 @@ async def test_conflict_pipeline( await data_check.save() proposed_change_create.state.value = "merged" # type: ignore[attr-defined] await proposed_change_create.save() - john = await NodeManager.get_one_by_id_or_default_filter(db=db, id="John", schema_name=TestKind.PERSON) + john = await NodeManager.get_one_by_id_or_default_filter(db=db, id="John", kind=TestKind.PERSON) # The value of the description should match that of the source branch that was selected # as the branch to keep in the data conflict assert john.description.value == "Oh boy" # type: ignore[attr-defined] diff --git a/backend/tests/integration/proposed_change/test_proposed_change_profile.py b/backend/tests/integration/proposed_change/test_proposed_change_profile.py new file mode 100644 index 0000000000..2165e1a3c8 --- /dev/null +++ b/backend/tests/integration/proposed_change/test_proposed_change_profile.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from infrahub.core.constants import InfrahubKind, TaskConclusion, ValidatorConclusion +from infrahub.core.manager import NodeManager +from infrahub.core.node import Node +from infrahub.core.task import Task +from infrahub.services.adapters.cache.redis import RedisCache +from tests.constants import TestKind +from tests.helpers.schema import CAR_SCHEMA, load_schema +from tests.helpers.test_app import TestInfrahubApp + +if TYPE_CHECKING: + from infrahub_sdk import InfrahubClient + + from infrahub.database import InfrahubDatabase + from tests.adapters.message_bus import BusSimulator + + +class TestProposedChangePipelineProfile(TestInfrahubApp): + @pytest.fixture(scope="class") + async def initial_dataset( + self, + db: InfrahubDatabase, + initialize_registry: None, + git_repos_source_dir_module_scope: str, + client: InfrahubClient, + bus_simulator: BusSimulator, + ) -> None: + await load_schema(db, schema=CAR_SCHEMA) + + car_profile = await Node.init(schema=f"Profile{TestKind.CAR}", db=db) + await car_profile.new(db=db, profile_name="missing_description", description="missing description") + await car_profile.save(db=db) + + john = await Node.init(schema=TestKind.PERSON, db=db) + await john.new(db=db, name="John", height=175, description="The famous Joe Doe") + await john.save(db=db) + koenigsegg = await Node.init(schema=TestKind.MANUFACTURER, db=db) + await koenigsegg.new(db=db, name="Koenigsegg") + await koenigsegg.save(db=db) + people = await Node.init(schema=InfrahubKind.STANDARDGROUP, db=db) + await people.new(db=db, name="people", members=[john]) + await people.save(db=db) + + jesko = await Node.init(schema=TestKind.CAR, db=db) + await jesko.new(db=db, name="Jesko", color="Red", owner=john, manufacturer=koenigsegg, profiles=[car_profile]) + await jesko.save(db=db) + + bus_simulator.service.cache = RedisCache() + + @pytest.fixture(scope="class") + async def update_profile(self, db: InfrahubDatabase, initial_dataset: None, client: InfrahubClient) -> None: + branch1 = await client.branch.create(branch_name="update_profile") + profile1 = await NodeManager.get_one_by_default_filter( + db=db, id="missing_description", kind=f"Profile{TestKind.CAR}", branch=branch1.name + ) + assert profile1 + profile1.description.value = "MISSING DESCRIPTION" # type: ignore[attr-defined] + await profile1.save(db=db) + + async def test_pipeline(self, db: InfrahubDatabase, update_profile: None, client: InfrahubClient) -> None: + proposed_change_create = await client.create( + kind=InfrahubKind.PROPOSEDCHANGE, + data={"source_branch": "update_profile", "destination_branch": "main", "name": "PC1"}, + ) + await proposed_change_create.save() + + proposed_change = await NodeManager.get_one( + db=db, id=proposed_change_create.id, kind=InfrahubKind.PROPOSEDCHANGE + ) + assert proposed_change + peers = await proposed_change.validations.get_peers(db=db) # type: ignore[attr-defined] + assert peers + + # Ensure all validators and all tasks are successfull + assert all( + validator.conclusion.value.value == ValidatorConclusion.SUCCESS.value for validator in peers.values() + ) + + tasks = await Task.query(db=db, ids=[], fields={}, related_nodes=[proposed_change.id], limit=10, offset=0) + assert all(task["node"]["conclusion"] == TaskConclusion.SUCCESS for task in tasks["edges"]) + + proposed_change_create.state.value = "merged" # type: ignore[attr-defined] + await proposed_change_create.save() diff --git a/backend/tests/integration/schema_lifecycle/test_migration_attribute_branch.py b/backend/tests/integration/schema_lifecycle/test_migration_attribute_branch.py index bb96a279ce..791d1e74d3 100644 --- a/backend/tests/integration/schema_lifecycle/test_migration_attribute_branch.py +++ b/backend/tests/integration/schema_lifecycle/test_migration_attribute_branch.py @@ -151,7 +151,7 @@ def schema_step03( async def test_step01_baseline_backend(self, db: InfrahubDatabase, initial_dataset): persons = await registry.manager.query(db=db, schema=PERSON_KIND, branch=self.branch1) - assert len(persons) == 3 + assert len(persons) == 2 async def test_step02_check_attr_add_rename( self, db: InfrahubDatabase, client: InfrahubClient, initial_dataset, schema_step02 @@ -205,7 +205,6 @@ async def test_step02_load_attr_add_rename( # Check if the branch has been properly updated branches = await client.branch.all() - assert branches[self.branch1.name].is_isolated is True assert branches[self.branch1.name].has_schema_changes is True # Ensure that we can query the nodes with the new schema in BRANCH1 @@ -268,7 +267,7 @@ async def test_rebase(self, db: InfrahubDatabase, client: InfrahubClient, initia # Validate that all data added to main after the creation of the branch has been migrated properly persons = await registry.manager.query( - db=db, schema=PERSON_KIND, filters={"firstname__value": "Jane"}, branch=self.branch1 + db=db, schema=PERSON_KIND, filters={"firstname__value": "Jane"}, branch=self.branch1.name ) assert len(persons) == 1 jane = persons[0] diff --git a/backend/tests/integration/schema_lifecycle/test_migration_relationship_branch.py b/backend/tests/integration/schema_lifecycle/test_migration_relationship_branch.py index 88012656b6..526a74bc06 100644 --- a/backend/tests/integration/schema_lifecycle/test_migration_relationship_branch.py +++ b/backend/tests/integration/schema_lifecycle/test_migration_relationship_branch.py @@ -23,7 +23,7 @@ # pylint: disable=unused-argument -class TestSchemaLifecycleAttributeBranch(TestSchemaLifecycleBase): +class TestSchemaLifecycleRelationshipBranch(TestSchemaLifecycleBase): @property def branch1(self) -> Branch: return pytest.state["branch1"] # type: ignore[index] @@ -171,7 +171,7 @@ def schema_step03( async def test_step01_baseline_backend(self, db: InfrahubDatabase, initial_dataset): persons = await registry.manager.query(db=db, schema=PERSON_KIND, branch=self.branch1) - assert len(persons) == 3 + assert len(persons) == 2 async def test_step02_check(self, db: InfrahubDatabase, client: InfrahubClient, initial_dataset, schema_step02): car_schema = registry.schema.get_node_schema(name=CAR_KIND) @@ -237,7 +237,6 @@ async def test_step02_load(self, db: InfrahubDatabase, client: InfrahubClient, i # Check if the branch has been properly updated branches = await client.branch.all() - assert branches[self.branch1.name].is_isolated is True assert branches[self.branch1.name].has_schema_changes is True # Ensure that we can query the nodes with the new schema in BRANCH1 @@ -302,7 +301,7 @@ async def test_rebase(self, db: InfrahubDatabase, client: InfrahubClient, initia # Ensure that we can query the nodes with the new schema in BRANCH1 jane_cars = await registry.manager.query( - db=db, schema=CAR_KIND, filters={"main_driver__name__value": "Jane"}, branch=self.branch1 + db=db, schema=CAR_KIND, filters={"main_driver__name__value": "Jane"}, branch=self.branch1.name ) assert len(jane_cars) == 2 jane = await jane_cars[0].main_driver.get_peer(db=db) # type: ignore[attr-defined] diff --git a/backend/tests/integration/schema_lifecycle/test_schema_migration_branch.py b/backend/tests/integration/schema_lifecycle/test_schema_migration_branch.py index 3936b5c0d3..879ffd8efd 100644 --- a/backend/tests/integration/schema_lifecycle/test_schema_migration_branch.py +++ b/backend/tests/integration/schema_lifecycle/test_schema_migration_branch.py @@ -127,7 +127,7 @@ async def initial_dataset(self, db: InfrahubDatabase, initialize_registry, schem async def test_step01_baseline_backend(self, db: InfrahubDatabase, initial_dataset): persons = await registry.manager.query(db=db, schema=PERSON_KIND, branch=self.branch1) - assert len(persons) == 3 + assert len(persons) == 2 async def test_step02_check_attr_add_rename( self, db: InfrahubDatabase, client: InfrahubClient, initial_dataset, schema_step02 @@ -181,12 +181,11 @@ async def test_step02_load_attr_add_rename( # Check if the branch has been properly updated branches = await client.branch.all() - assert branches[self.branch1.name].is_isolated is True assert branches[self.branch1.name].has_schema_changes is True # Ensure that we can query the nodes with the new schema in BRANCH1 persons = await registry.manager.query( - db=db, schema=PERSON_KIND, filters={"firstname__value": "John"}, branch=self.branch1 + db=db, schema=PERSON_KIND, filters={"firstname__value": "John"}, branch=self.branch1.name ) assert len(persons) == 1 john = persons[0] @@ -268,14 +267,14 @@ async def test_step03_load(self, db: InfrahubDatabase, client: InfrahubClient, i # Ensure that we can query the existing node with the new schema # person_schema = registry.schema.get(name=PERSON_KIND) persons = await registry.manager.query( - db=db, schema=PERSON_KIND, filters={"firstname__value": "John"}, branch=self.branch1 + db=db, schema=PERSON_KIND, filters={"firstname__value": "John"}, branch=self.branch1.name ) assert len(persons) == 1 john = persons[0] assert not hasattr(john, "height") manufacturers = await registry.manager.query( - db=db, schema=MANUFACTURER_KIND_03, filters={"name__value": "renault"}, branch=self.branch1 + db=db, schema=MANUFACTURER_KIND_03, filters={"name__value": "renault"}, branch=self.branch1.name ) assert len(manufacturers) == 1 renault = manufacturers[0] @@ -289,14 +288,14 @@ async def test_rebase(self, db: InfrahubDatabase, client: InfrahubClient, initia # Validate that all data added to main after the creation of the branch has been migrated properly persons = await registry.manager.query( - db=db, schema=PERSON_KIND, filters={"firstname__value": "Jane"}, branch=self.branch1 + db=db, schema=PERSON_KIND, filters={"firstname__value": "Jane"}, branch=self.branch1.name ) assert len(persons) == 1 jane = persons[0] assert not hasattr(jane, "height") manufacturers = await registry.manager.query( - db=db, schema=MANUFACTURER_KIND_03, filters={"name__value": "honda"}, branch=self.branch1 + db=db, schema=MANUFACTURER_KIND_03, filters={"name__value": "honda"}, branch=self.branch1.name ) assert len(manufacturers) == 1 honda = manufacturers[0] diff --git a/backend/tests/integration/schema_lifecycle/test_schema_validator_generic_uniqueness.py b/backend/tests/integration/schema_lifecycle/test_schema_validator_generic_uniqueness.py index 4b886e9644..d539946d10 100644 --- a/backend/tests/integration/schema_lifecycle/test_schema_validator_generic_uniqueness.py +++ b/backend/tests/integration/schema_lifecycle/test_schema_validator_generic_uniqueness.py @@ -282,12 +282,12 @@ async def test_step_02_check_generic_uniqueness_constraint_rebase_failure( assert not response.errors boomer_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["boomer"] + db=db, kind=CYLON_KIND, id=initial_dataset["boomer"] ) boomer_main.favorite_color.value = "green" # type: ignore[attr-defined] await boomer_main.save(db=db) athena_branch = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["athena"], branch=branch_2 + db=db, kind=CYLON_KIND, id=initial_dataset["athena"], branch=branch_2 ) athena_branch.favorite_color.value = "green" # type: ignore[attr-defined] await athena_branch.save(db=db) @@ -307,12 +307,12 @@ async def test_step_03_check_generic_and_node_uniqueness_constraint_failure( schema_03_generic_and_node_uniqueness_failure, ): boomer_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["boomer"] + db=db, kind=CYLON_KIND, id=initial_dataset["boomer"] ) boomer_main.favorite_color.value = "green" # type: ignore[attr-defined] await boomer_main.save(db=db) caprica_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["caprica"] + db=db, kind=CYLON_KIND, id=initial_dataset["caprica"] ) caprica_main.favorite_color.value = "green" # type: ignore[attr-defined] await caprica_main.save(db=db) @@ -332,12 +332,12 @@ async def test_step_03_check_generic_and_node_uniqueness_constraint_failure( async def test_step_03_reset(self, db: InfrahubDatabase, initial_dataset): boomer_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["boomer"] + db=db, kind=CYLON_KIND, id=initial_dataset["boomer"] ) boomer_main.favorite_color.value = None # type: ignore[attr-defined] await boomer_main.save(db=db) caprica_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["caprica"] + db=db, kind=CYLON_KIND, id=initial_dataset["caprica"] ) caprica_main.favorite_color.value = None # type: ignore[attr-defined] await caprica_main.save(db=db) @@ -356,22 +356,22 @@ async def test_step_04_check_generic_and_node_uniqueness_constraint_rebase_failu assert not response.errors boomer_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["boomer"] + db=db, kind=CYLON_KIND, id=initial_dataset["boomer"] ) boomer_main.favorite_color.value = "green" # type: ignore[attr-defined] await boomer_main.save(db=db) athena_branch = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=CYLON_KIND, id=initial_dataset["athena"], branch=branch_2 + db=db, kind=CYLON_KIND, id=initial_dataset["athena"], branch=branch_2 ) athena_branch.favorite_color.value = "green" # type: ignore[attr-defined] await athena_branch.save(db=db) starbuck_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=PERSON_KIND, id=initial_dataset["starbuck"] + db=db, kind=PERSON_KIND, id=initial_dataset["starbuck"] ) starbuck_main.favorite_color.value = "purple" # type: ignore[attr-defined] await starbuck_main.save(db=db) president_branch = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name=PERSON_KIND, id=initial_dataset["president"], branch=branch_2 + db=db, kind=PERSON_KIND, id=initial_dataset["president"], branch=branch_2 ) president_branch.favorite_color.value = "purple" # type: ignore[attr-defined] await president_branch.save(db=db) diff --git a/backend/tests/integration/schema_lifecycle/test_schema_validator_main.py b/backend/tests/integration/schema_lifecycle/test_schema_validator_main.py index 1526b4e783..247f863b4c 100644 --- a/backend/tests/integration/schema_lifecycle/test_schema_validator_main.py +++ b/backend/tests/integration/schema_lifecycle/test_schema_validator_main.py @@ -292,7 +292,7 @@ async def test_step_05_check_attribute_unique_change_failure( async def test_step_06_check_attribute_unique_change_success( self, db: InfrahubDatabase, client: InfrahubClient, initial_dataset, schema_05_attribute_unique ): - pinto = await NodeManager.get_one_by_default_filter(db=db, id="pinto", schema_name="TestingCar") + pinto = await NodeManager.get_one_by_default_filter(db=db, id="pinto", kind="TestingCar", raise_on_error=True) await pinto.delete(db=db) success, response = await client.schema.check(schemas=[schema_05_attribute_unique]) @@ -318,5 +318,6 @@ async def test_step_06_check_attribute_unique_change_success( }, }, }, + "human_friendly_id": None, }, } diff --git a/backend/tests/integration/services/adapters/message_bus/test_rabbitmq.py b/backend/tests/integration/services/adapters/message_bus/test_rabbitmq.py index 5e2971cc66..3682ef6a9d 100644 --- a/backend/tests/integration/services/adapters/message_bus/test_rabbitmq.py +++ b/backend/tests/integration/services/adapters/message_bus/test_rabbitmq.py @@ -217,7 +217,11 @@ async def test_rabbitmq_initial_setup(rabbitmq_api: RabbitMQManager) -> None: ) assert ( Queue( - name="infrahub.rpcs", arguments={"x-max-priority": 5}, durable=True, exclusive=False, queue_type="classic" + name="infrahub.rpcs", + arguments={"x-max-priority": 5, "x-consumer-timeout": 30000}, + durable=True, + exclusive=False, + queue_type="classic", ) in api_queues ) diff --git a/backend/tests/integration/user_workflows/test_user_worflow.py b/backend/tests/integration/user_workflows/test_user_worflow.py index afbb77de05..18e4d99ead 100644 --- a/backend/tests/integration/user_workflows/test_user_worflow.py +++ b/backend/tests/integration/user_workflows/test_user_worflow.py @@ -329,6 +329,7 @@ async def test_update_intf_description_main(self, client, init_db_infra, dataset assert intfs[0]["node"]["description"]["value"] == new_description + @pytest.mark.xfail(reason="Investigate as part of the reworking of the diff payload (issue #3265)") async def test_validate_diff_after_description_update(self, client, dataset01, integration_helper): headers = await integration_helper.admin_headers() diff --git a/backend/tests/unit/api/conftest.py b/backend/tests/unit/api/conftest.py index 710c5a9383..a9dbe6b07a 100644 --- a/backend/tests/unit/api/conftest.py +++ b/backend/tests/unit/api/conftest.py @@ -548,11 +548,11 @@ async def data_diff_relationship_one(db: InfrahubDatabase, default_branch, car_p time_minus1 = pendulum.now(tz="UTC") c1_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="volt", schema_name="TestElectricCar", branch=default_branch + db=db, id="volt", kind="TestElectricCar", branch=default_branch ) p2_main = await NodeManager.get_one_by_id_or_default_filter( - db=db, id="Jane", schema_name="TestPerson", branch=default_branch + db=db, id="Jane", kind="TestPerson", branch=default_branch ) await c1_main.previous_owner.update(data=p2_main, db=db) diff --git a/backend/tests/unit/api/test_11_artifact.py b/backend/tests/unit/api/test_11_artifact.py index bdd8963d0b..f6d2104788 100644 --- a/backend/tests/unit/api/test_11_artifact.py +++ b/backend/tests/unit/api/test_11_artifact.py @@ -1,5 +1,6 @@ from fastapi.testclient import TestClient +from infrahub.core import registry from infrahub.core.constants import InfrahubKind from infrahub.core.node import Node from infrahub.database import InfrahubDatabase @@ -59,3 +60,68 @@ async def test_artifact_definition_endpoint( messages.RequestArtifactDefinitionGenerate(artifact_definition=ad1.id, branch="main", limit=[]) in rpc_bus.messages ) + + +async def test_artifact_endpoint( + db: InfrahubDatabase, + admin_headers, + register_core_models_schema, + register_builtin_models_schema, + car_person_data_generic, + authentication_base, +): + from infrahub.server import app + + client = TestClient(app) + + with client: + response = client.get("/api/artifact/95008984-16ca-4e58-8323-0899bb60035f", headers=admin_headers) + assert response.status_code == 404 + + g1 = await Node.init(db=db, schema=InfrahubKind.STANDARDGROUP) + await g1.new(db=db, name="group1", members=[car_person_data_generic["c1"], car_person_data_generic["c2"]]) + await g1.save(db=db) + + t1 = await Node.init(db=db, schema="CoreTransformPython") + await t1.new( + db=db, + name="transform01", + query=str(car_person_data_generic["q1"].id), + repository=str(car_person_data_generic["r1"].id), + file_path="transform01.py", + class_name="Transform01", + ) + await t1.save(db=db) + + ad1 = await Node.init(db=db, schema=InfrahubKind.ARTIFACTDEFINITION) + await ad1.new( + db=db, + name="artifactdef01", + targets=g1, + transformation=t1, + content_type="application/json", + artifact_name="myartifact", + parameters={"value": {"name": "name__value"}}, + ) + await ad1.save(db=db) + + art1 = await Node.init(db=db, schema=InfrahubKind.ARTIFACT) + await art1.new( + db=db, + name="myyartifact", + definition=ad1, + status="Ready", + object=car_person_data_generic["c1"], + storage_id="95008984-16ca-4e58-8323-0899bb60035f", + checksum="60d39063c26263353de24e1b913e1e1c", + content_type="application/json", + ) + await art1.save(db=db) + + registry.storage.store(identifier="95008984-16ca-4e58-8323-0899bb60035f", content='{"test": true}'.encode()) + + with client: + response = client.get(f"/api/artifact/{art1.id}", headers=admin_headers) + + assert response.status_code == 200 + assert response.json() == {"test": True} diff --git a/backend/tests/unit/api/test_20_graphql_api.py b/backend/tests/unit/api/test_20_graphql_api.py index 614c960796..17ded28d46 100644 --- a/backend/tests/unit/api/test_20_graphql_api.py +++ b/backend/tests/unit/api/test_20_graphql_api.py @@ -1,5 +1,6 @@ import pytest +from infrahub.core import registry from infrahub.core.branch import Branch from infrahub.core.initialization import create_branch from infrahub.core.timestamp import Timestamp @@ -217,3 +218,125 @@ async def test_download_schema(db: InfrahubDatabase, client, client_headers): response = client.get("/schema.graphql?branch=notvalid", headers=client_headers) assert response.status_code == 400 + + +async def test_query_at_previous_schema( + db: InfrahubDatabase, client, admin_headers, default_branch: Branch, authentication_base, car_person_data +): + # Load the schema in the database + schema = registry.schema.get_schema_branch(name=default_branch.name) + await registry.schema.load_schema_to_db(schema=schema, branch=default_branch, db=db) + + time_before = Timestamp() + + query = """ + query { + TestPerson { + edges { + node { + display_label + } + } + } + } + """ + + # Must execute in a with block to execute the startup/shutdown events + with client: + response = client.post( + "/graphql", + json={"query": query}, + headers=admin_headers, + ) + + assert response.status_code == 200 + assert "errors" not in response.json() + assert response.json()["data"] is not None + result = response.json()["data"] + assert result == { + "TestPerson": { + "edges": [ + {"node": {"display_label": "John"}}, + {"node": {"display_label": "Jane"}}, + ], + }, + } + + creation = client.post( + "/api/schema/load", + headers=admin_headers, + json={ + "schemas": [ + { + "version": "1.0", + "nodes": [ + { + "name": "Person", + "namespace": "Test", + "default_filter": "name__value", + "display_labels": ["name__value", "height__value"], + "attributes": [ + {"name": "name", "kind": "Text", "unique": True}, + {"name": "height", "kind": "Number", "optional": True}, + ], + "relationships": [ + {"name": "cars", "peer": "TestCar", "cardinality": "many", "direction": "inbound"} + ], + }, + ], + } + ] + }, + ) + data = creation.json() + assert data + assert data.get("schema_updated") is True + assert "diff" in data + assert data["diff"] == { + "added": {}, + "changed": { + "TestPerson": {"added": {}, "changed": {"display_labels": None}, "removed": {}}, + }, + "removed": {}, + } + assert creation.status_code == 200 + + # Do another query to validate that the schema has been updated + response = client.post( + "/graphql", + json={"query": query}, + headers=admin_headers, + ) + + assert response.status_code == 200 + assert "errors" not in response.json() + assert response.json()["data"] is not None + result = response.json()["data"] + assert result == { + "TestPerson": { + "edges": [ + {"node": {"display_label": "John 180"}}, + {"node": {"display_label": "Jane 170"}}, + ], + }, + } + + # Query before we updated the schema to validate that we can pull the latest schema + response = client.post( + f"/graphql?at={time_before.to_string()}", + json={"query": query}, + headers=admin_headers, + ) + + assert "errors" not in response.json() + assert response.status_code == 200 + assert response.json()["data"] is not None + result = response.json()["data"] + assert result == { + "TestPerson": { + "edges": [ + {"node": {"display_label": "John"}}, + {"node": {"display_label": "Jane"}}, + ], + }, + } diff --git a/backend/tests/unit/api/test_40_schema_api.py b/backend/tests/unit/api/test_40_schema_api.py index 2cb190ca27..1e8b8494d5 100644 --- a/backend/tests/unit/api/test_40_schema_api.py +++ b/backend/tests/unit/api/test_40_schema_api.py @@ -144,6 +144,33 @@ async def test_schema_kind_default_branch( assert "relationships" in schema +async def test_json_schema_kind_default_branch( + db: InfrahubDatabase, + client, + client_headers, + default_branch: Branch, + car_person_schema_generics: SchemaRoot, + car_person_data_generic, +): + with client: + response = client.get( + f"/api/schema/json_schema/{InfrahubKind.TAG}", + headers=client_headers, + ) + + assert response.status_code == 200 + assert response.json() is not None + + schema = response.json() + + assert "$schema" in schema + assert "title" in schema + assert "type" in schema + assert "properties" in schema + assert "required" in schema + assert "description" in schema + + async def test_schema_kind_not_valid( db: InfrahubDatabase, client, diff --git a/backend/tests/unit/api/test_auth.py b/backend/tests/unit/api/test_auth.py index 5a4da864d2..3a6b516188 100644 --- a/backend/tests/unit/api/test_auth.py +++ b/backend/tests/unit/api/test_auth.py @@ -206,7 +206,7 @@ async def test_generate_api_token(db: InfrahubDatabase, default_branch, client, "/api/auth/login", json={ "username": "test-admin", - "password": config.SETTINGS.security.initial_admin_password, + "password": config.SETTINGS.initial.admin_password, }, ) @@ -218,9 +218,10 @@ async def test_generate_api_token(db: InfrahubDatabase, default_branch, client, CoreAccountTokenCreate(data: { name: "my-first-token" }) { ok object { - token { - value - } + id + token { + value + } } } } @@ -234,6 +235,7 @@ async def test_generate_api_token(db: InfrahubDatabase, default_branch, client, assert jwt_response.status_code == 200 api_token = jwt_response.json()["data"]["CoreAccountTokenCreate"]["object"]["token"]["value"] + token_id = jwt_response.json()["data"]["CoreAccountTokenCreate"]["object"]["id"] # Validate that the generated API token can't be used to generate another API token with client: @@ -246,3 +248,60 @@ async def test_generate_api_token(db: InfrahubDatabase, default_branch, client, assert api_response.status_code == 200 assert not api_response.json()["data"]["CoreAccountTokenCreate"] assert api_response.json()["errors"][0]["message"] == api_response.json()["errors"][0]["message"] + + token_query = """ + query CoreAccountToken { + CoreAccountToken(offset: 0, limit: 5) { + count + edges { + node { + expiration + id + name + } + } + } + } + """ + with client: + token_query_response = client.post( + "/graphql", + json={"query": token_query}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert token_query_response.status_code == 200 + tokens = token_query_response.json()["data"]["CoreAccountToken"]["edges"] + assert token_id in [token["node"]["id"] for token in tokens] + + token_delete_mutation = ( + """ + mutation MyMutation { + CoreAccountTokenDelete(data: {id: "%s"}) { + ok + } + } + """ + % token_id + ) + + with client: + token_delete_response = client.post( + "/graphql", + json={"query": token_delete_mutation}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert token_delete_response.status_code == 200 + assert token_delete_response.json()["data"]["CoreAccountTokenDelete"]["ok"] + + with client: + token_query_response = client.post( + "/graphql", + json={"query": token_query}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert token_query_response.status_code == 200 + tokens = token_query_response.json()["data"]["CoreAccountToken"]["edges"] + assert token_id not in [token["node"]["id"] for token in tokens] diff --git a/backend/tests/unit/api/test_auth_cookies.py b/backend/tests/unit/api/test_auth_cookies.py index c740e4f004..8161d2c72e 100644 --- a/backend/tests/unit/api/test_auth_cookies.py +++ b/backend/tests/unit/api/test_auth_cookies.py @@ -68,7 +68,7 @@ async def test_generate_api_token(db: InfrahubDatabase, default_branch, client, "/api/auth/login", json={ "username": "test-admin", - "password": config.SETTINGS.security.initial_admin_password, + "password": config.SETTINGS.initial.admin_password, }, ) diff --git a/backend/tests/unit/conftest.py b/backend/tests/unit/conftest.py index 0cae2aa76d..7865bc26e9 100644 --- a/backend/tests/unit/conftest.py +++ b/backend/tests/unit/conftest.py @@ -22,6 +22,9 @@ initialization, ) from infrahub.core.node import Node +from infrahub.core.node.ipam import BuiltinIPPrefix +from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool from infrahub.core.schema import ( GenericSchema, NodeSchema, @@ -2190,6 +2193,14 @@ async def init_db(empty_database, db: InfrahubDatabase) -> None: await initialization(db=db) +@pytest.fixture +async def init_nodes_registry(db: InfrahubDatabase) -> None: + registry.node["Node"] = Node + registry.node[InfrahubKind.IPPREFIX] = BuiltinIPPrefix + registry.node[InfrahubKind.IPPREFIXPOOL] = CoreIPPrefixPool + registry.node[InfrahubKind.IPADDRESSPOOL] = CoreIPAddressPool + + @pytest.fixture async def organization_schema() -> SchemaRoot: SCHEMA: dict[str, Any] = { @@ -2381,6 +2392,54 @@ async def register_ipam_schema(default_branch: Branch, ipam_schema: SchemaRoot) return schema_branch +@pytest.fixture +async def register_ipam_extended_schema(default_branch: Branch, register_ipam_schema) -> SchemaBranch: + SCHEMA: dict[str, Any] = { + "nodes": [ + { + "name": "MandatoryPrefix", + "namespace": "Test", + "description": "A model with a mandatory relationship to a BuiltinIPPrefix", + "attributes": [ + {"name": "name", "kind": "Text"}, + {"name": "description", "kind": "Text", "optional": True}, + ], + "relationships": [ + { + "name": "prefix", + "peer": "IpamIPPrefix", + "kind": "Attribute", + "optional": False, + "cardinality": "one", + }, + ], + }, + { + "name": "MandatoryAddress", + "namespace": "Test", + "description": "A model with a mandatory relationship to a IpamIPAddress", + "attributes": [ + {"name": "name", "kind": "Text"}, + {"name": "description", "kind": "Text", "optional": True}, + ], + "relationships": [ + { + "name": "address", + "peer": "IpamIPAddress", + "kind": "Attribute", + "optional": False, + "cardinality": "one", + }, + ], + }, + ], + } + + schema_branch = registry.schema.register_schema(schema=SchemaRoot(**SCHEMA), branch=default_branch.name) + default_branch.update_schema_hash() + return schema_branch + + @pytest.fixture async def create_test_admin(db: InfrahubDatabase, register_core_models_schema, data_schema) -> Node: account = await Node.init(db=db, schema=InfrahubKind.ACCOUNT) @@ -2388,7 +2447,7 @@ async def create_test_admin(db: InfrahubDatabase, register_core_models_schema, d db=db, name="test-admin", type="User", - password=config.SETTINGS.security.initial_admin_password, + password=config.SETTINGS.initial.admin_password, role="admin", ) await account.save(db=db) @@ -2499,3 +2558,174 @@ async def mock_core_schema_01(helper, httpx_mock: HTTPXMock) -> HTTPXMock: @pytest.fixture def dataset01(init_db) -> None: ds01.load_data() + + +@pytest.fixture +async def ip_dataset_01( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + + # ----------------------- + # Namespace NS1 + # ----------------------- + + ns1 = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ns1.new(db=db, name="ns1") + await ns1.save(db=db) + + net161 = await Node.init(db=db, schema=prefix_schema) + await net161.new(db=db, prefix="2001:db8::/48", ip_namespace=ns1) + await net161.save(db=db) + + net162 = await Node.init(db=db, schema=prefix_schema) + await net162.new(db=db, prefix="2001:db8::/64", ip_namespace=ns1, parent=net161) + await net162.save(db=db) + + net146 = await Node.init(db=db, schema=prefix_schema) + await net146.new(db=db, prefix="10.0.0.0/8", ip_namespace=ns1) + await net146.save(db=db) + + net140 = await Node.init(db=db, schema=prefix_schema) + await net140.new(db=db, prefix="10.10.0.0/16", ip_namespace=ns1, parent=net146) + await net140.save(db=db) + + net142 = await Node.init(db=db, schema=prefix_schema) + await net142.new(db=db, prefix="10.10.1.0/24", parent=net140, ip_namespace=ns1) + await net142.save(db=db) + + net143 = await Node.init(db=db, schema=prefix_schema) + await net143.new(db=db, prefix="10.10.1.0/27", parent=net142, ip_namespace=ns1) + await net143.save(db=db) + + net144 = await Node.init(db=db, schema=prefix_schema) + await net144.new(db=db, prefix="10.10.2.0/24", parent=net140, ip_namespace=ns1) + await net144.save(db=db) + + net145 = await Node.init(db=db, schema=prefix_schema) + await net145.new(db=db, prefix="10.10.3.0/27", parent=net140, ip_namespace=ns1) + await net145.save(db=db) + + address10 = await Node.init(db=db, schema=address_schema) + await address10.new(db=db, address="10.10.0.0", ip_prefix=net140, ip_namespace=ns1) + await address10.save(db=db) + + address11 = await Node.init(db=db, schema=address_schema) + await address11.new(db=db, address="10.10.1.1", ip_prefix=net143, ip_namespace=ns1) + await address11.save(db=db) + + # ----------------------- + # Namespace NS2 + # ----------------------- + ns2 = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ns2.new(db=db, name="ns2") + await ns2.save(db=db) + + net240 = await Node.init(db=db, schema=prefix_schema) + await net240.new(db=db, prefix="10.10.0.0/15", ip_namespace=ns2) + await net240.save(db=db) + + net241 = await Node.init(db=db, schema=prefix_schema) + await net241.new(db=db, prefix="10.10.0.0/24", parent=net240, ip_namespace=ns2) + await net241.save(db=db) + + net242 = await Node.init(db=db, schema=prefix_schema) + await net242.new(db=db, prefix="10.10.4.0/27", parent=net240, ip_namespace=ns2) + await net242.save(db=db) + + data = { + "ns1": ns1, + "ns2": ns2, + "net161": net161, + "net162": net162, + "net140": net140, + "net142": net142, + "net143": net143, + "net144": net144, + "net145": net145, + "net146": net146, + "address10": address10, + "address11": address11, + "net240": net240, + "net241": net241, + "net242": net242, + } + return data + + +@pytest.fixture +async def ip_dataset_prefix_v4( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + + ns1 = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ns1.new(db=db, name="ns1") + await ns1.save(db=db) + + net146 = await Node.init(db=db, schema=prefix_schema) + await net146.new(db=db, prefix="10.0.0.0/8", ip_namespace=ns1) + await net146.save(db=db) + + net140 = await Node.init(db=db, schema=prefix_schema) + await net140.new(db=db, prefix="10.10.0.0/16", ip_namespace=ns1, parent=net146) + await net140.save(db=db) + + net141 = await Node.init(db=db, schema=prefix_schema) + await net141.new(db=db, prefix="10.11.0.0/16", ip_namespace=ns1, parent=net146) + await net141.save(db=db) + + net142 = await Node.init(db=db, schema=prefix_schema) + await net142.new(db=db, prefix="10.10.1.0/24", parent=net140, ip_namespace=ns1) + await net142.save(db=db) + + net143 = await Node.init(db=db, schema=prefix_schema) + await net143.new(db=db, prefix="10.10.1.0/27", parent=net142, ip_namespace=ns1) + await net143.save(db=db) + + net144 = await Node.init(db=db, schema=prefix_schema) + await net144.new(db=db, prefix="10.10.2.0/24", parent=net140, ip_namespace=ns1) + await net144.save(db=db) + + net145 = await Node.init(db=db, schema=prefix_schema) + await net145.new(db=db, prefix="10.10.3.0/27", parent=net140, ip_namespace=ns1) + await net145.save(db=db) + + ip1_net145 = await Node.init(db=db, schema=address_schema) + await ip1_net145.new(db=db, address="10.10.3.1/27", ip_prefix=net145, ip_namespace=ns1) + await ip1_net145.save(db=db) + + net147 = await Node.init(db=db, schema=prefix_schema) + await net147.new(db=db, prefix="10.200.0.0/30", parent=net146, ip_namespace=ns1) + await net147.save(db=db) + + ip1_net147 = await Node.init(db=db, schema=address_schema) + await ip1_net147.new(db=db, address="10.200.0.1/30", ip_prefix=net147, ip_namespace=ns1) + await ip1_net147.save(db=db) + + ip_branch = await create_branch(branch_name="ip_branch1", db=db) + + ip2_net147 = await Node.init(db=db, schema=address_schema, branch=ip_branch) + await ip2_net147.new(db=db, address="10.200.0.2/30", ip_prefix=net147, ip_namespace=ns1) + await ip2_net147.save(db=db) + + data = { + "ns1": ns1, + "net140": net140, + "net141": net141, + "net142": net142, + "net143": net143, + "net144": net144, + "net145": net145, + "net146": net146, + "net147": net147, + } + return data diff --git a/backend/tests/unit/core/constraint_validators/test_relationship_peer_update.py b/backend/tests/unit/core/constraint_validators/test_relationship_peer_update.py index 51a43d7195..33959afb4d 100644 --- a/backend/tests/unit/core/constraint_validators/test_relationship_peer_update.py +++ b/backend/tests/unit/core/constraint_validators/test_relationship_peer_update.py @@ -162,13 +162,14 @@ async def test_query_no_relationships( db: InfrahubDatabase, branch: Branch, car_accord_main: Node, car_volt_main: Node, person_john_main ): await branch.rebase(db=db) + car_schema = registry.schema.get(name="TestCar", duplicate=False) + owner_rel = car_schema.get_relationship(name="owner") + owner_rel.optional = True for car in (car_accord_main, car_volt_main): fresh_car = await NodeManager.get_one(db=db, id=car.id, branch=branch) await fresh_car.owner.update(db=db, data=None) await fresh_car.save(db=db) - car_schema = registry.schema.get(name="TestCar") - owner_rel = car_schema.get_relationship(name="owner") owner_rel.peer = "TestCar" schema_path = SchemaPath(path_type=SchemaPathType.RELATIONSHIP, schema_kind="TestCar", field_name="owner") diff --git a/backend/tests/unit/core/constraint_validators/test_uniqueness_checker.py b/backend/tests/unit/core/constraint_validators/test_uniqueness_checker.py index c3700e4004..0b2b2d891a 100644 --- a/backend/tests/unit/core/constraint_validators/test_uniqueness_checker.py +++ b/backend/tests/unit/core/constraint_validators/test_uniqueness_checker.py @@ -236,11 +236,9 @@ async def test_generic_unique_attribute_violations( branch: Branch, default_branch: Branch, ): - nolt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestGazCar", id="nolt", branch=branch - ) + nolt_car = await NodeManager.get_one_by_id_or_default_filter(db=db, kind="TestGazCar", id="nolt", branch=branch) volt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestElectricCar", id="volt", branch=branch + db=db, kind="TestElectricCar", id="volt", branch=branch ) volt_car.name.value = "nolt" await volt_car.save(db=db) @@ -291,14 +289,12 @@ async def test_generic_unique_attribute_multiple_relationship_violations_to_same await nolt_owner.save(db=db) volt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestElectricCar", id="volt", branch=branch + db=db, kind="TestElectricCar", id="volt", branch=branch ) await volt_car.owner.get_peer(db=db) await volt_car.previous_owner.update(data=nolt_owner, db=db) await volt_car.save(db=db) - nolt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestGazCar", id="nolt", branch=branch - ) + nolt_car = await NodeManager.get_one_by_id_or_default_filter(db=db, kind="TestGazCar", id="nolt", branch=branch) await nolt_car.owner.update(data=nolt_owner, db=db) await nolt_car.previous_owner.update(data=nolt_owner, db=db) await nolt_car.save(db=db) @@ -372,12 +368,12 @@ async def test_generic_unique_constraint_relationship_with_and_without_attr( ): owner = car_person_generics_data_simple["p1"] volt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestElectricCar", id="volt", branch=branch + db=db, kind="TestElectricCar", id="volt", branch=branch ) await volt_car.previous_owner.update(data=owner, db=db) await volt_car.save(db=db) bolt_car = await NodeManager.get_one_by_id_or_default_filter( - db=db, schema_name="TestElectricCar", id="bolt", branch=branch + db=db, kind="TestElectricCar", id="bolt", branch=branch ) await bolt_car.previous_owner.update(data=owner, db=db) await bolt_car.save(db=db) diff --git a/backend/tests/unit/core/ipam/test_ipam.py b/backend/tests/unit/core/ipam/test_ipam.py index 0aa09571d7..70dda42230 100644 --- a/backend/tests/unit/core/ipam/test_ipam.py +++ b/backend/tests/unit/core/ipam/test_ipam.py @@ -9,14 +9,8 @@ from infrahub.core.manager import NodeManager from infrahub.core.node import Node from infrahub.core.query.ipam import ( - IPPrefixContainerFetch, IPPrefixSubnetFetch, - IPPrefixUtilizationAddress, - IPPrefixUtilizationPrefix, - get_container, get_ip_addresses, - get_ip_prefix_for_ip_address, - get_utilization, ) from infrahub.core.schema_manager import SchemaBranch from infrahub.database import InfrahubDatabase @@ -56,38 +50,6 @@ async def test_ipaddress_creation( await address2.save(db=db) -async def test_ipprefix_is_within_container( - db: InfrahubDatabase, - default_branch: Branch, - default_ipnamespace: Node, - register_core_models_schema: SchemaBranch, - register_ipam_schema: SchemaBranch, -): - prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) - - container = await Node.init(db=db, schema=prefix_schema) - await container.new(db=db, prefix="2001:db8::/32", ip_namespace=default_ipnamespace) - await container.save(db=db) - - prefix = await Node.init(db=db, schema=prefix_schema) - await prefix.new(db=db, prefix="2001:db8::/48", parent=container, ip_namespace=default_ipnamespace) - await prefix.save(db=db) - - unrelated = await Node.init(db=db, schema=prefix_schema) - await unrelated.new(db=db, prefix="192.0.2.0/24", ip_namespace=default_ipnamespace) - await unrelated.save(db=db) - - container_ip_network = ipaddress.ip_network(container.prefix.value) - prefix_ip_network = ipaddress.ip_network(prefix.prefix.value) - - prefix_container = await get_container(db=db, branch=default_branch, ip_prefix=container_ip_network) - assert prefix_container is None - - prefix_container = await get_container(db=db, branch=default_branch, ip_prefix=prefix_ip_network) - assert prefix_container - assert prefix_container.prefix == ipaddress.ip_network(container_ip_network) - - @pytest.mark.parametrize( "input,response", [ @@ -129,24 +91,6 @@ async def test_ipprefix_subnets_small_dataset( assert sorted([str(subnet.prefix) for subnet in subnets]) == ["2001:db8::/48"] -@pytest.mark.parametrize( - "input,response", - [ - (ipaddress.ip_network("10.10.0.0/22"), "10.10.0.0/16"), - (ipaddress.ip_network("10.10.1.0/28"), "10.10.1.0/27"), - (ipaddress.ip_interface("10.10.1.10/27"), "10.10.1.0/27"), - ], -) -async def test_ipprefix_container(db: InfrahubDatabase, default_branch: Branch, ip_dataset_01, input, response): - ns1_id = ip_dataset_01["ns1"].id - query = await IPPrefixContainerFetch.init(db=db, branch=default_branch, obj=input, namespace=ns1_id) - - await query.execute(db=db) - container = query.get_container() - assert container is not None - assert str(container.prefix) == response - - async def test_ipaddress_is_within_ipprefix( db: InfrahubDatabase, default_branch: Branch, @@ -176,54 +120,6 @@ async def test_ipaddress_is_within_ipprefix( assert len(ip_addresses) == 1 assert ip_addresses[0].address == address_ip_address - ip_prefix = await get_ip_prefix_for_ip_address(db=db, branch=default_branch, ip_address=address_ip_address) - assert ip_prefix - assert ip_prefix.prefix == prefix_ip_network - - -async def test_ipprefix_utilization( - db: InfrahubDatabase, - default_branch: Branch, - register_core_models_schema: SchemaBranch, - register_ipam_schema: SchemaBranch, -): - prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) - address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) - - container = await Node.init(db=db, schema=prefix_schema) - await container.new(db=db, prefix="192.0.2.0/24", member_type="prefix") - await container.save(db=db) - - prefix = await Node.init(db=db, schema=prefix_schema) - await prefix.new(db=db, prefix="192.0.2.0/28", member_type="address", parent=container) - await prefix.save(db=db) - - prefix2 = await Node.init(db=db, schema=prefix_schema) - await prefix2.new(db=db, prefix="192.0.2.128/28", member_type="prefix", parent=container) - await prefix2.save(db=db) - - addresses = [] - for i in range(1, 8): - address = await Node.init(db=db, schema=address_schema) - await address.new(db=db, address=f"192.0.2.{i}/28", ip_prefix=prefix) - await address.save(db=db) - addresses.append(address) - - query = await IPPrefixUtilizationPrefix.init(db, branch=default_branch, ip_prefix=container) - await query.execute(db) - assert query.get_percentage() == 100 / 8 - assert await get_utilization(db=db, branch=default_branch, ip_prefix=container) == 100 / 8 - - query = await IPPrefixUtilizationPrefix.init(db, branch=default_branch, ip_prefix=prefix2) - await query.execute(db) - assert query.get_percentage() == 0 - assert await get_utilization(db=db, branch=default_branch, ip_prefix=prefix2) == 0 - - query = await IPPrefixUtilizationAddress.init(db, branch=default_branch, ip_prefix=prefix) - await query.execute(db) - assert query.get_percentage() == 50.0 - assert await get_utilization(db=db, branch=default_branch, ip_prefix=prefix) == 50.0 - async def test_query_by_parent_ids(db: InfrahubDatabase, default_branch: Branch, ip_dataset_01): prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) diff --git a/backend/tests/unit/core/ipam/test_ipam_reconcile_query.py b/backend/tests/unit/core/ipam/test_ipam_reconcile_query.py index 4570cff3cc..17de8559b9 100644 --- a/backend/tests/unit/core/ipam/test_ipam_reconcile_query.py +++ b/backend/tests/unit/core/ipam/test_ipam_reconcile_query.py @@ -2,9 +2,11 @@ from infrahub.core import registry from infrahub.core.branch import Branch -from infrahub.core.initialization import create_ipam_namespace, get_default_ipnamespace +from infrahub.core.constants import InfrahubKind +from infrahub.core.initialization import create_branch, create_ipam_namespace, get_default_ipnamespace from infrahub.core.node import Node from infrahub.core.query.ipam import IPPrefixReconcileQuery +from infrahub.core.schema_manager import SchemaBranch from infrahub.database import InfrahubDatabase @@ -234,27 +236,29 @@ async def test_ipprefix_reconcile_query_get_deleted_node_by_uuid( } -async def test_branch_updates_respected(db: InfrahubDatabase, branch: Branch, default_branch: Branch, ip_dataset_01): +async def test_branch_updates_respected(db: InfrahubDatabase, default_branch: Branch, ip_dataset_01): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + + branch2 = await create_branch(branch_name="branch2", db=db) + ns1_id = ip_dataset_01["ns1"].id - prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=branch) - address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=branch) - await branch.rebase(db=db) net140 = ip_dataset_01["net140"] await net140.delete(db=db) address10 = ip_dataset_01["address10"] await address10.delete(db=db) - new_parent_branch = await Node.init(db=db, schema=prefix_schema, branch=branch) + new_parent_branch = await Node.init(db=db, schema=prefix_schema, branch=branch2) await new_parent_branch.new(db=db, prefix="10.10.0.0/17", ip_namespace=ns1_id) await new_parent_branch.save(db=db) new_address_main = await Node.init(db=db, schema=address_schema, branch=default_branch) await new_address_main.new(db=db, address="10.10.0.2", ip_namespace=ns1_id) await new_address_main.save(db=db) - new_address_branch = await Node.init(db=db, schema=address_schema, branch=branch) + new_address_branch = await Node.init(db=db, schema=address_schema, branch=branch2) await new_address_branch.new(db=db, address="10.10.0.1", ip_namespace=ns1_id) await new_address_branch.save(db=db) query = await IPPrefixReconcileQuery.init( - db=db, branch=branch, ip_value=ipaddress.ip_network("10.10.0.0/22"), namespace=ns1_id + db=db, branch=branch2, ip_value=ipaddress.ip_network("10.10.0.0/22"), namespace=ns1_id ) await query.execute(db=db) @@ -262,10 +266,231 @@ async def test_branch_updates_respected(db: InfrahubDatabase, branch: Branch, de assert query.get_current_parent_uuid() is None assert query.get_current_children_uuids() == [] assert query.get_calculated_parent_uuid() == new_parent_branch.id - assert set(query.get_calculated_children_uuids()) == { + expected_children = { + ip_dataset_01["net142"].id, + ip_dataset_01["net144"].id, + ip_dataset_01["net145"].id, + ip_dataset_01["address10"].id, + new_address_branch.id, + } + assert set(query.get_calculated_children_uuids()) == expected_children + + await branch2.rebase(db=db) + + query = await IPPrefixReconcileQuery.init( + db=db, branch=branch2, ip_value=ipaddress.ip_network("10.10.0.0/22"), namespace=ns1_id + ) + await query.execute(db=db) + + assert query.get_ip_node_uuid() is None + assert query.get_current_parent_uuid() is None + assert query.get_current_children_uuids() == [] + assert query.get_calculated_parent_uuid() == new_parent_branch.id + + expected_children_after_rebase = { ip_dataset_01["net142"].id, ip_dataset_01["net144"].id, ip_dataset_01["net145"].id, new_address_branch.id, new_address_main.id, } + assert set(query.get_calculated_children_uuids()) == expected_children_after_rebase + + +async def test_reconcile_parent_child_identification( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + ip_namespace = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ip_namespace.new(db=db, name="ns1") + await ip_namespace.save(db=db) + prefix_id_map = {} + for network in [ + "136.0.0.0/8", + "136.128.0.0/12", + "136.136.0.0/16", + "136.136.128.0/20", + "136.136.136.0/24", + "136.136.136.128/28", + "136.136.136.136/32", + ]: + prefix_node = await Node.init(db=db, schema=prefix_schema) + await prefix_node.new(db=db, prefix=network, ip_namespace=ip_namespace) + await prefix_node.save(db=db) + prefix_id_map[prefix_node.id] = network + address_id_map = {} + for address in ["136.136.136.136/30", "136.136.136.136/31", "136.136.136.136/32"]: + address_node = await Node.init(db=db, schema=address_schema) + await address_node.new(db=db, address=address, ip_namespace=ip_namespace) + await address_node.save(db=db) + address_id_map[address_node.id] = address + + for prefix_to_check, parent, children in ( + (ipaddress.ip_network("136.0.0.0/8"), None, {"136.128.0.0/12"}), + (ipaddress.ip_network("136.128.0.0/12"), "136.0.0.0/8", {"136.136.0.0/16"}), + (ipaddress.ip_network("136.136.0.0/16"), "136.128.0.0/12", {"136.136.128.0/20"}), + ): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=prefix_to_check + ) + await query.execute(db=db) + calculated_parent_uuid = query.get_calculated_parent_uuid() + if parent is None: + assert calculated_parent_uuid is None + else: + assert parent == prefix_id_map.get(calculated_parent_uuid) + assert children == {prefix_id_map.get(ccu) for ccu in query.get_calculated_children_uuids()} + + for prefix_to_check, parent, prefix_children, address_children in ( + (ipaddress.ip_network("136.136.136.136/32"), "136.136.136.128/28", set(), {"136.136.136.136/32"}), + # 136.136.136.136/32 is not an address child for the below b/c its correct parent is prefix 136.136.136.136/32, not 136.136.136.136/30 + ( + ipaddress.ip_network("136.136.136.136/30"), + "136.136.136.128/28", + {"136.136.136.136/32"}, + {"136.136.136.136/30", "136.136.136.136/31"}, + ), + ): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=prefix_to_check + ) + await query.execute(db=db) + + calculated_parent_uuid = query.get_calculated_parent_uuid() + if parent is None: + assert calculated_parent_uuid is None + else: + assert parent == prefix_id_map.get(calculated_parent_uuid) + assert prefix_children == { + prefix_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in prefix_id_map + } + assert address_children == { + address_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in address_id_map + } + + +async def test_address_cannot_be_parent( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + ip_namespace = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ip_namespace.new(db=db, name="ns1") + await ip_namespace.save(db=db) + prefix_node = await Node.init(db=db, schema=prefix_schema) + await prefix_node.new(db=db, prefix="172.20.20.0/27", ip_namespace=ip_namespace) + await prefix_node.save(db=db) + address_node = await Node.init(db=db, schema=address_schema) + await address_node.new(db=db, address="172.20.20.0/24", ip_namespace=ip_namespace) + await address_node.save(db=db) + + for ip_value in (ipaddress.ip_interface("172.20.20.0/24"), ipaddress.ip_network("172.20.20.0/27")): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ip_value + ) + await query.execute(db=db) + assert query.get_calculated_parent_uuid() is None + assert query.get_calculated_children_uuids() == [] + + +async def test_adjacent_parents_and_addresses( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + ip_namespace = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ip_namespace.new(db=db, name="ns1") + await ip_namespace.save(db=db) + prefix_id_map = {} + for prefix in ("192.0.2.0/32", "192.0.2.0/31", "192.0.2.0/30", "192.0.2.0/29"): + prefix_node = await Node.init(db=db, schema=prefix_schema) + await prefix_node.new(db=db, prefix=prefix, ip_namespace=ip_namespace) + await prefix_node.save(db=db) + prefix_id_map[prefix_node.id] = prefix + address_id_map = {} + for i in range(7): + address = f"192.0.2.{i}/31" + address_node = await Node.init(db=db, schema=address_schema) + await address_node.new(db=db, address=address, ip_namespace=ip_namespace) + await address_node.save(db=db) + address_id_map[address_node.id] = address + + # test prefix 192.0.2.0/32 + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_network("192.0.2.0/32") + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/31" + assert query.get_calculated_children_uuids() == [] + # test prefix 192.0.2.0/31 + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_network("192.0.2.0/31") + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/30" + assert {address_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in address_id_map} == { + "192.0.2.0/31", + "192.0.2.1/31", + } + assert {prefix_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in prefix_id_map} == { + "192.0.2.0/32" + } + # test prefix 192.0.2.0/30 + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_network("192.0.2.0/30") + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/29" + assert {address_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in address_id_map} == { + "192.0.2.2/31", + "192.0.2.3/31", + } + assert {prefix_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in prefix_id_map} == { + "192.0.2.0/31" + } + # test prefix 192.0.2.0/29 + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_network("192.0.2.0/29") + ) + await query.execute(db=db) + assert query.get_calculated_parent_uuid() is None + assert {address_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in address_id_map} == { + "192.0.2.4/31", + "192.0.2.5/31", + "192.0.2.6/31", + } + assert {prefix_id_map[ccu] for ccu in query.get_calculated_children_uuids() if ccu in prefix_id_map} == { + "192.0.2.0/30" + } + # test children address find correct parent + for address in ("192.0.2.0/31", "192.0.2.1/31"): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_interface(address) + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/31" + assert query.get_calculated_children_uuids() == [] + for address in ("192.0.2.2/31", "192.0.2.3/31"): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_interface(address) + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/30" + assert query.get_calculated_children_uuids() == [] + for address in ("192.0.2.4/31", "192.0.2.5/31", "192.0.2.6/31"): + query = await IPPrefixReconcileQuery.init( + db=db, branch=default_branch, namespace=ip_namespace.id, ip_value=ipaddress.ip_interface(address) + ) + await query.execute(db=db) + assert prefix_id_map[query.get_calculated_parent_uuid()] == "192.0.2.0/29" + assert query.get_calculated_children_uuids() == [] diff --git a/backend/tests/unit/core/resource_manager/__init__.py b/backend/tests/unit/core/resource_manager/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/tests/unit/core/resource_manager/test_ipaddress_pool.py b/backend/tests/unit/core/resource_manager/test_ipaddress_pool.py new file mode 100644 index 0000000000..1e88ae571d --- /dev/null +++ b/backend/tests/unit/core/resource_manager/test_ipaddress_pool.py @@ -0,0 +1,64 @@ +import pytest + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.node import Node +from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase +from infrahub.exceptions import PoolExhaustedError + + +async def test_get_next( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net145 = ip_dataset_prefix_v4["net145"] + + adress_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + pool = await CoreIPAddressPool.init(schema=adress_pool_schema, db=db) + await pool.new(db=db, name="pool1", resources=[net145], ip_namespace=ns1, default_address_type="IpamIPAddress") + await pool.save(db=db) + + assert pool + + next_address = await pool.get_next(db=db, prefixlen=30) + assert str(next_address) == "10.10.3.2/30" + + next_prefix = await pool.get_resource( + db=db, address_type="IpamIPAddress", identifier="item1", branch=default_branch + ) + assert next_prefix + + next_prefix2 = await pool.get_resource( + db=db, address_type="IpamIPAddress", identifier="item1", branch=default_branch + ) + assert next_prefix.id == next_prefix2.id + + +async def test_get_next_full( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net147 = ip_dataset_prefix_v4["net147"] + + adress_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + pool = await CoreIPAddressPool.init(schema=adress_pool_schema, db=db) + await pool.new(db=db, name="pool2", resources=[net147], ip_namespace=ns1, default_address_type="IpamIPAddress") + await pool.save(db=db) + + assert pool + + with pytest.raises(PoolExhaustedError, match="There are no more addresses available in this pool"): + await pool.get_next(db=db, prefixlen=30) diff --git a/backend/tests/unit/core/resource_manager/test_prefix_pool.py b/backend/tests/unit/core/resource_manager/test_prefix_pool.py new file mode 100644 index 0000000000..4695a784e8 --- /dev/null +++ b/backend/tests/unit/core/resource_manager/test_prefix_pool.py @@ -0,0 +1,140 @@ +import pytest + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.initialization import create_branch +from infrahub.core.node import Node +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase + + +async def test_get_next( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + net141 = ip_dataset_prefix_v4["net141"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db) + await pool.new(db=db, name="pool1", resources=[net140, net141], ip_namespace=ns1) + await pool.save(db=db) + + assert pool + + next_subnet = await pool.get_next(db=db, prefixlen=17) + assert str(next_subnet) == "10.10.128.0/17" + + next_prefix = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", identifier="item1", branch=default_branch + ) + assert next_prefix + + next_prefix2 = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", identifier="item1", branch=default_branch + ) + assert next_prefix.id == next_prefix2.id + + +async def test_get_one( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + net141 = ip_dataset_prefix_v4["net141"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db) + await pool.new(db=db, name="pool1", resources=[net140, net141], ip_namespace=ns1) + await pool.save(db=db) + + assert pool + + next_prefix = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", identifier="item1", branch=default_branch + ) + assert next_prefix + + next_prefix2 = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", identifier="item1", branch=default_branch + ) + assert next_prefix.id == next_prefix2.id + + next_prefix3 = await pool.get_resource( + db=db, + prefixlen=24, + prefix_type="IpamIPPrefix", + member_type="address", + identifier="item2", + branch=default_branch, + ) + assert next_prefix3.member_type.value == "address" + + with pytest.raises(ValueError): + await pool.get_resource(db=db, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch) + + with pytest.raises(ValueError): + await pool.get_resource(db=db, prefixlen=17, member_type="prefix", branch=default_branch) + + +async def test_get_all_resources( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + net141 = ip_dataset_prefix_v4["net141"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db) + await pool.new(db=db, name="pool1", resources=[net140, net141], ip_namespace=ns1) + await pool.save(db=db) + + assert pool + + prefix1 = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch + ) + prefix2 = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch + ) + another_branch = await create_branch(branch_name="another_branch", db=db) + prefix3 = await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", branch=another_branch + ) + with pytest.raises(IndexError): + await pool.get_resource( + db=db, prefixlen=17, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch + ) + + prefix4 = await pool.get_resource( + db=db, prefixlen=24, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch + ) + prefix5 = await pool.get_resource( + db=db, prefixlen=24, prefix_type="IpamIPPrefix", member_type="prefix", branch=default_branch + ) + + all_prefixes = [ + prefix1.prefix.value, + prefix2.prefix.value, + prefix3.prefix.value, + prefix4.prefix.value, + prefix5.prefix.value, + ] + assert sorted(all_prefixes) == ["10.10.0.0/24", "10.10.128.0/17", "10.10.4.0/24", "10.11.0.0/17", "10.11.128.0/17"] diff --git a/backend/tests/unit/core/schema_manager/conftest.py b/backend/tests/unit/core/schema_manager/conftest.py index 39c19a4bd7..7912ddab0e 100644 --- a/backend/tests/unit/core/schema_manager/conftest.py +++ b/backend/tests/unit/core/schema_manager/conftest.py @@ -10,6 +10,83 @@ def _get_schema_by_kind(full_schema, kind): return schema_dict +@pytest.fixture +async def animal_person_schema_dict() -> dict: + FULL_SCHEMA = { + "generics": [ + { + "name": "Animal", + "namespace": "Test", + "display_labels": ["name__value"], + "human_friendly_id": ["owner__name__value", "name__value"], + "order_by": ["name__value"], + "icon": "myicon", + "uniqueness_constraints": [ + ["owner", "name__value"], + ], + "branch": BranchSupportType.AWARE.value, + "attributes": [ + {"name": "name", "kind": "Text"}, + ], + "relationships": [ + { + "name": "owner", + "peer": "TestPerson", + "optional": False, + "identifier": "person__animal", + "cardinality": "one", + "direction": "outbound", + }, + ], + }, + ], + "nodes": [ + { + "name": "Dog", + "namespace": "Test", + "inherit_from": ["TestAnimal"], + "attributes": [ + {"name": "breed", "kind": "Text", "optional": False}, + {"name": "color", "kind": "Color", "default_value": "#444444", "optional": True}, + ], + }, + { + "name": "Cat", + "namespace": "Test", + "inherit_from": ["TestAnimal"], + "display_labels": ["name__value", "breed__value", "color__value"], + "human_friendly_id": ["owner__name__value", "name__value", "breed__value"], + "order_by": ["breed__value", "name__value"], + "attributes": [ + {"name": "breed", "kind": "Text", "optional": False}, + {"name": "color", "kind": "Color", "default_value": "#444444", "optional": True}, + ], + }, + { + "name": "Person", + "namespace": "Test", + "display_labels": ["name__value"], + "attributes": [ + {"name": "name", "kind": "Text", "unique": True}, + {"name": "other_name", "kind": "Text", "unique": True}, + {"name": "height", "kind": "Number", "optional": True}, + ], + "relationships": [ + { + "name": "animals", + "peer": "TestAnimal", + "identifier": "person__animal", + "cardinality": "many", + "direction": "inbound", + } + ], + }, + ], + } + + return FULL_SCHEMA + + @pytest.fixture def schema_all_in_one(): FULL_SCHEMA = { @@ -99,7 +176,7 @@ def schema_all_in_one(): "peer": InfrahubKind.TAG, "label": "Primary Tag", "identifier": "primary_tag__criticality", - "optional": True, + "optional": False, "cardinality": "one", "branch": BranchSupportType.AGNOSTIC.value, }, diff --git a/backend/tests/unit/core/schema_manager/test_manager_schema.py b/backend/tests/unit/core/schema_manager/test_manager_schema.py index 324ced828f..ecbe2e5ebc 100644 --- a/backend/tests/unit/core/schema_manager/test_manager_schema.py +++ b/backend/tests/unit/core/schema_manager/test_manager_schema.py @@ -113,6 +113,46 @@ async def test_schema_branch_process_inheritance(schema_all_in_one): } +async def test_schema_branch_process_inheritance_node_level(animal_person_schema_dict): + schema = SchemaBranch(cache={}, name="test") + schema.load_schema(schema=SchemaRoot(**animal_person_schema_dict)) + + schema.process_inheritance() + + animal = schema.get(name="TestAnimal") + assert sorted(animal.used_by) == ["TestCat", "TestDog"] + + dog = schema.get(name="TestDog") + cat = schema.get(name="TestCat") + assert dog.human_friendly_id == animal.human_friendly_id + assert cat.human_friendly_id != animal.human_friendly_id + + assert dog.display_labels == animal.display_labels + assert cat.display_labels != animal.display_labels + + assert dog.order_by == animal.order_by + assert cat.order_by != animal.order_by + + assert dog.icon == animal.icon + + +async def test_schema_branch_process_humain_friendly_id(animal_person_schema_dict): + schema = SchemaBranch(cache={}, name="test") + schema.load_schema(schema=SchemaRoot(**animal_person_schema_dict)) + + schema.process_inheritance() + schema.process_human_friendly_id() + + animal = schema.get(name="TestAnimal") + assert sorted(animal.used_by) == ["TestCat", "TestDog"] + + dog = schema.get(name="TestDog") + person = schema.get(name="TestPerson") + + assert person.human_friendly_id == ["name__value"] + assert dog.uniqueness_constraints == [["owner", "name__value"]] + + async def test_schema_branch_process_branch_support(schema_all_in_one): schema = SchemaBranch(cache={}, name="test") schema.load_schema(schema=SchemaRoot(**schema_all_in_one)) @@ -300,6 +340,7 @@ async def test_schema_branch_add_profile_schema(schema_all_in_one): schema = SchemaBranch(cache={}, name="test") schema.load_schema(schema=SchemaRoot(**schema_all_in_one)) + schema.process_inheritance() schema.add_profile_schemas() profile = schema.get(name="ProfileBuiltinCriticality") @@ -307,6 +348,7 @@ async def test_schema_branch_add_profile_schema(schema_all_in_one): assert profile.get_attribute("profile_priority").branch == BranchSupportType.AGNOSTIC.value assert set(profile.attribute_names) == {"profile_name", "profile_priority", "description"} core_profile_schema = schema.get("CoreProfile") + core_node_schema = schema.get("CoreNode") assert set(core_profile_schema.used_by) == { "ProfileBuiltinCriticality", "ProfileBuiltinTag", @@ -316,6 +358,21 @@ async def test_schema_branch_add_profile_schema(schema_all_in_one): "ProfileInfraTinySchema", } + assert set(core_node_schema.used_by) == { + "BuiltinBadge", + "BuiltinCriticality", + "BuiltinStatus", + "BuiltinTag", + "CoreStandardGroup", + "InfraTinySchema", + "ProfileBuiltinCriticality", + "ProfileBuiltinTag", + "ProfileBuiltinStatus", + "ProfileBuiltinBadge", + "ProfileCoreStandardGroup", + "ProfileInfraTinySchema", + } + async def test_schema_branch_generate_identifiers(schema_all_in_one): schema = SchemaBranch(cache={}, name="test") @@ -797,6 +854,44 @@ async def test_validate_uniqueness_constraints_success(schema_all_in_one, unique schema.validate_uniqueness_constraints() +async def test_validate_exception_ipam_ip_namespace( + db: InfrahubDatabase, default_branch: Branch, register_core_models_schema +): + SCHEMA: dict = { + "nodes": [ + { + "name": "IPPrefix", + "namespace": "Ipam", + "default_filter": "prefix__value", + "order_by": ["prefix__value"], + "display_labels": ["prefix__value"], + "human_friendly_id": ["ip_namespace__name__value", "prefix__value"], + "branch": BranchSupportType.AWARE.value, + "inherit_from": [InfrahubKind.IPPREFIX], + }, + { + "name": "IPAddress", + "namespace": "Ipam", + "default_filter": "address__value", + "order_by": ["address__value"], + "display_labels": ["address__value"], + "uniqueness_constraints": [["ip_namespace", "address__value"]], + "branch": BranchSupportType.AWARE.value, + "inherit_from": [InfrahubKind.IPADDRESS], + }, + ], + } + + ipam_schema = SchemaRoot(**SCHEMA) + + schema = registry.schema.get_schema_branch(name=default_branch.name) + schema.load_schema(schema=ipam_schema) + schema.process() + + ip_prefix_schema = schema.get(name="IpamIPPrefix") + assert ip_prefix_schema.uniqueness_constraints + + @pytest.mark.parametrize( "uniqueness_constraints,expected_error", [ @@ -822,11 +917,11 @@ async def test_validate_uniqueness_constraints_success(schema_all_in_one, unique ), ( [["primary_tag__name__value"]], - "InfraGenericInterface.uniqueness_constraints: cannot use attributes of related node in constraint, only the relationship", + "InfraGenericInterface.uniqueness_constraints: cannot use attributes of related node, only the relationship", ), ( [["mybool__value", "status__name__value"]], - "InfraGenericInterface.uniqueness_constraints: cannot use attributes of related node in constraint, only the relationship", + "InfraGenericInterface.uniqueness_constraints: cannot use attributes of related node, only the relationship", ), ], ) diff --git a/backend/tests/unit/core/schema_manager/test_validate_schema_path.py b/backend/tests/unit/core/schema_manager/test_validate_schema_path.py new file mode 100644 index 0000000000..10c3d35a15 --- /dev/null +++ b/backend/tests/unit/core/schema_manager/test_validate_schema_path.py @@ -0,0 +1,177 @@ +import pytest + +from infrahub.core.branch import Branch +from infrahub.core.constants import ( + SchemaElementPathType, +) +from infrahub.core.schema import ( + SchemaRoot, +) +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase + + +class TestValidateSchemaPath: + @pytest.fixture + async def schema(db: InfrahubDatabase, reset_registry, default_branch: Branch) -> SchemaBranch: + FULL_SCHEMA = { + "nodes": [ + { + "name": "Criticality", + "namespace": "Test", + "default_filter": "name__value", + "label": "Criticality", + "attributes": [ + {"name": "name", "kind": "Text", "label": "Name", "unique": True}, + {"name": "level", "kind": "Number", "label": "Level"}, + {"name": "color", "kind": "Text", "label": "Color", "default_value": "#444444"}, + {"name": "description", "kind": "Text", "label": "Description", "optional": True}, + ], + "relationships": [ + { + "name": "tags", + "peer": "TestTag", + "label": "Tags", + "optional": True, + "cardinality": "many", + }, + { + "name": "primary_tag", + "peer": "TestTag", + "label": "Primary Tag", + "identifier": "primary_tag__criticality", + "optional": True, + "cardinality": "one", + }, + ], + }, + { + "name": "Tag", + "namespace": "Test", + "label": "Tag", + "default_filter": "name__value", + "attributes": [ + {"name": "name", "kind": "Text", "label": "Name", "unique": True}, + {"name": "description", "kind": "Text", "label": "Description", "optional": True}, + ], + }, + ] + } + schema = SchemaRoot(**FULL_SCHEMA) + schema.generate_uuid() + schema_branch = SchemaBranch(cache={}, name="test") + schema_branch.load_schema(schema=schema) + return schema_branch + + def test_attr_only(self, schema: SchemaBranch): + criticality_schema = schema.get(name="TestCriticality") + + allowed_types = SchemaElementPathType.ATTR + schema_path = schema.validate_schema_path( + node_schema=criticality_schema, path="name__value", allowed_path_types=allowed_types + ) + assert schema_path.is_type_attribute + + with pytest.raises(ValueError) as exc: + schema.validate_schema_path(node_schema=criticality_schema, path="tags", allowed_path_types=allowed_types) + assert "only supports attributes" in str(exc.value) + + @pytest.mark.parametrize( + "path,allowed_types", + [ + # standalone + ("primary_tag", SchemaElementPathType.REL_ONE), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE_ATTR), + ("primary_tag", SchemaElementPathType.REL_ONE_NO_ATTR), + # with another flag (attr) + ("primary_tag", SchemaElementPathType.REL_ONE | SchemaElementPathType.ATTR), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE | SchemaElementPathType.ATTR), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE_ATTR | SchemaElementPathType.ATTR), + ("primary_tag", SchemaElementPathType.REL_ONE_NO_ATTR | SchemaElementPathType.ATTR), + # with another flag (rel) + ("primary_tag", SchemaElementPathType.REL_ONE | SchemaElementPathType.REL_MANY_NO_ATTR), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE | SchemaElementPathType.REL_MANY_NO_ATTR), + ("primary_tag__name__value", SchemaElementPathType.REL_ONE_ATTR | SchemaElementPathType.REL_MANY_NO_ATTR), + ("primary_tag", SchemaElementPathType.REL_ONE_NO_ATTR | SchemaElementPathType.REL_MANY_NO_ATTR), + ], + ) + def test_rel_one_valid(self, schema: SchemaBranch, path, allowed_types): + criticality_schema = schema.get(name="TestCriticality") + schema_path = schema.validate_schema_path( + node_schema=criticality_schema, path=path, allowed_path_types=allowed_types + ) + assert schema_path.is_type_relationship + + def test_rel_one_fail(self, schema: SchemaBranch): + criticality_schema = schema.get(name="TestCriticality") + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_ONE_NO_ATTR + schema.validate_schema_path( + node_schema=criticality_schema, path="primary_tag__name__value", allowed_path_types=allowed_types + ) + assert "cannot use attributes of related node" in str(exc.value) + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_ONE_ATTR + schema.validate_schema_path( + node_schema=criticality_schema, path="primary_tag", allowed_path_types=allowed_types + ) + assert "Must use attributes of related node" in str(exc.value) + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_ONE + schema.validate_schema_path( + node_schema=criticality_schema, path="name__value", allowed_path_types=allowed_types + ) + assert "this property only supports relationships" in str(exc.value) + + @pytest.mark.parametrize( + "path,allowed_types", + [ + # standalone + ("tags", SchemaElementPathType.REL_MANY), + ("tags__name__value", SchemaElementPathType.REL_MANY), + ("tags__name__value", SchemaElementPathType.REL_MANY_ATTR), + ("tags", SchemaElementPathType.REL_MANY_NO_ATTR), + # with another flag (attr) + ("tags", SchemaElementPathType.REL_MANY | SchemaElementPathType.ATTR), + ("tags__name__value", SchemaElementPathType.REL_MANY | SchemaElementPathType.ATTR), + ("tags__name__value", SchemaElementPathType.REL_MANY_ATTR | SchemaElementPathType.ATTR), + ("tags", SchemaElementPathType.REL_MANY_NO_ATTR | SchemaElementPathType.ATTR), + # with another flag (rel) + ("tags", SchemaElementPathType.REL_MANY | SchemaElementPathType.REL_ONE_NO_ATTR), + ("tags__name__value", SchemaElementPathType.REL_MANY | SchemaElementPathType.REL_ONE_NO_ATTR), + ("tags__name__value", SchemaElementPathType.REL_MANY_ATTR | SchemaElementPathType.REL_ONE_NO_ATTR), + ("tags", SchemaElementPathType.REL_MANY_NO_ATTR | SchemaElementPathType.REL_ONE_NO_ATTR), + ], + ) + def test_rel_many_valid(self, schema: SchemaBranch, path, allowed_types): + criticality_schema = schema.get(name="TestCriticality") + schema_path = schema.validate_schema_path( + node_schema=criticality_schema, path=path, allowed_path_types=allowed_types + ) + assert schema_path.is_type_relationship + + def test_rel_many_fail(self, schema: SchemaBranch): + criticality_schema = schema.get(name="TestCriticality") + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_MANY_NO_ATTR + schema.validate_schema_path( + node_schema=criticality_schema, path="tags__name__value", allowed_path_types=allowed_types + ) + assert "cannot use attributes of related node" in str(exc.value) + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_MANY_ATTR + schema.validate_schema_path(node_schema=criticality_schema, path="tags", allowed_path_types=allowed_types) + assert "Must use attributes of related node" in str(exc.value) + + with pytest.raises(ValueError) as exc: + allowed_types = SchemaElementPathType.REL_MANY + schema.validate_schema_path( + node_schema=criticality_schema, path="name__value", allowed_path_types=allowed_types + ) + assert "this property only supports relationships" in str(exc.value) diff --git a/backend/tests/unit/core/test_branch.py b/backend/tests/unit/core/test_branch.py index 1ac808abaa..878c4c5d44 100644 --- a/backend/tests/unit/core/test_branch.py +++ b/backend/tests/unit/core/test_branch.py @@ -168,17 +168,12 @@ async def test_get_branches_and_times_to_query_branch1(db: InfrahubDatabase, bas t0 = Timestamp() results = branch1.get_branches_and_times_to_query(at=t0) assert Timestamp(results[frozenset(["branch1"])]) > now - assert results[frozenset(["main"])] == t0.to_string() + assert results[frozenset(["main"])] == base_dataset_02["time_m45"] t1 = Timestamp("2s") results = branch1.get_branches_and_times_to_query(at=t1) assert results[frozenset(["branch1"])] == t1.to_string() - assert results[frozenset(["main"])] == t1.to_string() - - branch1.is_isolated = True - results = branch1.get_branches_and_times_to_query(at=Timestamp()) - assert Timestamp(results[frozenset(["branch1"])]) > now - assert results[frozenset(("main",))] == base_dataset_02["time_m45"] + assert results[frozenset(["main"])] == base_dataset_02["time_m45"] async def test_get_branches_and_times_to_query_global_main(db: InfrahubDatabase, base_dataset_02): @@ -202,16 +197,11 @@ async def test_get_branches_and_times_to_query_global_branch1(db: InfrahubDataba t0 = Timestamp() results = branch1.get_branches_and_times_to_query_global(at=t0) assert Timestamp(results[frozenset((GLOBAL_BRANCH_NAME, "branch1"))]) > now - assert results[frozenset((GLOBAL_BRANCH_NAME, "main"))] == t0.to_string() + assert results[frozenset((GLOBAL_BRANCH_NAME, "main"))] == base_dataset_02["time_m45"] t1 = Timestamp("2s") results = branch1.get_branches_and_times_to_query_global(at=t1.to_string()) assert results[frozenset((GLOBAL_BRANCH_NAME, "branch1"))] == t1.to_string() - assert results[frozenset((GLOBAL_BRANCH_NAME, "main"))] == t1.to_string() - - branch1.is_isolated = True - results = branch1.get_branches_and_times_to_query_global(at=Timestamp()) - assert Timestamp(frozenset((GLOBAL_BRANCH_NAME, "branch1"))) > now assert results[frozenset((GLOBAL_BRANCH_NAME, "main"))] == base_dataset_02["time_m45"] diff --git a/backend/tests/unit/core/test_diff_payload.py b/backend/tests/unit/core/test_diff_payload.py new file mode 100644 index 0000000000..2b78537b25 --- /dev/null +++ b/backend/tests/unit/core/test_diff_payload.py @@ -0,0 +1,248 @@ +import pytest + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import DiffAction, RelationshipCardinality, RelationshipKind +from infrahub.core.diff.branch_differ import BranchDiffer +from infrahub.core.diff.model import DiffElementType +from infrahub.core.diff.payload_builder import DiffPayloadBuilder +from infrahub.core.initialization import create_branch +from infrahub.core.manager import NodeManager +from infrahub.core.node import Node +from infrahub.core.schema.relationship_schema import RelationshipSchema +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase + + +@pytest.fixture +async def car_person_schema_with_friend( + db: InfrahubDatabase, default_branch: Branch, car_person_schema_unregistered +) -> SchemaBranch: + schema = [schema for schema in car_person_schema_unregistered.nodes if schema.kind == "TestPerson"][0] + schema.relationships.append( + RelationshipSchema( + name="best_friend", + identifier="test_person__test_person", + peer="TestPerson", + kind=RelationshipKind.GENERIC, + cardinality=RelationshipCardinality.ONE, + optional=True, + ) + ) + return registry.schema.register_schema(schema=car_person_schema_unregistered, branch=default_branch.name) + + +async def test_diff_payload_one_relationship_update( + db: InfrahubDatabase, person_alfred_main, person_john_main, car_accord_main +): + branch = await create_branch(db=db, branch_name="branch") + car_branch = await NodeManager.get_one(db=db, branch=branch, id=car_accord_main.id) + await car_branch.owner.update(db=db, data=person_alfred_main) + await car_branch.save(db=db) + differ = await BranchDiffer.init(branch=branch, db=db) + payload_builder = DiffPayloadBuilder(db=db, diff=differ) + + diff_payload = await payload_builder.get_branch_diff_nodes() + + payloads_by_id = {p.id: p for p in diff_payload} + assert set(payloads_by_id.keys()) == {car_accord_main.id, person_alfred_main.id, person_john_main.id} + assert payloads_by_id[person_alfred_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_alfred_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["cars"] + assert diff_element.type is DiffElementType.RELATIONSHIP_MANY + assert diff_element.name == "cars" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.ADDED + diff_peers = diff_element.peers + assert len(diff_peers) == 1 + assert diff_peers[0].peer.id == car_branch.id + + assert payloads_by_id[person_john_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_john_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["cars"] + assert diff_element.type is DiffElementType.RELATIONSHIP_MANY + assert diff_element.name == "cars" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.REMOVED + diff_peers = diff_element.peers + assert len(diff_peers) == 1 + assert diff_peers[0].peer.id == car_branch.id + + assert payloads_by_id[car_branch.id].action is DiffAction.UPDATED + owner_element = payloads_by_id[car_branch.id].elements["owner"] + assert owner_element.type is DiffElementType.RELATIONSHIP_ONE + assert owner_element.name == "owner" + assert owner_element.branch == branch.name + assert owner_element.action is DiffAction.UPDATED + assert owner_element.peer.previous.id == person_john_main.id + assert owner_element.peer.new.id == person_alfred_main.id + + +async def test_diff_payload_two_updates_one_relationship(db: InfrahubDatabase, person_albert_main, person_alfred_main): + branch = await create_branch(db=db, branch_name="branch") + car_branch = await Node.init(db=db, schema="TestCar", branch=branch) + await car_branch.new(db=db, name="pinto", nbr_seats=3, is_electric=False, owner=person_albert_main.id) + await car_branch.save(db=db) + car_branch = await NodeManager.get_one(db=db, branch=branch, id=car_branch.id) + await car_branch.owner.update(db=db, data=person_alfred_main) + await car_branch.save(db=db) + differ = await BranchDiffer.init(branch=branch, db=db) + payload_builder = DiffPayloadBuilder(db=db, diff=differ) + + diff_payload = await payload_builder.get_branch_diff_nodes() + + payloads_by_id = {p.id: p for p in diff_payload} + # NOT WORKING + # assert set(payloads_by_id.keys()) == {car_branch.id, person_alfred_main.id} + + assert payloads_by_id[person_alfred_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_alfred_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["cars"] + assert diff_element.type is DiffElementType.RELATIONSHIP_MANY + assert diff_element.name == "cars" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.ADDED + diff_peers = diff_element.peers + assert len(diff_peers) == 1 + assert diff_peers[0].peer.id == car_branch.id + + assert payloads_by_id[car_branch.id].action is DiffAction.ADDED + owner_element = payloads_by_id[car_branch.id].elements["owner"] + assert owner_element.type is DiffElementType.RELATIONSHIP_ONE + assert owner_element.name == "owner" + assert owner_element.branch == branch.name + assert owner_element.action is DiffAction.UPDATED + assert owner_element.peer.previous.id == person_albert_main.id + assert owner_element.peer.new.id == person_alfred_main.id + + +async def test_diff_payload_three_updates_one_relationship( + db: InfrahubDatabase, person_albert_main, person_alfred_main, person_jane_main +): + branch = await create_branch(db=db, branch_name="branch") + car_branch = await Node.init(db=db, schema="TestCar", branch=branch) + await car_branch.new(db=db, name="pinto", nbr_seats=3, is_electric=False, owner=person_albert_main.id) + await car_branch.save(db=db) + car_branch = await NodeManager.get_one(db=db, branch=branch, id=car_branch.id) + await car_branch.owner.update(db=db, data=person_jane_main) + await car_branch.save(db=db) + car_branch = await NodeManager.get_one(db=db, branch=branch, id=car_branch.id) + await car_branch.owner.update(db=db, data=person_alfred_main) + await car_branch.save(db=db) + differ = await BranchDiffer.init(branch=branch, db=db) + payload_builder = DiffPayloadBuilder(db=db, diff=differ) + + diff_payload = await payload_builder.get_branch_diff_nodes() + + payloads_by_id = {p.id: p for p in diff_payload} + # NOT WORKING + # assert set(payloads_by_id.keys()) == {person_alfred_main.id, car_branch.id} + assert person_alfred_main.id in payloads_by_id + assert payloads_by_id[person_alfred_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_alfred_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["cars"] + assert diff_element.type is DiffElementType.RELATIONSHIP_MANY + assert diff_element.name == "cars" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.ADDED + diff_peers = diff_element.peers + assert len(diff_peers) == 1 + assert diff_peers[0].peer.id == car_branch.id + + assert car_branch.id in payloads_by_id + assert payloads_by_id[car_branch.id].action is DiffAction.ADDED + owner_element = payloads_by_id[car_branch.id].elements["owner"] + assert owner_element.type is DiffElementType.RELATIONSHIP_ONE + assert owner_element.name == "owner" + assert owner_element.branch == branch.name + assert owner_element.action is DiffAction.UPDATED + assert owner_element.peer.previous.id == person_jane_main.id + assert owner_element.peer.new.id == person_alfred_main.id + + +async def test_remove_optional_cardinality_one_rel( + db: InfrahubDatabase, person_john_main, person_jane_main, car_person_schema_with_friend +): + john_main = await NodeManager.get_one(db=db, id=person_john_main.id) + await john_main.best_friend.update(db=db, data=person_jane_main) + await john_main.save(db=db) + branch = await create_branch(db=db, branch_name="branch") + john_branch = await NodeManager.get_one(db=db, branch=branch, id=john_main.id) + await john_branch.best_friend.update(db=db, data=None) + await john_branch.save(db=db) + + differ = await BranchDiffer.init(branch=branch, db=db) + payload_builder = DiffPayloadBuilder(db=db, diff=differ) + + diff_payload = await payload_builder.get_branch_diff_nodes() + + payloads_by_id = {p.id: p for p in diff_payload} + assert set(payloads_by_id.keys()) == {person_john_main.id, person_jane_main.id} + assert payloads_by_id[person_jane_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_jane_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["best_friend"] + assert diff_element.type is DiffElementType.RELATIONSHIP_ONE + assert diff_element.name == "best_friend" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.REMOVED + assert diff_element.peer.previous.id == person_john_main.id + assert diff_element.peer.new is None + assert payloads_by_id[person_john_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_john_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["best_friend"] + assert diff_element.type is DiffElementType.RELATIONSHIP_ONE + assert diff_element.name == "best_friend" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.REMOVED + assert diff_element.peer.previous.id == person_jane_main.id + assert diff_element.peer.new is None + + +async def test_remove_and_add_optional_cardinality_one_rel( + db: InfrahubDatabase, person_john_main, person_jane_main, person_alfred_main, car_person_schema_with_friend +): + john_main = await NodeManager.get_one(db=db, id=person_john_main.id) + await john_main.best_friend.update(db=db, data=person_jane_main) + await john_main.save(db=db) + branch = await create_branch(db=db, branch_name="branch") + john_branch = await NodeManager.get_one(db=db, branch=branch, id=john_main.id) + await john_branch.best_friend.update(db=db, data=None) + await john_branch.save(db=db) + john_branch = await NodeManager.get_one(db=db, branch=branch, id=john_main.id) + await john_branch.best_friend.update(db=db, data=person_alfred_main) + await john_branch.save(db=db) + + differ = await BranchDiffer.init(branch=branch, db=db) + payload_builder = DiffPayloadBuilder(db=db, diff=differ) + + diff_payload = await payload_builder.get_branch_diff_nodes() + + payloads_by_id = {p.id: p for p in diff_payload} + # NOT WORKING + # assert set(payloads_by_id.keys()) == {person_john_main.id, person_alfred_main.id} + assert payloads_by_id[person_john_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_john_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["best_friend"] + assert diff_element.type is DiffElementType.RELATIONSHIP_ONE + assert diff_element.name == "best_friend" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.UPDATED + assert diff_element.peer.previous.id == person_jane_main.id + assert diff_element.peer.new.id == person_alfred_main.id + assert payloads_by_id[person_alfred_main.id].action is DiffAction.UPDATED + diff_elements = payloads_by_id[person_alfred_main.id].elements + assert len(diff_elements) == 1 + diff_element = diff_elements["best_friend"] + assert diff_element.type is DiffElementType.RELATIONSHIP_ONE + assert diff_element.name == "best_friend" + assert diff_element.branch == branch.name + assert diff_element.action is DiffAction.ADDED + assert diff_element.peer.previous is None + assert diff_element.peer.new.id == person_john_main.id diff --git a/backend/tests/unit/core/test_enums.py b/backend/tests/unit/core/test_enums.py index e41b19f3b8..b3d1d3b110 100644 --- a/backend/tests/unit/core/test_enums.py +++ b/backend/tests/unit/core/test_enums.py @@ -10,3 +10,13 @@ def test_generate_python_enum(): enum_blue = enum_class("blue") assert isinstance(enum_blue, enum.Enum) assert {enum.name for enum in enum_class} == {"RED", "BLUE"} + + +def test_generate_python_enum_with_integers(): + enum_class = generate_python_enum(name="DHGroup", options=[2, 5, 14]) + assert isinstance(enum_class, enum.EnumType) + + enum_two = enum_class(2) + assert isinstance(enum_two, enum.Enum) + assert {enum.name for enum in enum_class} == {"2", "5", "14"} + assert {enum.value for enum in enum_class} == {2, 5, 14} diff --git a/backend/tests/unit/core/test_manager_node.py b/backend/tests/unit/core/test_manager_node.py index 570ae22940..3517278940 100644 --- a/backend/tests/unit/core/test_manager_node.py +++ b/backend/tests/unit/core/test_manager_node.py @@ -8,6 +8,7 @@ from infrahub.core.query.node import NodeToProcess from infrahub.core.registry import registry from infrahub.core.schema import NodeSchema +from infrahub.core.schema_manager import SchemaBranch from infrahub.core.timestamp import Timestamp from infrahub.database import InfrahubDatabase @@ -187,23 +188,52 @@ async def test_get_one_relationship_with_flag_property(db: InfrahubDatabase, def async def test_get_one_by_id_or_default_filter( db: InfrahubDatabase, default_branch: Branch, - criticality_schema: NodeSchema, + criticality_schema: SchemaBranch, criticality_low: Node, criticality_medium: Node, ): node1 = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=criticality_low.id, schema_name=criticality_schema.kind + db=db, id=criticality_low.id, kind=criticality_schema.kind ) assert isinstance(node1, Node) assert node1.id == criticality_low.id node2 = await NodeManager.get_one_by_id_or_default_filter( - db=db, id=criticality_low.name.value, schema_name=criticality_schema.kind + db=db, id=criticality_low.name.value, kind=criticality_schema.kind ) assert isinstance(node2, Node) assert node2.id == criticality_low.id +async def test_get_one_by_hfid( + db: InfrahubDatabase, + default_branch: Branch, + animal_person_schema: SchemaBranch, +): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + person2 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person2.new(db=db, name="Jim") + await person2.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + dog2 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog2.new(db=db, name="Bella", breed="French Bulldog", owner=person1) + await dog2.save(db=db) + + node1 = await NodeManager.get_one_by_hfid(db=db, hfid=["Jack", "Rocky"], kind=dog_schema.kind) + assert isinstance(node1, Node) + assert node1.id == dog1.id + + async def test_get_many(db: InfrahubDatabase, default_branch: Branch, criticality_low, criticality_medium): nodes = await NodeManager.get_many(db=db, ids=[criticality_low.id, criticality_medium.id]) assert len(nodes) == 2 @@ -480,27 +510,6 @@ async def test_get_one_global(db: InfrahubDatabase, default_branch: Branch, base obj2 = await NodeManager.get_one(db=db, id="c1", branch=branch1) - assert obj2.id == "c1" - assert obj2.db_id - assert obj2.name.value == "volt" - assert obj2.nbr_seats.value == 4 - assert obj2.color.value == "#444444" - assert obj2.is_electric.value is True - - -async def test_get_one_global_isolated(db: InfrahubDatabase, default_branch: Branch, base_dataset_12): - branch1 = await registry.get_branch(db=db, branch="branch1") - branch1.is_isolated = True - - obj1 = await NodeManager.get_one(db=db, id="p1", branch=branch1) - - assert obj1.id == "p1" - assert obj1.db_id - assert obj1.name.value == "John Doe" - assert obj1.height.value is None - - obj2 = await NodeManager.get_one(db=db, id="c1", branch=branch1) - assert obj2.id == "c1" assert obj2.db_id assert obj2.name.value == "accord" diff --git a/backend/tests/unit/core/test_node.py b/backend/tests/unit/core/test_node.py index 7535842a16..6c3c07f15a 100644 --- a/backend/tests/unit/core/test_node.py +++ b/backend/tests/unit/core/test_node.py @@ -225,6 +225,49 @@ async def test_render_display_label(db: InfrahubDatabase, default_branch: Branch assert await obj.render_display_label(db=db) == f"TestDisplay(ID: {obj.id})[NEW]" +async def test_get_hfid(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + assert await dog1.get_hfid(db=db) == ["Jack", "Rocky"] + assert await dog1.get_hfid(db=db, include_kind=True) == ["TestDog", "Jack", "Rocky"] + + assert await dog1.get_hfid_as_string(db=db) == "Jack__Rocky" + assert await dog1.get_hfid_as_string(db=db, include_kind=True) == "TestDog__Jack__Rocky" + + +async def test_get_path_value(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + assert await dog1.get_path_value(db=db, path="name__value") == "Rocky" + assert await dog1.get_path_value(db=db, path="owner__name__value") == "Jack" + + with pytest.raises(ValueError) as exc: + assert await person1.get_path_value(db=db, path="animals__name__value") + assert "path on a relationship of cardinality many" in str(exc.value) + + with pytest.raises(ValueError) as exc: + assert await dog1.get_path_value(db=db, path="name") + assert "value of a path without property" in str(exc.value) + + async def test_node_init_with_single_relationship(db: InfrahubDatabase, default_branch: Branch, car_person_schema): car = registry.schema.get(name="TestCar") person = registry.schema.get(name="TestPerson") diff --git a/backend/tests/unit/core/test_node_get_list_query.py b/backend/tests/unit/core/test_node_get_list_query.py index 8421f621f1..7e073000cf 100644 --- a/backend/tests/unit/core/test_node_get_list_query.py +++ b/backend/tests/unit/core/test_node_get_list_query.py @@ -222,7 +222,7 @@ async def test_query_NodeGetListQuery_order_by( async def test_query_NodeGetListQuery_order_by_optional_relationship_nulls( - db: InfrahubDatabase, branch: Branch, car_accord_main, car_camry_main, car_volt_main, car_yaris_main + db: InfrahubDatabase, car_accord_main, car_camry_main, car_volt_main, car_yaris_main, branch: Branch ): schema = registry.schema.get(name="TestCar", branch=branch, duplicate=False) schema.relationships.append( @@ -319,10 +319,10 @@ async def test_query_NodeGetListQuery_filter_with_profiles( db: InfrahubDatabase, person_john_main, person_jim_main, person_albert_main, person_alfred_main, branch: Branch ): profile_schema = registry.schema.get("ProfileTestPerson", branch=branch, duplicate=False) - person_profile = await Node.init(db=db, schema=profile_schema) + person_profile = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile.new(db=db, profile_name="person_profile_1", height=172, profile_priority=1001) await person_profile.save(db=db) - person_profile_2 = await Node.init(db=db, schema=profile_schema) + person_profile_2 = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile_2.new(db=db, profile_name="person_profile_2", height=177, profile_priority=1002) await person_profile_2.save(db=db) @@ -357,10 +357,10 @@ async def test_query_NodeGetListQuery_order_with_profiles( db: InfrahubDatabase, car_camry_main, car_accord_main, car_volt_main, branch: Branch ): profile_schema = registry.schema.get("ProfileTestCar", branch=branch, duplicate=False) - car_profile_black = await Node.init(db=db, schema=profile_schema) + car_profile_black = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_black.new(db=db, profile_name="car_profile_black", color="#000000", profile_priority=1001) await car_profile_black.save(db=db) - car_profile_white = await Node.init(db=db, schema=profile_schema) + car_profile_white = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_white.new(db=db, profile_name="car_profile_white", color="#ffffff", profile_priority=1002) await car_profile_white.save(db=db) @@ -385,29 +385,29 @@ async def test_query_NodeGetListQuery_order_with_profiles( async def test_query_NodeGetListQuery_with_profiles_deleted( db: InfrahubDatabase, + default_branch: Branch, car_camry_main, car_accord_main, car_volt_main, branch: Branch, - default_branch: Branch, ): profile_schema = registry.schema.get("ProfileTestCar", branch=branch, duplicate=False) - car_profile_black = await Node.init(db=db, schema=profile_schema) + car_profile_black = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_black.new(db=db, profile_name="car_profile_black", color="#000000", profile_priority=1001) await car_profile_black.save(db=db) - car_profile_white = await Node.init(db=db, schema=profile_schema) + car_profile_white = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_white.new(db=db, profile_name="car_profile_white", color="#ffffff", profile_priority=1002) await car_profile_white.save(db=db) await branch.rebase(db=db) car_schema = registry.schema.get("TestCar", branch=branch, duplicate=False) - car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=branch) await car.profiles.update(data=[car_profile_white], db=db) await car.save(db=db) - car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=branch) await car.profiles.update(data=[car_profile_black], db=db) await car.save(db=db) - car = await NodeManager.get_one(db=db, id=car_volt_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_volt_main.id, branch=branch) await car.profiles.update(data=[car_profile_black, car_profile_white], db=db) await car.save(db=db) @@ -527,23 +527,22 @@ async def test_query_NodeGetListQuery_updated_profile_attributes_nulled_on_branc car_accord_main, car_volt_main, branch: Branch, - default_branch: Branch, ): profile_schema = registry.schema.get("ProfileTestCar", branch=branch, duplicate=False) - car_profile_black = await Node.init(db=db, schema=profile_schema) + car_profile_black = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_black.new(db=db, profile_name="car_profile_black", color="#000000", profile_priority=1001) await car_profile_black.save(db=db) - car_profile_white = await Node.init(db=db, schema=profile_schema) + car_profile_white = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile_white.new(db=db, profile_name="car_profile_white", color="#ffffff", profile_priority=1002) await car_profile_white.save(db=db) car_schema = registry.schema.get("TestCar", branch=branch, duplicate=False) - car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=branch) await car.profiles.update(data=[car_profile_white], db=db) await car.save(db=db) - car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=branch) await car.profiles.update(data=[car_profile_black], db=db) await car.save(db=db) - car = await NodeManager.get_one(db=db, id=car_volt_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_volt_main.id, branch=branch) await car.profiles.update(data=[car_profile_black, car_profile_white], db=db) await car.save(db=db) await branch.rebase(db=db) @@ -568,13 +567,12 @@ async def test_query_NodeGetListQuery_multiple_profiles_same_priority_filter_and car_camry_main, car_accord_main, branch: Branch, - default_branch: Branch, ): profile_schema = registry.schema.get("ProfileTestCar", branch=branch, duplicate=False) profiles_group_1 = [] expected_profile_1 = None for i in range(10): - car_profile = await Node.init(db=db, schema=profile_schema) + car_profile = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile.new( db=db, profile_name=f"car_profile_{i}", color=f"#{randint(100000, 499999)}", profile_priority=1000 ) @@ -585,7 +583,7 @@ async def test_query_NodeGetListQuery_multiple_profiles_same_priority_filter_and profiles_group_2 = [] expected_profile_2 = None for i in range(10, 20): - car_profile = await Node.init(db=db, schema=profile_schema) + car_profile = await Node.init(db=db, schema=profile_schema, branch=branch) await car_profile.new( db=db, profile_name=f"car_profile_{i}", color=f"#{randint(500000, 999999)}", profile_priority=1000 ) @@ -595,10 +593,10 @@ async def test_query_NodeGetListQuery_multiple_profiles_same_priority_filter_and profiles_group_2.append(car_profile) car_schema = registry.schema.get("TestCar", branch=branch, duplicate=False) car_schema.order_by = ["color__value"] - car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_camry_main.id, branch=branch) await car.profiles.update(data=profiles_group_1, db=db) await car.save(db=db) - car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=default_branch) + car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=branch) await car.profiles.update(data=profiles_group_2, db=db) await car.save(db=db) diff --git a/backend/tests/unit/core/test_node_query.py b/backend/tests/unit/core/test_node_query.py index a6f8dea9fd..622c1ca0b0 100644 --- a/backend/tests/unit/core/test_node_query.py +++ b/backend/tests/unit/core/test_node_query.py @@ -106,10 +106,10 @@ async def test_query_NodeListGetInfoQuery_with_profiles( db: InfrahubDatabase, person_john_main, person_jim_main, person_albert_main, person_alfred_main, branch: Branch ): profile_schema = registry.schema.get("ProfileTestPerson", branch=branch) - person_profile = await Node.init(db=db, schema=profile_schema) + person_profile = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile.new(db=db, profile_name="person_profile_1", height=172, profile_priority=1001) await person_profile.save(db=db) - person_profile_2 = await Node.init(db=db, schema=profile_schema) + person_profile_2 = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile_2.new(db=db, profile_name="person_profile_2", height=177, profile_priority=1002) await person_profile_2.save(db=db) person = await NodeManager.get_one(db=db, id=person_john_main.id, branch=branch) @@ -120,7 +120,7 @@ async def test_query_NodeListGetInfoQuery_with_profiles( query = await NodeListGetInfoQuery.init(db=db, branch=branch, ids=ids) await query.execute(db=db) - async for node_to_process in query.get_nodes(duplicate=False): + async for node_to_process in query.get_nodes(db=db): if node_to_process.node_uuid != person_john_main.id: assert node_to_process.profile_uuids == [] else: @@ -131,10 +131,10 @@ async def test_query_NodeListGetInfoQuery_with_profiles_some_deleted( db: InfrahubDatabase, person_john_main, person_jim_main, person_albert_main, person_alfred_main, branch: Branch ): profile_schema = registry.schema.get("ProfileTestPerson", branch=branch) - person_profile = await Node.init(db=db, schema=profile_schema) + person_profile = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile.new(db=db, profile_name="person_profile_1", height=172, profile_priority=1001) await person_profile.save(db=db) - person_profile_2 = await Node.init(db=db, schema=profile_schema) + person_profile_2 = await Node.init(db=db, schema=profile_schema, branch=branch) await person_profile_2.new(db=db, profile_name="person_profile_2", height=177, profile_priority=1002) await person_profile_2.save(db=db) for person_id in (person_albert_main.id, person_alfred_main.id, person_john_main.id): @@ -149,7 +149,7 @@ async def test_query_NodeListGetInfoQuery_with_profiles_some_deleted( query = await NodeListGetInfoQuery.init(db=db, branch=branch, ids=ids) await query.execute(db=db) - queried_nodes = [node async for node in query.get_nodes(duplicate=False)] + queried_nodes = [node async for node in query.get_nodes(db=db)] assert {qn.node_uuid for qn in queried_nodes} == { person_john_main.id, person_jim_main.id, @@ -190,7 +190,7 @@ async def test_query_NodeListGetInfoQuery_renamed( ids = [person_john_main.id, person_jim_main.id, person_albert_main.id] query = await NodeListGetInfoQuery.init(db=db, branch=branch, ids=ids) await query.execute(db=db) - results = [node.labels async for node in query.get_nodes()] + results = [node.labels async for node in query.get_nodes(db=db)] for result in results: assert sorted(result) == ["CoreNode", "Node", "Test2NewPerson"] @@ -208,19 +208,8 @@ async def test_query_NodeListGetAttributeQuery_all_fields(db: InfrahubDatabase, assert len(query.get_attributes_group_by_node()["c1"].attrs) == 4 assert len(query.get_attributes_group_by_node()["c2"].attrs) == 4 - # Query all the nodes in branch1, c1, c2 and c3 present - # Expect 15 attributes because each node has 4 but c1at2 has a value both in Main and Branch1 - query = await NodeListGetAttributeQuery.init(db=db, ids=["c1", "c2", "c3"], branch=branch1) - await query.execute(db=db) - assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c2", "c3"] - assert len(list(query.get_results())) == 15 - assert len(query.get_attributes_group_by_node()["c1"].attrs) == 4 - assert len(query.get_attributes_group_by_node()["c2"].attrs) == 4 - assert len(query.get_attributes_group_by_node()["c3"].attrs) == 4 - - # Query all the nodes in branch1 in isolated mode, only c1 and c3 present + # Query all the nodes in branch1, only c1 and c3 present # Expect 9 attributes because each node has 4 but c1at2 has a value both in Main and Branch1 - branch1.is_isolated = True query = await NodeListGetAttributeQuery.init(db=db, ids=["c1", "c2", "c3"], branch=branch1) await query.execute(db=db) assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c3"] @@ -280,17 +269,16 @@ async def test_query_NodeListGetAttributeQuery(db: InfrahubDatabase, base_datase assert len(query.get_attributes_group_by_node()["c2"].attrs) == 2 assert len(list(query.get_results())) == 4 - # Query all the nodes in branch1: c1, c2 and c3 present - # Expect 6 attributes because each node has 1 but c1at2 has its value and its protected flag defined both in Main and Branch1 + # Query all the nodes in branch1: c1 and c3 present + # Expect 5 attributes because each node has 1 but c1at2 has its value and its protected flag defined both in Main and Branch1 query = await NodeListGetAttributeQuery.init( db=db, ids=["c1", "c2", "c3"], branch=branch1, fields={"nbr_seats": True} ) await query.execute(db=db) - assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c2", "c3"] + assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c3"] assert len(query.get_attributes_group_by_node()["c1"].attrs) == 1 - assert len(query.get_attributes_group_by_node()["c2"].attrs) == 1 assert len(query.get_attributes_group_by_node()["c3"].attrs) == 1 - assert len(list(query.get_results())) == 6 + assert len(list(query.get_results())) == 5 # Query c1 in branch1 # Expect 4 attributes because c1at2 has its value and its protected flag defined both in Main and Branch1 @@ -300,9 +288,8 @@ async def test_query_NodeListGetAttributeQuery(db: InfrahubDatabase, base_datase assert len(list(query.get_results())) == 4 assert query.results[0].branch_score != query.results[1].branch_score - # Query all the nodes in branch1 in isolated mode, only c1 and c3 present + # Query all the nodes in branch1, only c1 and c3 present # Expect 4 attributes because c1at2 has its value and its protected flag defined both in Main and Branch1 - branch1.is_isolated = True query = await NodeListGetAttributeQuery.init(db=db, ids=["c1"], branch=branch1, fields={"nbr_seats": True}) await query.execute(db=db) assert sorted(query.get_attributes_group_by_node().keys()) == ["c1"] @@ -338,13 +325,12 @@ async def test_query_NodeListGetAttributeQuery_deleted(db: InfrahubDatabase, bas assert len(query.get_attributes_group_by_node()["c1"].attrs) == 4 assert len(query.get_attributes_group_by_node()["c2"].attrs) == 4 - # Query all the nodes in branch1: c1, c2 and c3 present + # Query all the nodes in branch1: c1 and c3 present # Expect 6 attributes because each node has 1 but c1at2 has its value and its protected flag defined both in Main and Branch1 query = await NodeListGetAttributeQuery.init(db=db, ids=["c1", "c2", "c3"], branch=branch1) await query.execute(db=db) - assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c2", "c3"] + assert sorted(query.get_attributes_group_by_node().keys()) == ["c1", "c3"] assert len(query.get_attributes_group_by_node()["c1"].attrs) == 3 - assert len(query.get_attributes_group_by_node()["c2"].attrs) == 3 assert len(query.get_attributes_group_by_node()["c3"].attrs) == 3 # Query c1 in branch1 diff --git a/backend/tests/unit/core/test_query_utils.py b/backend/tests/unit/core/test_query_utils.py index e7bd09b93b..bc745ec589 100644 --- a/backend/tests/unit/core/test_query_utils.py +++ b/backend/tests/unit/core/test_query_utils.py @@ -1,12 +1,13 @@ from infrahub.core.constants import InfrahubKind from infrahub.core.query.utils import find_node_schema +from infrahub.database import InfrahubDatabase -async def test_find_node_schema(neo4j_factory, group_schema, branch): +async def test_find_node_schema(db: InfrahubDatabase, neo4j_factory, group_schema, branch): n1 = neo4j_factory.hydrate_node(111, {"Node", "Group", InfrahubKind.STANDARDGROUP}, {"uuid": "n1"}, "111") - schema = find_node_schema(node=n1, branch=branch, duplicate=True) + schema = find_node_schema(db=db, node=n1, branch=branch, duplicate=True) assert schema.kind == InfrahubKind.STANDARDGROUP n2 = neo4j_factory.hydrate_node(122, {"Node", InfrahubKind.GENERICGROUP}, {"uuid": "n1"}, "122") - schema = find_node_schema(node=n2, branch=branch, duplicate=False) + schema = find_node_schema(db=db, node=n2, branch=branch, duplicate=False) assert schema is None diff --git a/backend/tests/unit/core/test_relationship.py b/backend/tests/unit/core/test_relationship.py index c0a316569e..c07fb087de 100644 --- a/backend/tests/unit/core/test_relationship.py +++ b/backend/tests/unit/core/test_relationship.py @@ -3,10 +3,13 @@ from infrahub import exceptions as infra_execs from infrahub.core import registry from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind from infrahub.core.manager import NodeManager from infrahub.core.node import Node +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool from infrahub.core.query.relationship import RelationshipGetPeerQuery from infrahub.core.relationship.model import Relationship, RelationshipValidatorList +from infrahub.core.schema_manager import SchemaBranch from infrahub.core.timestamp import Timestamp from infrahub.database import InfrahubDatabase @@ -173,7 +176,7 @@ async def test_relationship_hash( async def test_relationship_validate_one_init_empty_success(): - result = RelationshipValidatorList(min_count=1, max_count=1) + result = RelationshipValidatorList(name="name", min_count=1, max_count=1) # Assert that the list is empty assert not result @@ -183,7 +186,7 @@ async def test_relationship_validate_one_init_empty_success(): async def test_relationship_validate_many_init_empty_success(): - result = RelationshipValidatorList(min_count=100, max_count=100) + result = RelationshipValidatorList(name="name", min_count=100, max_count=100) # Assert that the list is empty assert not result @@ -192,7 +195,7 @@ async def test_relationship_validate_many_init_empty_success(): async def test_relationship_validate_empty_init_success(): - result = RelationshipValidatorList() + result = RelationshipValidatorList(name="name") # Assert that the list is empty assert not result @@ -203,7 +206,7 @@ async def test_relationship_validate_empty_init_success(): async def test_relationship_validate_many_init_empty_raise_min_ge_max(): with pytest.raises(infra_execs.ValidationError): - RelationshipValidatorList(min_count=200, max_count=100) + RelationshipValidatorList(name="name", min_count=200, max_count=100) async def test_relationship_validate_init_below_min_raise(db: InfrahubDatabase, person_jack_main: Node, branch: Branch): @@ -213,7 +216,7 @@ async def test_relationship_validate_init_below_min_raise(db: InfrahubDatabase, rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) with pytest.raises(infra_execs.ValidationError, match="max_count must be greater than min_count"): - RelationshipValidatorList(rel_jack, min_count=3, max_count=0) + RelationshipValidatorList(rel_jack, name="name", min_count=3, max_count=0) async def test_relationship_validate_init_above_max_raise(db: InfrahubDatabase, person_jack_main: None, branch: Branch): @@ -225,7 +228,7 @@ async def test_relationship_validate_init_above_max_raise(db: InfrahubDatabase, rel_3 = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) with pytest.raises(infra_execs.ValidationError, match="Too many relationships, max 2"): - RelationshipValidatorList(rel_1, rel_2, rel_3, min_count=0, max_count=2) + RelationshipValidatorList(rel_1, rel_2, rel_3, name="name", min_count=0, max_count=2) async def test_relationship_validate_one_success(db: InfrahubDatabase, person_jack_main: Node, branch: Branch): @@ -234,7 +237,7 @@ async def test_relationship_validate_one_success(db: InfrahubDatabase, person_ja rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) - result = RelationshipValidatorList(rel_jack, min_count=1, max_count=1) + result = RelationshipValidatorList(rel_jack, name="name", min_count=1, max_count=1) result.append(rel_jack) assert len(result) == 1 @@ -253,7 +256,7 @@ async def test_relationship_validate_one_append_raise(db: InfrahubDatabase, pers rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) rel_doe = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) - result = RelationshipValidatorList(min_count=1, max_count=1) + result = RelationshipValidatorList(name="name", min_count=1, max_count=1) assert len(result) == 0 assert result._relationships_count == 0 @@ -274,7 +277,7 @@ async def test_relationship_validate_one_append_extend_duplicate( rel_schema = person_schema.get_relationship("tags") rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) - result = RelationshipValidatorList(rel_jack, min_count=1, max_count=1) + result = RelationshipValidatorList(rel_jack, name="name", min_count=1, max_count=1) # RelationshipValidatorList should not append/extend a duplicate relationship result.append(rel_jack) @@ -294,7 +297,7 @@ async def test_relationship_validate_one_extend_raise(db: InfrahubDatabase, pers rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) - result = RelationshipValidatorList(rel_jack, min_count=1, max_count=1) + result = RelationshipValidatorList(rel_jack, name="name", min_count=1, max_count=1) with pytest.raises(infra_execs.ValidationError, match="Too many relationships, max 1"): rel_albert = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) @@ -307,7 +310,7 @@ async def test_relationship_validate_one_remove_raise(db: InfrahubDatabase, pers rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) - result = RelationshipValidatorList(rel_jack, min_count=1, max_count=1) + result = RelationshipValidatorList(rel_jack, name="name", min_count=1, max_count=1) expected_msg = "Too few relationships, min 1" with pytest.raises(infra_execs.ValidationError, match=expected_msg): @@ -330,7 +333,7 @@ async def test_relationship_validate_many_no_limit_success( rel_doe_one = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) rel_doe_two = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) - result = RelationshipValidatorList(rel_jack, rel_doe_one, rel_doe_two, min_count=0, max_count=0) + result = RelationshipValidatorList(rel_jack, rel_doe_one, rel_doe_two, name="name", min_count=0, max_count=0) assert result[0] == rel_jack assert result[1] == rel_doe_one @@ -345,7 +348,7 @@ async def test_relationship_validate_many_no_limit_duplicate_success( rel = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) - result = RelationshipValidatorList(rel, min_count=rel_schema.min_count, max_count=rel_schema.max_count) + result = RelationshipValidatorList(rel, name="name", min_count=rel_schema.min_count, max_count=rel_schema.max_count) for _ in range(5): result.append(rel) @@ -363,7 +366,7 @@ async def test_relationship_validate_many_above_max_count_raise( rel_doe_one = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) rel_doe_two = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) - result = RelationshipValidatorList(min_count=2, max_count=2) + result = RelationshipValidatorList(name="name", min_count=2, max_count=2) result.extend([rel_jack, rel_doe_one]) assert result[0] == rel_jack @@ -388,7 +391,7 @@ async def test_relationship_validate_many_less_than_min_raise( rel_jack = Relationship(schema=rel_schema, branch=branch, node=person_jack_main) rel_doe_one = Relationship(schema=rel_schema, branch=branch, node=Node(person_schema, branch, at="now")) - result = RelationshipValidatorList(rel_jack, rel_doe_one, min_count=2, max_count=2) + result = RelationshipValidatorList(rel_jack, rel_doe_one, name="name", min_count=2, max_count=2) assert result[0] == rel_jack assert result[1] == rel_doe_one @@ -402,3 +405,35 @@ async def test_relationship_validate_many_less_than_min_raise( result.remove(rel_doe_one) with pytest.raises(infra_execs.ValidationError, match=expected_msg): del result[0] + + +async def test_relationship_assign_from_pool( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + mandatory_prefix_schema = registry.schema.get_node_schema(name="TestMandatoryPrefix", branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_prefix_length=24, + default_prefix_type="IpamIPPrefix", + resources=[net140], + ip_namespace=ns1, + ) + await pool.save(db=db) + + obj = await Node.init(schema=mandatory_prefix_schema, db=db, branch=default_branch) + await obj.new(db=db, name={"value": "site1"}, prefix={"from_pool": {"id": pool.id}}) + await obj.save(db=db) + + assert await obj.prefix.get_peer(db=db) diff --git a/backend/tests/unit/core/test_schema.py b/backend/tests/unit/core/test_schema.py index d96fb28338..77bd09e2b8 100644 --- a/backend/tests/unit/core/test_schema.py +++ b/backend/tests/unit/core/test_schema.py @@ -109,11 +109,6 @@ async def test_node_schema_generate_fields_for_display_label(): schema = NodeSchema(**SCHEMA) assert schema.generate_fields_for_display_label() == {"level": {"value": None}, "name": {"value": None}} - SCHEMA["display_labels"] = ["name__value__third"] - schema = NodeSchema(**SCHEMA) - with pytest.raises(ValueError): - schema.generate_fields_for_display_label() - async def test_rel_schema_query_filter(db: InfrahubDatabase, default_branch, car_person_schema): person = registry.schema.get(name="TestPerson") diff --git a/backend/tests/unit/core/test_schema_parse_attribute_path.py b/backend/tests/unit/core/test_schema_parse_schema_path.py similarity index 58% rename from backend/tests/unit/core/test_schema_parse_attribute_path.py rename to backend/tests/unit/core/test_schema_parse_schema_path.py index c5376c6144..58e3146f45 100644 --- a/backend/tests/unit/core/test_schema_parse_attribute_path.py +++ b/backend/tests/unit/core/test_schema_parse_schema_path.py @@ -2,64 +2,62 @@ from infrahub.core import registry from infrahub.core.schema import AttributePathParsingError, SchemaAttributePath +from infrahub.core.schema_manager import SchemaBranch -class TestSchemaParseAttributePath: +class TestSchemaParseSchemaPath: def test_property_only_is_invalid(self, car_person_schema): car_schema = registry.schema.get(name="TestCar") with pytest.raises(AttributePathParsingError, match=r"value is invalid on schema"): - car_schema.parse_attribute_path("value") + car_schema.parse_schema_path(path="value") @pytest.mark.parametrize("bad_path", ["blork", "person", "__", "__dunder__"]) def test_invalid_paths(self, car_person_schema, bad_path): car_schema = registry.schema.get(name="TestCar") with pytest.raises(AttributePathParsingError, match=rf"{bad_path} is invalid on schema"): - car_schema.parse_attribute_path(bad_path) + car_schema.parse_schema_path(path=bad_path) def test_invalid_attribute_of_relationship_path(self, car_person_schema): car_schema = registry.schema.get(name="TestCar") with pytest.raises(AttributePathParsingError, match=r"blork is not a valid attribute of TestPerson"): - car_schema.parse_attribute_path("owner__blork") + car_schema.parse_schema_path(path="owner__blork", schema=car_person_schema) def test_invalid_property_of_attribute_path(self, car_person_schema): car_schema = registry.schema.get(name="TestCar") with pytest.raises(AttributePathParsingError, match=r"blork is not a valid property of nbr_seats"): - car_schema.parse_attribute_path("nbr_seats__blork") + car_schema.parse_schema_path(path="nbr_seats__blork") - def test_invalid_path_with_map_override(self, car_person_schema_unregistered): - schema_map = { - sch.kind: sch for sch in car_person_schema_unregistered.nodes + car_person_schema_unregistered.generics - } - car_schema = schema_map.get("TestCar") + def test_invalid_path_with_map_override(self, car_person_schema: SchemaBranch): + car_schema = car_person_schema.get("TestCar") with pytest.raises(AttributePathParsingError, match=r"blork is not a valid attribute of TestPerson"): - car_schema.parse_attribute_path("owner__blork", schema_map_override=schema_map) + car_schema.parse_schema_path(path="owner__blork", schema=car_person_schema) def test_attribute_only_is_valid(self, car_person_schema): car_schema = registry.schema.get(name="TestCar") - schema_path = car_schema.parse_attribute_path("nbr_seats") + schema_path = car_schema.parse_schema_path(path="nbr_seats") assert schema_path == SchemaAttributePath(attribute_schema=car_schema.get_attribute("nbr_seats")) - def test_relationship_only_is_valid(self, car_person_schema): + def test_relationship_only_is_valid(self, car_person_schema: SchemaBranch): car_schema = registry.schema.get(name="TestCar") - schema_path = car_schema.parse_attribute_path("owner") + schema_path = car_schema.parse_schema_path(path="owner", schema=car_person_schema) assert schema_path == SchemaAttributePath( relationship_schema=car_schema.get_relationship("owner"), related_schema=registry.schema.get(name="TestPerson"), ) - def test_relationship_and_attribute_is_valid(self, car_person_schema): + def test_relationship_and_attribute_is_valid(self, car_person_schema: SchemaBranch): car_schema = registry.schema.get(name="TestCar") - schema_path = car_schema.parse_attribute_path("owner__name") + schema_path = car_schema.parse_schema_path(path="owner__name", schema=car_person_schema) owner_schema = registry.schema.get(name="TestPerson") assert schema_path == SchemaAttributePath( @@ -68,27 +66,11 @@ def test_relationship_and_attribute_is_valid(self, car_person_schema): attribute_schema=owner_schema.get_attribute("name"), ) - def test_relationship_attribute_and_property_is_valid(self, car_person_schema): - car_schema = registry.schema.get(name="TestCar") - - schema_path = car_schema.parse_attribute_path("owner__name__value") - - owner_schema = registry.schema.get(name="TestPerson") - assert schema_path == SchemaAttributePath( - relationship_schema=car_schema.get_relationship("owner"), - related_schema=owner_schema, - attribute_schema=owner_schema.get_attribute("name"), - attribute_property_name="value", - ) - - def test_relationship_attribute_and_property_is_valid_map_override(self, car_person_schema_unregistered): - schema_map = { - sch.kind: sch for sch in car_person_schema_unregistered.nodes + car_person_schema_unregistered.generics - } - car_schema = schema_map.get("TestCar") - owner_schema = schema_map.get("TestPerson") + def test_relationship_attribute_and_property_is_valid(self, car_person_schema: SchemaBranch): + car_schema = car_person_schema.get("TestCar") + owner_schema = car_person_schema.get("TestPerson") - schema_path = car_schema.parse_attribute_path("owner__name__value", schema_map_override=schema_map) + schema_path = car_schema.parse_schema_path(path="owner__name__value", schema=car_person_schema) assert schema_path == SchemaAttributePath( relationship_schema=car_schema.get_relationship("owner"), diff --git a/backend/tests/unit/git/conftest.py b/backend/tests/unit/git/conftest.py index 0c56b37fb8..c72c5d6e02 100644 --- a/backend/tests/unit/git/conftest.py +++ b/backend/tests/unit/git/conftest.py @@ -644,11 +644,9 @@ async def mock_schema_query_02(helper, httpx_mock: HTTPXMock) -> HTTPXMock: async def mock_check_create(helper, httpx_mock: HTTPXMock) -> HTTPXMock: response = { "data": { - InfrahubKind.CHECKDEFINITION: { + f"{InfrahubKind.CHECKDEFINITION}Create": { "ok": True, - "object": { - "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", - }, + "object": {"id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"}, } } } diff --git a/backend/tests/unit/graphql/mutations/test_branch.py b/backend/tests/unit/graphql/mutations/test_branch.py index 5e94511773..32650624f3 100644 --- a/backend/tests/unit/graphql/mutations/test_branch.py +++ b/backend/tests/unit/graphql/mutations/test_branch.py @@ -453,88 +453,6 @@ async def test_branch_update_description(db: InfrahubDatabase, base_dataset_02): assert branch4_updated.description == "testing" -async def test_branch_update_isolated(db: InfrahubDatabase, base_dataset_02): - branch4 = await create_branch(branch_name="branch4", db=db) - - query = """ - mutation($isolated: Boolean!) { - BranchUpdate( - data: { - name: "branch4", - is_isolated: $isolated - } - ) { - ok - } - } - """ - gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch4) - result = await graphql( - schema=gql_params.schema, - source=query, - context_value=gql_params.context, - root_value=None, - variable_values={"isolated": True}, - ) - - assert result.errors is None - assert result.data - assert result.data["BranchUpdate"]["ok"] is True - - branch4_updated = await Branch.get_by_name(db=db, name="branch4") - assert branch4_updated.is_isolated is True - - # Change it False - gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch4) - result = await graphql( - schema=gql_params.schema, - source=query, - context_value=gql_params.context, - root_value=None, - variable_values={"isolated": False}, - ) - - assert result.errors is None - assert result.data - assert result.data["BranchUpdate"]["ok"] is True - - branch4_updated2 = await Branch.get_by_name(db=db, name="branch4") - assert branch4_updated2.is_isolated is False - - -async def test_branch_update_isolated_schema_change(db: InfrahubDatabase, default_branch: Branch, base_dataset_02): - default_branch.update_schema_hash() - - branch4 = await create_branch(branch_name="branch4", db=db, isolated=True) - # Update the hash to simulate a schema change - branch4.schema_hash.main = "f190a8a7f435833e9e15521b8495aaaa" - await branch4.save(db=db) - - query = """ - mutation($isolated: Boolean!) { - BranchUpdate( - data: { - name: "branch4", - is_isolated: $isolated - } - ) { - ok - } - } - """ - gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=branch4) - result = await graphql( - schema=gql_params.schema, - source=query, - context_value=gql_params.context, - root_value=None, - variable_values={"isolated": False}, - ) - - assert len(result.errors) == 1 - assert "Can't convert branch4 to non-isolated mode" in result.errors[0].message - - async def test_branch_merge(db: InfrahubDatabase, base_dataset_02, register_core_models_schema, session_admin): branch1 = await Branch.get_by_name(db=db, name="branch1") diff --git a/backend/tests/unit/graphql/mutations/test_resource_manager.py b/backend/tests/unit/graphql/mutations/test_resource_manager.py new file mode 100644 index 0000000000..bbc928d96d --- /dev/null +++ b/backend/tests/unit/graphql/mutations/test_resource_manager.py @@ -0,0 +1,494 @@ +import pytest +from graphql import graphql + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.node import Node +from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase +from infrahub.graphql import prepare_graphql_params + + +@pytest.fixture +async def prefix_pool_01( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_prefix_length=24, + default_prefix_type="IpamIPPrefix", + resources=[net140], + ip_namespace=ns1, + ) + await pool.save(db=db) + + ip_dataset_prefix_v4["pool"] = pool + + return ip_dataset_prefix_v4 + + +async def test_create_object_and_assign_prefix_from_pool(db: InfrahubDatabase, default_branch: Branch, prefix_pool_01): + pool = prefix_pool_01["pool"] + + query = ( + """ + mutation { + TestMandatoryPrefixCreate(data: { + name: { value: "site1" } + prefix: { + from_pool: { + id: "%s" + } + } + }) { + ok + object { + name { + value + } + prefix { + node { + prefix { + value + } + } + properties { + source { + id + } + } + } + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["TestMandatoryPrefixCreate"]["ok"] + assert result.data["TestMandatoryPrefixCreate"]["object"] == { + "name": {"value": "site1"}, + "prefix": { + "node": {"prefix": {"value": "10.10.0.0/24"}}, + "properties": { + "source": {"id": pool.id}, + }, + }, + } + + +async def test_update_object_and_assign_prefix_from_pool(db: InfrahubDatabase, default_branch: Branch, prefix_pool_01): + pool = prefix_pool_01["pool"] + net142 = prefix_pool_01["net142"] + + schema = registry.schema.get_node_schema(name="TestMandatoryPrefix", branch=default_branch) + + obj = await Node.init(db=db, schema=schema, branch=default_branch) + await obj.new(db=db, name="site1", prefix=net142) + await obj.save(db=db) + + query = """ + mutation { + TestMandatoryPrefixUpdate(data: { + id: "%s" + prefix: { + from_pool: { + id: "%s" + } + } + }) { + ok + object { + name { + value + } + prefix { + node { + prefix { + value + } + } + properties { + source { + id + } + } + } + } + } + } + """ % (obj.id, pool.id) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["TestMandatoryPrefixUpdate"]["ok"] + assert result.data["TestMandatoryPrefixUpdate"]["object"] == { + "name": {"value": "site1"}, + "prefix": { + "node": {"prefix": {"value": "10.10.0.0/24"}}, + "properties": { + "source": {"id": pool.id}, + }, + }, + } + + +async def test_create_object_and_assign_address_from_pool( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net145 = ip_dataset_prefix_v4["net145"] + + address_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + pool = await CoreIPAddressPool.init(schema=address_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_address_type="IpamIPAddress", + resources=[net145], + ip_namespace=ns1, + ) + await pool.save(db=db) + + query = ( + """ + mutation { + TestMandatoryAddressCreate(data: { + name: { value: "server1" } + address: { + from_pool: { + id: "%s" + } + } + }) { + ok + object { + name { + value + } + address { + node { + address { + value + } + } + properties { + source { + id + } + } + } + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["TestMandatoryAddressCreate"]["ok"] + assert result.data["TestMandatoryAddressCreate"]["object"] == { + "name": {"value": "server1"}, + "address": { + "node": {"address": {"value": "10.10.3.2/27"}}, + "properties": { + "source": {"id": pool.id}, + }, + }, + } + + +async def test_prefix_pool_get_resource( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_prefix_length=24, + default_prefix_type="IpamIPPrefix", + resources=[net140], + ip_namespace=ns1, + ) + await pool.save(db=db) + + query = ( + """ + mutation { + IPPrefixPoolGetResource(data: { + id: "%s" + }) { + ok + node { + kind + display_label + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["IPPrefixPoolGetResource"]["ok"] + assert result.data["IPPrefixPoolGetResource"]["node"] == { + "display_label": "10.10.0.0/24", + "kind": "IpamIPPrefix", + } + + +async def test_prefix_pool_get_resource_with_identifier( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net140 = ip_dataset_prefix_v4["net140"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + + pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_prefix_length=24, + default_prefix_type="IpamIPPrefix", + resources=[net140], + ip_namespace=ns1, + ) + await pool.save(db=db) + + resource = await pool.get_resource(db=db, identifier="myidentifier", branch=default_branch) + + query = ( + """ + mutation { + IPPrefixPoolGetResource(data: { + id: "%s" + identifier: "myidentifier" + }) { + ok + node { + id + kind + display_label + identifier + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["IPPrefixPoolGetResource"]["ok"] + assert result.data["IPPrefixPoolGetResource"]["node"] == { + "id": resource.id, + "display_label": "10.10.0.0/24", + "kind": "IpamIPPrefix", + "identifier": "myidentifier", + } + + +async def test_address_pool_get_resource( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net145 = ip_dataset_prefix_v4["net145"] + + address_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + pool = await CoreIPAddressPool.init(schema=address_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_address_type="IpamIPAddress", + resources=[net145], + ip_namespace=ns1, + ) + await pool.save(db=db) + + query = ( + """ + mutation { + IPAddressPoolGetResource(data: { + id: "%s" + }) { + ok + node { + kind + display_label + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["IPAddressPoolGetResource"]["ok"] + assert result.data["IPAddressPoolGetResource"]["node"] == {"display_label": "10.10.3.2/27", "kind": "IpamIPAddress"} + + +async def test_address_pool_get_resource_with_identifier( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_prefix_v4, +): + ns1 = ip_dataset_prefix_v4["ns1"] + net145 = ip_dataset_prefix_v4["net145"] + + address_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + pool = await CoreIPAddressPool.init(schema=address_pool_schema, db=db, branch=default_branch) + await pool.new( + db=db, + name="pool1", + default_address_type="IpamIPAddress", + resources=[net145], + ip_namespace=ns1, + ) + await pool.save(db=db) + + resource = await pool.get_resource(db=db, identifier="myidentifier", branch=default_branch) + + query = ( + """ + mutation { + IPAddressPoolGetResource(data: { + id: "%s" + identifier: "myidentifier" + }) { + ok + node { + id + kind + display_label + identifier + } + } + } + """ + % pool.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert not result.errors + assert result.data + assert result.data["IPAddressPoolGetResource"]["ok"] + assert result.data["IPAddressPoolGetResource"]["node"] == { + "id": resource.id, + "display_label": "10.10.3.2/27", + "kind": "IpamIPAddress", + "identifier": "myidentifier", + } diff --git a/backend/tests/unit/graphql/profiles/test_query.py b/backend/tests/unit/graphql/profiles/test_query.py index 22a4c3ceb8..b5fbc01420 100644 --- a/backend/tests/unit/graphql/profiles/test_query.py +++ b/backend/tests/unit/graphql/profiles/test_query.py @@ -12,7 +12,7 @@ @pytest.fixture -def criticality_schema(default_branch: Branch, data_schema): +def criticality_schema(default_branch: Branch, data_schema, node_group_schema): SCHEMA = { "name": "Criticality", "namespace": "Test", @@ -139,9 +139,9 @@ async def test_profile_apply(db: InfrahubDatabase, default_branch: Branch, criti name { value } level { value } id - profiles{ + profiles { edges { - node{ id } + node { id } } } } @@ -255,6 +255,9 @@ async def test_is_from_profile_set_correctly(db: InfrahubDatabase, default_branc "id": crit_2_profile.id, } + assert crit_1_profile.id in gql_params.context.related_node_ids + assert crit_2_profile.id in gql_params.context.related_node_ids + async def test_is_profile_source_set_correctly(db: InfrahubDatabase, default_branch: Branch, criticality_schema): profile_schema = registry.schema.get("ProfileTestCriticality", branch=default_branch) diff --git a/backend/tests/unit/graphql/queries/test_ipam.py b/backend/tests/unit/graphql/queries/test_ipam.py new file mode 100644 index 0000000000..b203c72442 --- /dev/null +++ b/backend/tests/unit/graphql/queries/test_ipam.py @@ -0,0 +1,188 @@ +import pytest +from graphql import graphql + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.node import Node +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase +from infrahub.graphql import prepare_graphql_params + + +@pytest.fixture +async def ip_dataset_01( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + + # ----------------------- + # Namespace NS1 + # ----------------------- + + ns1 = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ns1.new(db=db, name="ns1") + await ns1.save(db=db) + + net146 = await Node.init(db=db, schema=prefix_schema) + await net146.new(db=db, prefix="10.0.0.0/8", ip_namespace=ns1) + await net146.save(db=db) + + net140 = await Node.init(db=db, schema=prefix_schema) + await net140.new(db=db, prefix="10.10.0.0/16", ip_namespace=ns1, parent=net146) + await net140.save(db=db) + + net142 = await Node.init(db=db, schema=prefix_schema) + await net142.new(db=db, prefix="10.10.1.0/24", parent=net140, ip_namespace=ns1) + await net142.save(db=db) + + net143 = await Node.init(db=db, schema=prefix_schema) + await net143.new(db=db, prefix="10.10.1.0/27", parent=net142, ip_namespace=ns1) + await net143.save(db=db) + + net144 = await Node.init(db=db, schema=prefix_schema) + await net144.new(db=db, prefix="10.10.2.0/24", parent=net140, ip_namespace=ns1) + await net144.save(db=db) + + net145 = await Node.init(db=db, schema=prefix_schema) + await net145.new(db=db, prefix="10.10.3.0/27", parent=net140, ip_namespace=ns1) + await net145.save(db=db) + + data = { + "ns1": ns1, + # "ns2": ns2, + # "net161": net161, + # "net162": net162, + "net140": net140, + "net142": net142, + "net143": net143, + "net144": net144, + "net145": net145, + "net146": net146, + # "address10": address10, + # "address11": address11, + # "net240": net240, + # "net241": net241, + # "net242": net242, + } + return data + + +@pytest.fixture +async def ip_dataset_02( + db: InfrahubDatabase, + default_branch: Branch, + register_core_models_schema: SchemaBranch, + register_ipam_schema: SchemaBranch, +): + prefix_schema = registry.schema.get_node_schema(name="IpamIPPrefix", branch=default_branch) + address_schema = registry.schema.get_node_schema(name="IpamIPAddress", branch=default_branch) + + # ----------------------- + # Namespace NS1 + # ----------------------- + + ns = await Node.init(db=db, schema=InfrahubKind.NAMESPACE) + await ns.new(db=db, name="ns2") + await ns.save(db=db) + + net1 = await Node.init(db=db, schema=prefix_schema) + await net1.new(db=db, prefix="10.200.30.0/27", ip_namespace=ns, is_pool=False, member_type="address") + await net1.save(db=db) + + net1_ip1 = await Node.init(db=db, schema=address_schema) + await net1_ip1.new(db=db, address="10.200.30.1/27", ip_namespace=ns, ip_prefix=net1) + await net1_ip1.save(db=db) + + data = { + "ns": ns, + "net1": net1, + } + return data + + +@pytest.mark.parametrize( + "prefix,prefix_length,response", + [ + ("net146", 16, "10.11.0.0/16"), + ("net146", 24, "10.11.0.0/24"), + ("net142", 26, "10.10.1.64/26"), + ("net142", 27, "10.10.1.32/27"), + ], +) +async def test_ipprefix_nextavailable( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_01, + prefix, + prefix_length, + response, +): + obj = ip_dataset_01[prefix] + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + + query = """ + query($prefix: String!, $prefix_length: Int!) { + IPPrefixGetNextAvailable(prefix_id: $prefix, prefix_length: $prefix_length) { + prefix + } + } + """ + + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + variable_values={"prefix": obj.id, "prefix_length": prefix_length}, + ) + + assert not result.errors + assert result.data + assert result.data["IPPrefixGetNextAvailable"]["prefix"] == response + + +@pytest.mark.parametrize( + "prefix,prefix_length,response", + [ + ("net1", 30, "10.200.30.2/30"), + ("net1", None, "10.200.30.2/27"), + ], +) +async def test_ipaddress_nextavailable( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_schema: SchemaBranch, + ip_dataset_02, + prefix, + prefix_length, + response, +): + obj = ip_dataset_02[prefix] + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + + query = """ + query($prefix: String!, $prefix_length: Int) { + IPAddressGetNextAvailable(prefix_id: $prefix, prefix_length: $prefix_length) { + address + } + } + """ + + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + variable_values={"prefix": obj.id, "prefix_length": prefix_length}, + ) + + assert not result.errors + assert result.data + assert result.data["IPAddressGetNextAvailable"]["address"] == response diff --git a/backend/tests/unit/graphql/queries/test_resource_pool.py b/backend/tests/unit/graphql/queries/test_resource_pool.py new file mode 100644 index 0000000000..23fdfde56f --- /dev/null +++ b/backend/tests/unit/graphql/queries/test_resource_pool.py @@ -0,0 +1,367 @@ +import pytest +from graphql import graphql + +from infrahub.core import registry +from infrahub.core.branch import Branch +from infrahub.core.constants import InfrahubKind +from infrahub.core.node import Node +from infrahub.core.node.resource_manager.ip_address_pool import CoreIPAddressPool +from infrahub.core.node.resource_manager.ip_prefix_pool import CoreIPPrefixPool +from infrahub.core.schema_manager import SchemaBranch +from infrahub.database import InfrahubDatabase +from infrahub.graphql import prepare_graphql_params + + +@pytest.fixture +async def prefix_pools_02( + db: InfrahubDatabase, + default_branch: Branch, + default_ipnamespace: Node, + register_ipam_extended_schema: SchemaBranch, + init_nodes_registry, + ip_dataset_01, +): + ns1 = ip_dataset_01["ns1"] + ipv6_prefix_resource = ip_dataset_01["net161"] + ipv4_prefix_resource = ip_dataset_01["net144"] + ipv4_address_resource = ip_dataset_01["net145"] + + prefix_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPPREFIXPOOL, branch=default_branch) + address_pool_schema = registry.schema.get_node_schema(name=InfrahubKind.IPADDRESSPOOL, branch=default_branch) + + ipv6_prefix_pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await ipv6_prefix_pool.new( + db=db, + name="ipv6_prefix", + default_prefix_length=56, + default_prefix_type="IpamIPPrefix", + resources=[ipv6_prefix_resource], + ip_namespace=ns1, + ) + await ipv6_prefix_pool.save(db=db) + + ipv4_prefix_pool = await CoreIPPrefixPool.init(schema=prefix_pool_schema, db=db, branch=default_branch) + await ipv4_prefix_pool.new( + db=db, + name="ipv4_prefix", + default_prefix_length=26, + default_prefix_type="IpamIPPrefix", + resources=[ipv4_prefix_resource], + ip_namespace=ns1, + ) + await ipv4_prefix_pool.save(db=db) + + ipv4_address_pool = await CoreIPAddressPool.init(schema=address_pool_schema, db=db, branch=default_branch) + await ipv4_address_pool.new( + db=db, + name="ipv4_address", + default_prefix_length=27, + default_address_type="IpamIPAddress", + resources=[ipv4_address_resource], + ip_namespace=ns1, + ) + await ipv4_address_pool.save(db=db) + + return { + "ipv4_address_pool": ipv4_address_pool, + "ipv4_address_resource": ipv4_address_resource, + "ipv4_prefix_pool": ipv4_prefix_pool, + "ipv4_prefix_resource": ipv4_prefix_resource, + "ipv6_prefix_pool": ipv6_prefix_pool, + "ipv6_prefix_resource": ipv6_prefix_resource, + } + + +ADDRESS_MUTATION = """ +mutation CreateAddress($name: String!, $pool: String!, $identifier: String){ + TestMandatoryAddressCreate(data: { + name: { value: $name } + address: { + from_pool: { + id: $pool + identifier: $identifier + } + } + }) { + ok + object { + name { + value + } + address { + node { + address { + value + } + } + properties { + source { + id + } + } + } + } + } +} +""" + +PREFIX_MUTATION = """ +mutation CreatePrefix($name: String!, $pool: String!, $identifier: String){ + TestMandatoryPrefixCreate(data: { + name: { value: $name } + prefix: { + from_pool: { + id: $pool + identifier: $identifier + } + } + }) { + ok + object { + name { + value + } + prefix { + node { + prefix { + value + } + } + properties { + source { + id + } + } + } + } + } +} +""" + +ALLOCATED = """ +query Allocated($pool_id: String!, $resource_id: String!) { + InfrahubResourcePoolAllocated(pool_id: $pool_id, resource_id: $resource_id) { + count + edges { + node { + branch + display_label + id + identifier + kind + } + } + } +} +""" + + +async def test_create_ipv6_prefix_and_read_allocations(db: InfrahubDatabase, default_branch: Branch, prefix_pools_02): + ipv6_prefix_resource = prefix_pools_02["ipv6_prefix_resource"] + ipv6_prefix_pool = prefix_pools_02["ipv6_prefix_pool"] + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + + site1_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "site1", "pool": ipv6_prefix_pool.id, "identifier": "site1"}, + ) + + site2_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "site2", "pool": ipv6_prefix_pool.id, "identifier": "site2"}, + ) + + site3_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={ + "name": "site3", + "pool": ipv6_prefix_pool.id, + }, + ) + + assert not site1_result.errors + assert site1_result.data + assert site1_result.data["TestMandatoryPrefixCreate"]["ok"] + site1_prefix = site1_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + assert not site2_result.errors + assert site2_result.data + assert site2_result.data["TestMandatoryPrefixCreate"]["ok"] + site2_prefix = site2_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + assert not site3_result.errors + assert site3_result.data + assert site3_result.data["TestMandatoryPrefixCreate"]["ok"] + site3_prefix = site3_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + allocated_result = await graphql( + schema=gql_params.schema, + source=ALLOCATED, + context_value=gql_params.context, + root_value=None, + variable_values={ + "pool_id": ipv6_prefix_pool.id, + "resource_id": ipv6_prefix_resource.id, + }, + ) + + assert not allocated_result.errors + assert allocated_result.data + # The count is the three allocated within this test along and one created in the fixture + assert allocated_result.data["InfrahubResourcePoolAllocated"]["count"] == 4 + + nodes = allocated_result.data["InfrahubResourcePoolAllocated"]["edges"] + + prefixes = [node["node"]["display_label"] for node in nodes] + assert site1_prefix in prefixes + assert site2_prefix in prefixes + assert site3_prefix in prefixes + + +async def test_create_ipv4_prefix_and_read_allocations(db: InfrahubDatabase, default_branch: Branch, prefix_pools_02): + ipv4_prefix_resource = prefix_pools_02["ipv4_prefix_resource"] + ipv4_prefix_pool = prefix_pools_02["ipv4_prefix_pool"] + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + + site1_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "site1", "pool": ipv4_prefix_pool.id, "identifier": "site1"}, + ) + + site2_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "site2", "pool": ipv4_prefix_pool.id, "identifier": "site2"}, + ) + + site3_result = await graphql( + schema=gql_params.schema, + source=PREFIX_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={ + "name": "site3", + "pool": ipv4_prefix_pool.id, + }, + ) + + assert not site1_result.errors + assert site1_result.data + assert site1_result.data["TestMandatoryPrefixCreate"]["ok"] + site1_prefix = site1_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + assert not site2_result.errors + assert site2_result.data + assert site2_result.data["TestMandatoryPrefixCreate"]["ok"] + site2_prefix = site2_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + assert not site3_result.errors + assert site3_result.data + assert site3_result.data["TestMandatoryPrefixCreate"]["ok"] + site3_prefix = site3_result.data["TestMandatoryPrefixCreate"]["object"]["prefix"]["node"]["prefix"]["value"] + + allocated_result = await graphql( + schema=gql_params.schema, + source=ALLOCATED, + context_value=gql_params.context, + root_value=None, + variable_values={ + "pool_id": ipv4_prefix_pool.id, + "resource_id": ipv4_prefix_resource.id, + }, + ) + + assert not allocated_result.errors + assert allocated_result.data + assert allocated_result.data["InfrahubResourcePoolAllocated"]["count"] == 3 + + nodes = allocated_result.data["InfrahubResourcePoolAllocated"]["edges"] + + prefixes = [node["node"]["display_label"] for node in nodes] + assert site1_prefix in prefixes + assert site2_prefix in prefixes + assert site3_prefix in prefixes + + +async def test_create_ipv4_address_and_read_allocations(db: InfrahubDatabase, default_branch: Branch, prefix_pools_02): + ipv4_address_resource = prefix_pools_02["ipv4_address_resource"] + ipv4_address_pool = prefix_pools_02["ipv4_address_pool"] + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + + device1_result = await graphql( + schema=gql_params.schema, + source=ADDRESS_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "device1", "pool": ipv4_address_pool.id, "identifier": "site1"}, + ) + + device2_result = await graphql( + schema=gql_params.schema, + source=ADDRESS_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "device1", "pool": ipv4_address_pool.id, "identifier": "site2"}, + ) + + device3_result = await graphql( + schema=gql_params.schema, + source=ADDRESS_MUTATION, + context_value=gql_params.context, + root_value=None, + variable_values={"name": "device3", "pool": ipv4_address_pool.id, "identifier": "site3"}, + ) + + assert not device1_result.errors + assert device1_result.data + assert device1_result.data["TestMandatoryAddressCreate"]["ok"] + device1_address = device1_result.data["TestMandatoryAddressCreate"]["object"]["address"]["node"]["address"]["value"] + + assert not device2_result.errors + assert device2_result.data + assert device2_result.data["TestMandatoryAddressCreate"]["ok"] + device2_address = device2_result.data["TestMandatoryAddressCreate"]["object"]["address"]["node"]["address"]["value"] + + assert not device3_result.errors + assert device3_result.data + assert device3_result.data["TestMandatoryAddressCreate"]["ok"] + device3_address = device3_result.data["TestMandatoryAddressCreate"]["object"]["address"]["node"]["address"]["value"] + + allocated_result = await graphql( + schema=gql_params.schema, + source=ALLOCATED, + context_value=gql_params.context, + root_value=None, + variable_values={ + "pool_id": ipv4_address_pool.id, + "resource_id": ipv4_address_resource.id, + }, + ) + + assert not allocated_result.errors + assert allocated_result.data + assert allocated_result.data["InfrahubResourcePoolAllocated"]["count"] == 3 + + nodes = allocated_result.data["InfrahubResourcePoolAllocated"]["edges"] + + addresses = [node["node"]["display_label"] for node in nodes] + assert device1_address in addresses + assert device2_address in addresses + assert device3_address in addresses diff --git a/backend/tests/unit/graphql/test_graphql_query.py b/backend/tests/unit/graphql/test_graphql_query.py index de5b4d85a2..9036c95bc3 100644 --- a/backend/tests/unit/graphql/test_graphql_query.py +++ b/backend/tests/unit/graphql/test_graphql_query.py @@ -265,6 +265,98 @@ async def test_display_label_default_value(db: InfrahubDatabase, default_branch: assert result.data["TestCriticality"]["edges"][0]["node"]["display_label"] == f"TestCriticality(ID: {obj1.id})" +async def test_display_hfid(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + query = """ + query { + TestDog { + edges { + node { + id + hfid + display_label + } + } + } + } + """ + gql_params = prepare_graphql_params( + db=db, include_mutation=False, include_subscription=False, branch=default_branch + ) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert result.errors is None + assert len(result.data["TestDog"]["edges"]) == 1 + assert result.data["TestDog"]["edges"][0] == { + "node": { + "display_label": await dog1.render_display_label(db=db), + "hfid": ["Jack", "Rocky"], + "id": dog1.id, + }, + } + + +async def test_display_label_generic(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + cat_schema = animal_person_schema.get(name="TestCat") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + cat1 = await Node.init(db=db, schema=cat_schema, branch=default_branch) + await cat1.new(db=db, name="Kitty", breed="Persian", owner=person1) + await cat1.save(db=db) + + query = """ + query { + TestAnimal { + edges { + node { + display_label + } + } + } + } + """ + gql_params = prepare_graphql_params( + db=db, include_mutation=False, include_subscription=False, branch=default_branch + ) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + + assert result.errors is None + assert len(result.data["TestAnimal"]["edges"]) == 2 + expected_results = ["Kitty Persian #444444", "Rocky Labrador"] + assert sorted([item["node"]["display_label"] for item in result.data["TestAnimal"]["edges"]]) == expected_results + + async def test_all_attributes(db: InfrahubDatabase, default_branch: Branch, data_schema, all_attribute_types_schema): obj1 = await Node.init(db=db, schema="TestAllAttributeTypes") await obj1.new( @@ -623,7 +715,7 @@ async def test_query_diffsummary_old(db: InfrahubDatabase, default_branch: Branc branch2 = await create_branch(branch_name="branch2", db=db) await c1_main.delete(db=db) p1_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=p1_main.id, db=db, schema_name="TestPerson", branch=branch2 + id=p1_main.id, db=db, kind="TestPerson", branch=branch2 ) p1_branch2.name.value = "Jonathan" await p1_branch2.save(db=db) @@ -631,9 +723,7 @@ async def test_query_diffsummary_old(db: InfrahubDatabase, default_branch: Branc await p2_main.save(db=db) c2_main.name.value = "bolting" await c2_main.save(db=db) - c3_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=c3_main.id, db=db, schema_name="TestCar", branch=branch2 - ) + c3_branch2 = await NodeManager.get_one_by_id_or_default_filter(id=c3_main.id, db=db, kind="TestCar", branch=branch2) await c3_branch2.owner.update(data=p1_branch2.id, db=db) await c3_branch2.save(db=db) @@ -691,7 +781,7 @@ async def test_query_diffsummaryold(db: InfrahubDatabase, default_branch: Branch branch2 = await create_branch(branch_name="branch2", db=db) await c1_main.delete(db=db) p1_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=p1_main.id, db=db, schema_name="TestPerson", branch=branch2 + id=p1_main.id, db=db, kind="TestPerson", branch=branch2 ) p1_branch2.name.value = "Jonathan" await p1_branch2.save(db=db) @@ -699,9 +789,7 @@ async def test_query_diffsummaryold(db: InfrahubDatabase, default_branch: Branch await p2_main.save(db=db) c2_main.name.value = "bolting" await c2_main.save(db=db) - c3_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=c3_main.id, db=db, schema_name="TestCar", branch=branch2 - ) + c3_branch2 = await NodeManager.get_one_by_id_or_default_filter(id=c3_main.id, db=db, kind="TestCar", branch=branch2) await c3_branch2.owner.update(data=p1_branch2.id, db=db) await c3_branch2.save(db=db) @@ -759,7 +847,7 @@ async def test_query_diffsummary(db: InfrahubDatabase, default_branch: Branch, c branch2 = await create_branch(branch_name="branch2", db=db) await c1_main.delete(db=db) p1_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=p1_main.id, db=db, schema_name="TestPerson", branch=branch2 + id=p1_main.id, db=db, kind="TestPerson", branch=branch2 ) p1_branch2.name.value = "Jonathan" await p1_branch2.save(db=db) @@ -767,9 +855,7 @@ async def test_query_diffsummary(db: InfrahubDatabase, default_branch: Branch, c await p2_main.save(db=db) c2_main.name.value = "bolting" await c2_main.save(db=db) - c3_branch2 = await NodeManager.get_one_by_id_or_default_filter( - id=c3_main.id, db=db, schema_name="TestCar", branch=branch2 - ) + c3_branch2 = await NodeManager.get_one_by_id_or_default_filter(id=c3_main.id, db=db, kind="TestCar", branch=branch2) await c3_branch2.owner.update(data=p1_branch2.id, db=db) await c3_branch2.save(db=db) diff --git a/backend/tests/unit/graphql/test_manager.py b/backend/tests/unit/graphql/test_manager.py index 1ab60a655d..3b1d251b1e 100644 --- a/backend/tests/unit/graphql/test_manager.py +++ b/backend/tests/unit/graphql/test_manager.py @@ -21,7 +21,7 @@ async def test_generate_interface_object(db: InfrahubDatabase, default_branch: B assert inspect.isclass(result) assert issubclass(result, graphene.Interface) assert result._meta.name == "TestVehicule" - assert sorted(list(result._meta.fields.keys())) == ["description", "display_label", "id", "name"] + assert sorted(list(result._meta.fields.keys())) == ["description", "display_label", "hfid", "id", "name"] async def test_generate_graphql_object(db: InfrahubDatabase, default_branch: Branch, criticality_schema): @@ -37,6 +37,7 @@ async def test_generate_graphql_object(db: InfrahubDatabase, default_branch: Bra "color", "description", "display_label", + "hfid", "id", "is_false", "is_true", @@ -65,6 +66,7 @@ async def test_generate_graphql_object_with_interface( "_updated_at", "description", "display_label", + "hfid", "id", "name", "nbr_doors", @@ -117,6 +119,7 @@ async def test_generate_object_types(db: InfrahubDatabase, default_branch: Branc "_updated_at", "color", "display_label", + "hfid", "id", "is_electric", "member_of_groups", @@ -139,6 +142,7 @@ async def test_generate_object_types(db: InfrahubDatabase, default_branch: Branc "cars", "display_label", "height", + "hfid", "id", "member_of_groups", "name", diff --git a/backend/tests/unit/graphql/test_mutation_create.py b/backend/tests/unit/graphql/test_mutation_create.py index 097e6cba25..114f3e122b 100644 --- a/backend/tests/unit/graphql/test_mutation_create.py +++ b/backend/tests/unit/graphql/test_mutation_create.py @@ -983,3 +983,113 @@ async def test_create_with_uniqueness_constraint_violation(db: InfrahubDatabase, ) assert len(result.errors) == 1 assert "Violates uniqueness constraint 'owner-color'" in result.errors[0].message + + +async def test_relationship_with_hfid(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + query = """ + mutation { + TestDogCreate(data: { + name: { value: "Rocky" }, + breed: { value: "Labrador" }, + color: { value: "black" }, + owner: { hfid: ["Jack"] }, + }) { + ok + object { + id + } + } + } + """ + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is None + assert result.data["TestDogCreate"]["ok"] is True + assert result.data["TestDogCreate"]["object"]["id"] + + +async def test_incorrect_peer_type_prevented(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + person2 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person2.new(db=db, name="Jill") + await person2.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + dog2 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog2.new(db=db, name="Hank", breed="Chow", owner=person2) + await dog2.save(db=db) + + query = """ + mutation { + TestPersonCreate(data: {name: { value: "Herb"}, height: {value: 182}, animals: [{id: "%(animal_id)s"}]}) { + ok + object { + id + } + } + } + """ % {"animal_id": person2.id} + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is not None + assert len(result.errors) == 1 + assert ( + result.errors[0].message + == f"""TestPerson - {person2.id} cannot be added to relationship, must be of type: ['TestCat', 'TestDog'] at animals""" + ) + + query = """ + mutation { + TestDogCreate(data: { + name: { value: "Rocky" }, + breed: { value: "Labrador" }, + color: { value: "black" }, + owner: { id: "%(owner_id)s" }, + }) { + ok + object { + id + } + } + } + """ % {"owner_id": dog2.id} + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is not None + assert len(result.errors) == 1 + assert ( + result.errors[0].message + == f"""TestDog - {dog2.id} cannot be added to relationship, must be of type: ['TestPerson'] at owner""" + ) diff --git a/backend/tests/unit/graphql/test_mutation_update.py b/backend/tests/unit/graphql/test_mutation_update.py index 44ff4c5aa4..b826b6a916 100644 --- a/backend/tests/unit/graphql/test_mutation_update.py +++ b/backend/tests/unit/graphql/test_mutation_update.py @@ -616,6 +616,9 @@ async def test_update_delete_optional_relationship_cardinality_one( assert result.data["TestCarUpdate"]["ok"] is True assert result.data["TestCarUpdate"]["object"]["owner"]["node"]["name"]["value"] == "Jim" + car_schema = registry.schema.get_node_schema(name="TestCar", branch=branch, duplicate=False) + car_schema.get_relationship(name="owner").optional = True + registry.schema.set(name="TestCar", schema=car_schema, branch=branch.name) car = await NodeManager.get_one(db=db, id=car_accord_main.id, branch=branch) car_peer = await car.owner.get_peer(db=db) assert car_peer.id == person_jim_main.id @@ -1143,3 +1146,159 @@ async def test_update_with_uniqueness_constraint_violation(db: InfrahubDatabase, ) assert len(result.errors) == 1 assert "Violates uniqueness constraint 'owner-color'" in result.errors[0].message + + +async def test_with_hfid(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + query = """ + mutation { + TestDogUpdate(data: { + hfid: ["Jack", "Rocky"], + color: { value: "black" }, + }) { + ok + object { + id + color { + value + } + } + } + } + """ + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is None + assert result.data["TestDogUpdate"]["ok"] is True + assert result.data["TestDogUpdate"]["object"] == {"color": {"value": "black"}, "id": dog1.id} + + +async def test_incorrect_peer_type_prevented(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + person2 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person2.new(db=db, name="Jill") + await person2.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + dog2 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog2.new(db=db, name="Hank", breed="Chow", owner=person2) + await dog2.save(db=db) + + query = """ + mutation { + TestPersonUpdate(data: { + id: "%(person_id)s", + animals: [{ id: "%(animal_id)s" }], + }) { + ok + } + } + """ % {"person_id": person1.id, "animal_id": person2.id} + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is not None + assert len(result.errors) == 1 + assert ( + result.errors[0].message + == f"""TestPerson - {person2.id} cannot be added to relationship, must be of type: ['TestCat', 'TestDog'] at animals""" + ) + + retrieved_person = await NodeManager.get_one(db=db, branch=default_branch, id=person1.id) + animals = await retrieved_person.animals.get(db=db) + assert len(animals) == 1 + assert animals[0].peer_id == dog1.id + + query = """ + mutation { + TestDogUpdate(data: { + id: "%(dog_id)s", + owner: { id: "%(owner_id)s" }, + }) { + ok + } + } + """ % {"dog_id": dog1.id, "owner_id": dog2.id} + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is not None + assert len(result.errors) == 1 + assert ( + result.errors[0].message + == f"""TestDog - {dog2.id} cannot be added to relationship, must be of type: ['TestPerson'] at owner""" + ) + + retrieved_dog = await NodeManager.get_one(db=db, branch=default_branch, id=dog1.id) + owner = await retrieved_dog.owner.get(db=db) + assert owner.peer_id == person1.id + + +async def test_removing_mandatory_relationship_not_allowed(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + query = """ + mutation { + TestDogUpdate(data: { + id: "%(animal_id)s", + owner: null, + breed: {value: "mixed"} + }) { + ok + } + } + """ % {"animal_id": dog1.id} + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is not None + assert len(result.errors) == 1 + assert result.errors[0].message == "Too few relationships, min 1 at owner" diff --git a/backend/tests/unit/graphql/test_mutation_upsert.py b/backend/tests/unit/graphql/test_mutation_upsert.py index adf6cf1d0d..928cc76bdb 100644 --- a/backend/tests/unit/graphql/test_mutation_upsert.py +++ b/backend/tests/unit/graphql/test_mutation_upsert.py @@ -203,3 +203,110 @@ async def test_update_by_id_to_nonunique_value_raises_error( expected_error = "An object already exist with this value: name: Jim at name" assert any(expected_error in error.message for error in result.errors) + + +async def test_with_hfid_existing(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + query = ( + """ + mutation { + TestDogUpsert(data: { + hfid: ["Jack", "Rocky"], + name: { value: "Bella" }, + breed: { value: "Labrador" }, + color: { value: "black" }, + owner: { id: "%s" } + }) { + ok + object { + id + color { + value + } + } + } + } + """ + % person1.id + ) + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is None + assert result.data["TestDogUpsert"]["ok"] is True + assert result.data["TestDogUpsert"]["object"] == {"color": {"value": "black"}, "id": dog1.id} + + +async def test_with_hfid_new(db: InfrahubDatabase, default_branch, animal_person_schema): + person_schema = animal_person_schema.get(name="TestPerson") + dog_schema = animal_person_schema.get(name="TestDog") + + person1 = await Node.init(db=db, schema=person_schema, branch=default_branch) + await person1.new(db=db, name="Jack") + await person1.save(db=db) + + dog1 = await Node.init(db=db, schema=dog_schema, branch=default_branch) + await dog1.new(db=db, name="Rocky", breed="Labrador", owner=person1) + await dog1.save(db=db) + + query = ( + """ + mutation { + TestDogUpsert(data: { + hfid: ["Jack", "Bella"], + name: { value: "Bella" }, + breed: { value: "Labrador" }, + color: { value: "black" }, + owner: { id: "%s" } + }) { + ok + object { + id + name { + value + } + color { + value + } + breed { + value + } + } + } + } + """ + % person1.id + ) + + gql_params = prepare_graphql_params(db=db, include_subscription=False, branch=default_branch) + result = await graphql( + schema=gql_params.schema, + source=query, + context_value=gql_params.context, + root_value=None, + variable_values={}, + ) + assert result.errors is None + assert result.data["TestDogUpsert"]["ok"] is True + new_id = result.data["TestDogUpsert"]["object"]["id"] + assert result.data["TestDogUpsert"]["object"] == { + "breed": {"value": "Labrador"}, + "color": {"value": "black"}, + "id": new_id, + "name": {"value": "Bella"}, + } diff --git a/backend/tests/unit/pools/__init__.py b/backend/tests/unit/pools/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/tests/unit/pools/test_address.py b/backend/tests/unit/pools/test_address.py new file mode 100644 index 0000000000..3479942267 --- /dev/null +++ b/backend/tests/unit/pools/test_address.py @@ -0,0 +1,29 @@ +from ipaddress import ip_interface, ip_network + +from netaddr import IPNetwork + +from infrahub.pools.address import get_available + + +def test_get_available(): + network = ip_network("10.16.18.0/30") + addresses = [ip_interface("10.16.18.1/30")] + available = get_available(network=network, addresses=addresses, is_pool=False) + assert len(available) == 1 + assert available.iter_cidrs()[0] == IPNetwork("10.16.18.2/32") + + +def test_get_available_pool(): + network = ip_network("10.16.18.0/30") + addresses = [ip_interface("10.16.18.1/30")] + available = get_available(network=network, addresses=addresses, is_pool=True) + assert len(available) == 3 + assert available.iter_cidrs()[0] == IPNetwork("10.16.18.0/32") + assert available.iter_cidrs()[1] == IPNetwork("10.16.18.2/31") + + +def test_get_available_full(): + network = ip_network("10.16.18.0/30") + addresses = [ip_interface("10.16.18.1/30"), ip_interface("10.16.18.2/30")] + available = get_available(network=network, addresses=addresses, is_pool=False) + assert len(available) == 0 diff --git a/backend/tests/unit/pools/test_prefix.py b/backend/tests/unit/pools/test_prefix.py new file mode 100644 index 0000000000..a8f10d98e1 --- /dev/null +++ b/backend/tests/unit/pools/test_prefix.py @@ -0,0 +1,148 @@ +import ipaddress + +import pytest + +from infrahub.pools.prefix import PrefixPool + + +def test_init_v4(): + sub = PrefixPool("192.168.0.0/28") + avail_subs = sub.get_nbr_available_subnets() + + assert avail_subs == {29: 2, 30: 0, 31: 0, 32: 0} + assert sub.available_subnets[29] == ["192.168.0.0/29", "192.168.0.8/29"] + + +def test_init_v6(): + sub = PrefixPool("2001:db8::0/48") + avail_subs = sub.get_nbr_available_subnets() + + assert avail_subs[49] == 2 + assert avail_subs[50] == 0 + + +def test_split_supernet_first(): + sub = PrefixPool("192.168.0.0/24") + + sub.split_supernet( + supernet=ipaddress.ip_network("192.168.0.128/25"), + subnet=ipaddress.ip_network("192.168.0.128/27"), + ) + avail_subs = sub.get_nbr_available_subnets() + + assert avail_subs[25] == 1 + assert avail_subs[26] == 1 + assert avail_subs[27] == 2 + assert avail_subs[28] == 0 + + assert sub.available_subnets[25] == ["192.168.0.0/25"] + assert sub.available_subnets[26] == ["192.168.0.192/26"] + assert sub.available_subnets[27] == ["192.168.0.128/27", "192.168.0.160/27"] + + +def test_split_supernet_middle(): + sub = PrefixPool("192.168.0.0/24") + + sub.split_supernet( + supernet=ipaddress.ip_network("192.168.0.128/25"), + subnet=ipaddress.ip_network("192.168.0.192/27"), + ) + avail_subs = sub.get_nbr_available_subnets() + + assert avail_subs[25] == 1 + assert avail_subs[26] == 1 + assert avail_subs[27] == 2 + assert avail_subs[28] == 0 + + assert sub.available_subnets[25] == ["192.168.0.0/25"] + assert sub.available_subnets[26] == ["192.168.0.128/26"] + assert sub.available_subnets[27] == ["192.168.0.192/27", "192.168.0.224/27"] + + +def test_split_supernet_end(): + sub = PrefixPool("192.168.0.0/16") + + sub.split_supernet( + supernet=ipaddress.ip_network("192.168.128.0/17"), + subnet=ipaddress.ip_network("192.168.255.192/27"), + ) + avail_subs = sub.get_nbr_available_subnets() + + assert avail_subs[17] == 1 + assert avail_subs[25] == 1 + assert avail_subs[26] == 1 + assert avail_subs[27] == 2 + assert avail_subs[28] == 0 + + assert sub.available_subnets[17] == ["192.168.0.0/17"] + assert sub.available_subnets[26] == ["192.168.255.128/26"] + assert sub.available_subnets[27] == ["192.168.255.192/27", "192.168.255.224/27"] + + +def test_get_subnet_v4_no_owner(): + sub = PrefixPool("192.168.0.0/16") + + assert str(sub.get(prefixlen=24)) == "192.168.0.0/24" + assert str(sub.get(prefixlen=25)) == "192.168.1.0/25" + assert str(sub.get(prefixlen=17)) == "192.168.128.0/17" + assert str(sub.get(prefixlen=24)) == "192.168.2.0/24" + assert str(sub.get(prefixlen=25)) == "192.168.1.128/25" + + +def test_get_subnet_v4_with_owner(): + sub = PrefixPool("192.168.0.0/16") + + assert str(sub.get(prefixlen=24, identifier="first")) == "192.168.0.0/24" + assert str(sub.get(prefixlen=25, identifier="second")) == "192.168.1.0/25" + assert str(sub.get(prefixlen=17, identifier="third")) == "192.168.128.0/17" + assert str(sub.get(prefixlen=25, identifier="second")) == "192.168.1.0/25" + assert str(sub.get(prefixlen=17, identifier="third")) == "192.168.128.0/17" + + +def test_get_subnet_no_more_subnet(): + sub = PrefixPool("192.0.0.0/22") + + assert str(sub.get(prefixlen=24)) == "192.0.0.0/24" + assert str(sub.get(prefixlen=24)) == "192.0.1.0/24" + assert str(sub.get(prefixlen=24)) == "192.0.2.0/24" + assert str(sub.get(prefixlen=24)) == "192.0.3.0/24" + with pytest.raises(IndexError): + assert sub.get(prefixlen=24) is False + + +def test_get_subnet_v6_no_owner(): + sub = PrefixPool("2620:135:6000:fffe::/64") + assert str(sub.get(prefixlen=127)), "2620:135:6000:fffe::/127" + + +def test_already_allocated_v4_no_owner(): + sub = PrefixPool("192.168.0.0/16") + + assert str(sub.get(prefixlen=24, identifier="first")) == "192.168.0.0/24" + assert str(sub.get(prefixlen=24, identifier="second")) == "192.168.1.0/24" + + assert sub.check_if_already_allocated(identifier="second") is True + assert sub.check_if_already_allocated(identifier="third") is False + + +def test_reserve_no_owner(): + sub = PrefixPool("192.168.0.0/16") + + assert sub.reserve("192.168.0.0/24") is True + assert str(sub.get(prefixlen=24)) == "192.168.1.0/24" + + +def test_reserve_wrong_input(): + sub = PrefixPool("192.168.0.0/16") + + with pytest.raises(ValueError): + assert sub.reserve("192.192.1.0/24", identifier="first") + + +def test_reserve_with_owner(): + sub = PrefixPool("192.192.0.0/16") + + assert sub.reserve("192.192.0.0/24", identifier="first") is True + assert sub.reserve("192.192.1.0/24", identifier="second") is True + + assert str(sub.get(prefixlen=24)) == "192.192.2.0/24" diff --git a/backend/tests/unit/services/adapters/redis/test_redis.py b/backend/tests/unit/services/adapters/redis/test_redis.py index c9823341a9..a7348438f1 100644 --- a/backend/tests/unit/services/adapters/redis/test_redis.py +++ b/backend/tests/unit/services/adapters/redis/test_redis.py @@ -1,15 +1,22 @@ import asyncio from uuid import uuid4 +import pytest + +from infrahub import config +from infrahub.message_bus.types import KVTTL from infrahub.services.adapters.cache.redis import RedisCache async def test_get(): + if config.SETTINGS.cache.driver != config.CacheDriver.Redis: + pytest.skip("Must use Redis to run this test") + redis = RedisCache() key = f"ci_testing:{uuid4()}" value = "I exist" initial = await redis.get(key=key) - await redis.set(key=key, value=value, expires=1) + await redis.set(key=key, value=value, expires=KVTTL.ONE) after_set = await redis.get(key=key) await asyncio.sleep(1.1) after_expiry = await redis.get(key=key) @@ -20,11 +27,14 @@ async def test_get(): async def test_list_keys(): + if config.SETTINGS.cache.driver != config.CacheDriver.Redis: + pytest.skip("Must use Redis to run this test") + redis = RedisCache() base_key = f"ci_testing:{uuid4()}" iterations = 1005 for i in range(iterations): - await redis.set(key=f"{base_key}:{i + 1}", value="Value set", expires=10) + await redis.set(key=f"{base_key}:{i + 1}", value="Value set", expires=KVTTL.TEN) keys = await redis.list_keys(filter_pattern=f"{base_key}:*") diff --git a/development/docker-compose-deps-nats.yml b/development/docker-compose-deps-nats.yml new file mode 100644 index 0000000000..947daa2ad9 --- /dev/null +++ b/development/docker-compose-deps-nats.yml @@ -0,0 +1,22 @@ +--- +# yamllint disable rule:line-length +services: + message-queue: + image: "${MESSAGE_QUEUE_DOCKER_IMAGE:-nats:alpine}" # need alpine since latest is based on scratch (no wget available) + volumes: + - ./nats-server.conf:/etc/nats/nats-server.conf + healthcheck: + test: wget -O /dev/null http://localhost:8222/varz || exit 1 + interval: 5s + timeout: 5s + retries: 20 + start_period: 10s + # This is actually unused but required to not break all the other compose files requiring this service... + cache: + image: "${MESSAGE_QUEUE_DOCKER_IMAGE:-nats:alpine}" + healthcheck: + test: wget -O /dev/null http://localhost:8222/varz || exit 1 + interval: 5s + timeout: 5s + retries: 20 + start_period: 10s diff --git a/development/docker-compose-deps.yml b/development/docker-compose-deps.yml index 0d53579d58..0fee0e583c 100644 --- a/development/docker-compose-deps.yml +++ b/development/docker-compose-deps.yml @@ -6,7 +6,7 @@ services: - "RABBITMQ_DEFAULT_USER=infrahub" - "RABBITMQ_DEFAULT_PASS=infrahub" healthcheck: - test: rabbitmq-diagnostics -q ping + test: rabbitmq-diagnostics -q check_port_connectivity interval: 5s timeout: 30s retries: 3 diff --git a/development/docker-compose-test-scale.yml b/development/docker-compose-test-scale.yml index 9997b688b3..cbb82c9590 100644 --- a/development/docker-compose-test-scale.yml +++ b/development/docker-compose-test-scale.yml @@ -20,6 +20,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_API_CORS_ALLOW_METHODS: INFRAHUB_API_CORS_ALLOW_ORIGINS: INFRAHUB_BROKER_ADDRESS: + INFRAHUB_BROKER_DRIVER: INFRAHUB_BROKER_ENABLE: INFRAHUB_BROKER_MAXIMUM_CONCURRENT_MESSAGES: INFRAHUB_BROKER_MAXIMUM_MESSAGE_RETRIES: @@ -31,6 +32,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_BROKER_VIRTUALHOST: INFRAHUB_CACHE_ADDRESS: INFRAHUB_CACHE_DATABASE: + INFRAHUB_CACHE_DRIVER: INFRAHUB_CACHE_ENABLE: INFRAHUB_CACHE_PORT: INFRAHUB_CONFIG: @@ -50,6 +52,8 @@ x-infrahub-config: &infrahub_config INFRAHUB_GIT_REPOSITORIES_DIRECTORY: INFRAHUB_GIT_SYNC_INTERVAL: INFRAHUB_INITIAL_DEFAULT_BRANCH: + INFRAHUB_INITIAL_ADMIN_PASSWORD: + INFRAHUB_INITIAL_ADMIN_TOKEN: INFRAHUB_INTERNAL_ADDRESS: INFRAHUB_LOGGING_REMOTE_API_SERVER_DSN: INFRAHUB_LOGGING_REMOTE_ENABLE: @@ -58,11 +62,10 @@ x-infrahub-config: &infrahub_config INFRAHUB_LOG_LEVEL: INFRAHUB_MISC_MAXIMUM_VALIDATOR_EXECUTION_TIME: INFRAHUB_MISC_PRINT_QUERY_DETAILS: + INFRAHUB_MISC_RESPONSE_DELAY: INFRAHUB_MISC_START_BACKGROUND_RUNNER: INFRAHUB_PRODUCTION: INFRAHUB_SECURITY_ACCESS_TOKEN_LIFETIME: - INFRAHUB_SECURITY_INITIAL_ADMIN_PASSWORD: - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: INFRAHUB_SECURITY_REFRESH_TOKEN_LIFETIME: INFRAHUB_SECURITY_SECRET_KEY: INFRAHUB_STORAGE_BUCKET_NAME: @@ -71,7 +74,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_STORAGE_DRIVER: INFRAHUB_STORAGE_ENDPOINT_URL: INFRAHUB_STORAGE_LOCAL_PATH: - INFRAHUB_STORAGE_QUERYTSTRING_AUTH: + INFRAHUB_STORAGE_QUERYSTRING_AUTH: INFRAHUB_STORAGE_USE_SSL: INFRAHUB_TRACE_ENABLE: INFRAHUB_TRACE_EXPORTER_ENDPOINT: @@ -103,8 +106,10 @@ services: INFRAHUB_CONFIG: /source/development/infrahub.toml INFRAHUB_PRODUCTION: false INFRAHUB_LOG_LEVEL: INFO - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec + INFRAHUB_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec INFRAHUB_SECURITY_SECRET_KEY: 327f747f-efac-42be-9e73-999f08f86b92 + INFRAHUB_BROKER_ADDRESS: message-queue + INFRAHUB_CACHE_ADDRESS: "${INFRAHUB_CACHE_ADDRESS:-cache}" volumes: - ../:/source - "storage_data:/opt/infrahub/storage" diff --git a/development/docker-compose-test.yml b/development/docker-compose-test.yml index 70f47b1322..2b4510d28d 100644 --- a/development/docker-compose-test.yml +++ b/development/docker-compose-test.yml @@ -20,6 +20,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_API_CORS_ALLOW_METHODS: INFRAHUB_API_CORS_ALLOW_ORIGINS: INFRAHUB_BROKER_ADDRESS: + INFRAHUB_BROKER_DRIVER: INFRAHUB_BROKER_ENABLE: INFRAHUB_BROKER_MAXIMUM_CONCURRENT_MESSAGES: INFRAHUB_BROKER_MAXIMUM_MESSAGE_RETRIES: @@ -31,6 +32,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_BROKER_VIRTUALHOST: INFRAHUB_CACHE_ADDRESS: INFRAHUB_CACHE_DATABASE: + INFRAHUB_CACHE_DRIVER: INFRAHUB_CACHE_ENABLE: INFRAHUB_CACHE_PORT: INFRAHUB_CONFIG: @@ -50,6 +52,8 @@ x-infrahub-config: &infrahub_config INFRAHUB_GIT_REPOSITORIES_DIRECTORY: INFRAHUB_GIT_SYNC_INTERVAL: INFRAHUB_INITIAL_DEFAULT_BRANCH: + INFRAHUB_INITIAL_ADMIN_PASSWORD: + INFRAHUB_INITIAL_ADMIN_TOKEN: INFRAHUB_INTERNAL_ADDRESS: INFRAHUB_LOGGING_REMOTE_API_SERVER_DSN: INFRAHUB_LOGGING_REMOTE_ENABLE: @@ -58,11 +62,10 @@ x-infrahub-config: &infrahub_config INFRAHUB_LOG_LEVEL: INFRAHUB_MISC_MAXIMUM_VALIDATOR_EXECUTION_TIME: INFRAHUB_MISC_PRINT_QUERY_DETAILS: + INFRAHUB_MISC_RESPONSE_DELAY: INFRAHUB_MISC_START_BACKGROUND_RUNNER: INFRAHUB_PRODUCTION: INFRAHUB_SECURITY_ACCESS_TOKEN_LIFETIME: - INFRAHUB_SECURITY_INITIAL_ADMIN_PASSWORD: - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: INFRAHUB_SECURITY_REFRESH_TOKEN_LIFETIME: INFRAHUB_SECURITY_SECRET_KEY: INFRAHUB_STORAGE_BUCKET_NAME: @@ -71,7 +74,7 @@ x-infrahub-config: &infrahub_config INFRAHUB_STORAGE_DRIVER: INFRAHUB_STORAGE_ENDPOINT_URL: INFRAHUB_STORAGE_LOCAL_PATH: - INFRAHUB_STORAGE_QUERYTSTRING_AUTH: + INFRAHUB_STORAGE_QUERYSTRING_AUTH: INFRAHUB_STORAGE_USE_SSL: INFRAHUB_TRACE_ENABLE: INFRAHUB_TRACE_EXPORTER_ENDPOINT: @@ -94,6 +97,8 @@ services: INFRAHUB_PRODUCTION: false INFRAHUB_LOG_LEVEL: CRITICAL INFRAHUB_TEST_IN_DOCKER: 1 + INFRAHUB_BROKER_ADDRESS: message-queue + INFRAHUB_CACHE_ADDRESS: "${INFRAHUB_CACHE_ADDRESS:-cache}" volumes: - ../:/source tty: true diff --git a/development/docker-compose.yml b/development/docker-compose.yml index 3589badb8c..a88a31620e 100644 --- a/development/docker-compose.yml +++ b/development/docker-compose.yml @@ -20,19 +20,26 @@ x-infrahub-config: &infrahub_config INFRAHUB_API_CORS_ALLOW_METHODS: INFRAHUB_API_CORS_ALLOW_ORIGINS: INFRAHUB_BROKER_ADDRESS: + INFRAHUB_BROKER_DRIVER: INFRAHUB_BROKER_ENABLE: INFRAHUB_BROKER_MAXIMUM_CONCURRENT_MESSAGES: INFRAHUB_BROKER_MAXIMUM_MESSAGE_RETRIES: INFRAHUB_BROKER_NAMESPACE: INFRAHUB_BROKER_PASSWORD: INFRAHUB_BROKER_PORT: + INFRAHUB_BROKER_TLS_CA_FILE: INFRAHUB_BROKER_TLS_ENABLED: + INFRAHUB_BROKER_TLS_INSECURE: INFRAHUB_BROKER_USERNAME: INFRAHUB_BROKER_VIRTUALHOST: INFRAHUB_CACHE_ADDRESS: INFRAHUB_CACHE_DATABASE: + INFRAHUB_CACHE_DRIVER: INFRAHUB_CACHE_ENABLE: INFRAHUB_CACHE_PORT: + INFRAHUB_CACHE_TLS_CA_FILE: + INFRAHUB_CACHE_TLS_ENABLED: + INFRAHUB_CACHE_TLS_INSECURE: INFRAHUB_CONFIG: INFRAHUB_DB_ADDRESS: INFRAHUB_DB_DATABASE: @@ -42,6 +49,9 @@ x-infrahub-config: &infrahub_config INFRAHUB_DB_PROTOCOL: INFRAHUB_DB_QUERY_SIZE_LIMIT: INFRAHUB_DB_RETRY_LIMIT: + INFRAHUB_DB_TLS_CA_FILE: + INFRAHUB_DB_TLS_ENABLED: + INFRAHUB_DB_TLS_INSECURE: INFRAHUB_DB_TYPE: INFRAHUB_DB_USERNAME: INFRAHUB_DOCS_INDEX_PATH: @@ -49,6 +59,8 @@ x-infrahub-config: &infrahub_config INFRAHUB_EXPERIMENTAL_PULL_REQUEST: INFRAHUB_GIT_REPOSITORIES_DIRECTORY: INFRAHUB_GIT_SYNC_INTERVAL: + INFRAHUB_INITIAL_ADMIN_PASSWORD: + INFRAHUB_INITIAL_ADMIN_TOKEN: INFRAHUB_INITIAL_DEFAULT_BRANCH: INFRAHUB_INTERNAL_ADDRESS: INFRAHUB_LOGGING_REMOTE_API_SERVER_DSN: @@ -58,11 +70,10 @@ x-infrahub-config: &infrahub_config INFRAHUB_LOG_LEVEL: INFRAHUB_MISC_MAXIMUM_VALIDATOR_EXECUTION_TIME: INFRAHUB_MISC_PRINT_QUERY_DETAILS: + INFRAHUB_MISC_RESPONSE_DELAY: INFRAHUB_MISC_START_BACKGROUND_RUNNER: INFRAHUB_PRODUCTION: INFRAHUB_SECURITY_ACCESS_TOKEN_LIFETIME: - INFRAHUB_SECURITY_INITIAL_ADMIN_PASSWORD: - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: INFRAHUB_SECURITY_REFRESH_TOKEN_LIFETIME: INFRAHUB_SECURITY_SECRET_KEY: INFRAHUB_STORAGE_BUCKET_NAME: @@ -71,8 +82,11 @@ x-infrahub-config: &infrahub_config INFRAHUB_STORAGE_DRIVER: INFRAHUB_STORAGE_ENDPOINT_URL: INFRAHUB_STORAGE_LOCAL_PATH: - INFRAHUB_STORAGE_QUERYTSTRING_AUTH: + INFRAHUB_STORAGE_QUERYSTRING_AUTH: INFRAHUB_STORAGE_USE_SSL: + INFRAHUB_TELEMETRY_ENDPOINT: + INFRAHUB_TELEMETRY_INTERVAL: + INFRAHUB_TELEMETRY_OPTOUT: INFRAHUB_TRACE_ENABLE: INFRAHUB_TRACE_EXPORTER_ENDPOINT: INFRAHUB_TRACE_EXPORTER_PROTOCOL: @@ -101,8 +115,10 @@ services: <<: *infrahub_config INFRAHUB_CONFIG: /source/development/infrahub.toml INFRAHUB_PRODUCTION: false - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec + INFRAHUB_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec INFRAHUB_SECURITY_SECRET_KEY: 327f747f-efac-42be-9e73-999f08f86b92 + INFRAHUB_BROKER_ADDRESS: message-queue + INFRAHUB_CACHE_ADDRESS: "${INFRAHUB_CACHE_ADDRESS:-cache}" volumes: - "storage_data:/opt/infrahub/storage" tty: true @@ -135,8 +151,10 @@ services: INFRAHUB_ADDRESS: http://infrahub-server:8000 INFRAHUB_PRODUCTION: false INFRAHUB_LOG_LEVEL: DEBUG - INFRAHUB_SDK_API_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec - INFRAHUB_SDK_TIMEOUT: 20 + INFRAHUB_API_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec + INFRAHUB_TIMEOUT: 20 + INFRAHUB_BROKER_ADDRESS: message-queue + INFRAHUB_CACHE_ADDRESS: "${INFRAHUB_CACHE_ADDRESS:-cache}" volumes: - "git_data:/opt/infrahub/git" - "git_remote_data:/remote" diff --git a/development/infrahub.toml b/development/infrahub.toml index 3a22ebe91a..a2024a1bac 100644 --- a/development/infrahub.toml +++ b/development/infrahub.toml @@ -11,19 +11,5 @@ address = "database" port = 7687 protocol = "bolt" -[broker] -address = "message-queue" -username = "infrahub" -password = "infrahub" - -[cache] -address = "cache" - [storage] driver = "local" - -[storage.local] -path = "/opt/infrahub/storage" - -# [experimental_features] -# pull_request = true diff --git a/development/nats-server.conf b/development/nats-server.conf new file mode 100644 index 0000000000..56ab8f5aa5 --- /dev/null +++ b/development/nats-server.conf @@ -0,0 +1,7 @@ +# Client port of 4222 on all interfaces +port: 4222 + +# HTTP monitoring port +monitor_port: 8222 + +jetstream: enabled diff --git a/docker-compose.yml b/docker-compose.yml index 5ce0030e94..3b018c4606 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -50,6 +50,10 @@ x-infrahub-config: &infrahub_config INFRAHUB_GIT_REPOSITORIES_DIRECTORY: INFRAHUB_GIT_SYNC_INTERVAL: INFRAHUB_INITIAL_DEFAULT_BRANCH: + INFRAHUB_INITIAL_ADMIN_PASSWORD: + INFRAHUB_INITIAL_ADMIN_TOKEN: "06438eb2-8019-4776-878c-0941b1f1d1ec" + INFRAHUB_INITIAL_AGENT_PASSWORD: + INFRAHUB_INITIAL_AGENT_TOKEN: INFRAHUB_INTERNAL_ADDRESS: "http://infrahub-server:8000" INFRAHUB_LOGGING_REMOTE_API_SERVER_DSN: INFRAHUB_LOGGING_REMOTE_ENABLE: @@ -58,11 +62,10 @@ x-infrahub-config: &infrahub_config INFRAHUB_LOG_LEVEL: "INFO" INFRAHUB_MISC_MAXIMUM_VALIDATOR_EXECUTION_TIME: INFRAHUB_MISC_PRINT_QUERY_DETAILS: + INFRAHUB_MISC_RESPONSE_DELAY: INFRAHUB_MISC_START_BACKGROUND_RUNNER: INFRAHUB_PRODUCTION: "false" INFRAHUB_SECURITY_ACCESS_TOKEN_LIFETIME: - INFRAHUB_SECURITY_INITIAL_ADMIN_PASSWORD: - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: "06438eb2-8019-4776-878c-0941b1f1d1ec" INFRAHUB_SECURITY_REFRESH_TOKEN_LIFETIME: INFRAHUB_SECURITY_SECRET_KEY: "327f747f-efac-42be-9e73-999f08f86b92" INFRAHUB_STORAGE_BUCKET_NAME: @@ -71,8 +74,11 @@ x-infrahub-config: &infrahub_config INFRAHUB_STORAGE_DRIVER: "local" INFRAHUB_STORAGE_ENDPOINT_URL: INFRAHUB_STORAGE_LOCAL_PATH: "/opt/infrahub/storage" - INFRAHUB_STORAGE_QUERYTSTRING_AUTH: + INFRAHUB_STORAGE_QUERYSTRING_AUTH: INFRAHUB_STORAGE_USE_SSL: + INFRAHUB_TELEMETRY_ENDPOINT: + INFRAHUB_TELEMETRY_INTERVAL: + INFRAHUB_TELEMETRY_OPTOUT: INFRAHUB_TRACE_ENABLE: "false" INFRAHUB_TRACE_EXPORTER_ENDPOINT: INFRAHUB_TRACE_EXPORTER_PROTOCOL: @@ -88,7 +94,7 @@ services: RABBITMQ_DEFAULT_USER: *broker_username RABBITMQ_DEFAULT_PASS: *broker_password healthcheck: - test: rabbitmq-diagnostics -q ping + test: rabbitmq-diagnostics -q check_port_connectivity interval: 5s timeout: 30s retries: 3 @@ -105,7 +111,7 @@ services: retries: 3 database: - image: ${NEO4J_DOCKER_IMAGE:-neo4j:5.19.0-enterprise} + image: ${NEO4J_DOCKER_IMAGE:-neo4j:5.19.0-community} restart: unless-stopped environment: - "NEO4J_AUTH=neo4j/admin" @@ -125,7 +131,7 @@ services: - 6362:6362 infrahub-server: - image: "registry.opsmill.io/opsmill/infrahub:${VERSION:-0.12.1}" + image: "registry.opsmill.io/opsmill/infrahub:${VERSION:-0.13.0}" restart: unless-stopped command: > gunicorn --config backend/infrahub/serve/gunicorn_config.py @@ -156,7 +162,7 @@ services: deploy: mode: replicated replicas: 2 - image: "registry.opsmill.io/opsmill/infrahub:${VERSION:-0.12.1}" + image: "registry.opsmill.io/opsmill/infrahub:${VERSION:-0.13.0}" command: infrahub git-agent start --debug restart: unless-stopped depends_on: diff --git a/docs/README.md b/docs/README.md index 28da69c602..100b9eca92 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,4 +1,4 @@ -# Infrahub Documentation Website +# Infrahub documentation website This folder contains the source code and documentation powering https://docs.infrahub.app. @@ -12,7 +12,7 @@ This website is built using [Docusaurus](https://docusaurus.io/), a modern stati npm install ``` -### Local Development +### Local development ```shell npm start diff --git a/docs/_templates/dotinfrahub.j2 b/docs/_templates/dotinfrahub.j2 index 37718d63c2..d97fefb6f2 100644 --- a/docs/_templates/dotinfrahub.j2 +++ b/docs/_templates/dotinfrahub.j2 @@ -12,6 +12,12 @@ The file should be formatted as a Yaml file, have the filename `.infrahub.yml` a See [this topic](/topics/infrahub-yml) for more details on the available repository configuration options +::: + +:::note + +To help with the development process of a repository configuration file, you can leverage the schemas we publish for validation within your [editor](/development/editor) + ::: {% for property in properties %} diff --git a/docs/_templates/sdk_config.j2 b/docs/_templates/sdk_config.j2 index acb3c6e9c3..2c7f70c247 100644 --- a/docs/_templates/sdk_config.j2 +++ b/docs/_templates/sdk_config.j2 @@ -29,7 +29,7 @@ The following settings can be defined in the Config class ## {{ property.name }} **Property**: {{ property.name }}
-**Description**: {{ property.description }}
+**Description**: {% if '\n' in property.description %} {% endif %}{{ property.description }}
**Type**: `{{ property.type }}`
{% if "default" in property and property.default is not none and property.default != ""%} **Default value**: {{ property.default }}
diff --git a/docs/docs/development/backend.mdx b/docs/docs/development/backend.mdx index 0ef6f0e023..37f8895c65 100644 --- a/docs/docs/development/backend.mdx +++ b/docs/docs/development/backend.mdx @@ -11,7 +11,7 @@ In order start developing on Infrahub backend, it is recommended to have a decen * [Poetry](https://python-poetry.org/) to manage our Python virtual environment * [Docker](https://www.docker.com/) and its Compose extension to run dependencies such as the database, cache and queueing system -To fetch Infrahub's code, we will use git and we will use the `develop` branch. +To fetch Infrahub's code, we will use Git and we will use the `develop` branch. ```bash git clone git@github.com:opsmill/infrahub.git @@ -26,12 +26,12 @@ Most of Infrahub and tools around it rely on some settings. These settings are i ```bash export INFRAHUB_PRODUCTION=false export INFRAHUB_SECURITY_SECRET_KEY=super-secret -export INFRAHUB_SDK_USERNAME=admin -export INFRAHUB_SDK_PASSWORD=infrahub -export INFRAHUB_SDK_TIMEOUT=20 +export INFRAHUB_USERNAME=admin +export INFRAHUB_PASSWORD=infrahub +export INFRAHUB_TIMEOUT=20 export INFRAHUB_METRICS_PORT=8001 export INFRAHUB_DB_TYPE=neo4j # Accepts neo4j or memgraph -export INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN="${ADMIN_TOKEN}" # Random string which can be generated using: openssl rand -hex 16 +export INFRAHUB_INITIAL_ADMIN_TOKEN="${ADMIN_TOKEN}" # Random string which can be generated using: openssl rand -hex 16 export INFRAHUB_STORAGE_LOCAL_PATH="${HOME}/Development/infrahub-storage" export INFRAHUB_API_CORS_ALLOW_ORIGINS='["http://localhost:8080"]' # Allow frontend/backend communications without CORS issues export INFRAHUB_IMAGE_VER=local # Force building a local image instead of pulling one from the registry diff --git a/docs/docs/development/docs.mdx b/docs/docs/development/docs.mdx index 53e4c51100..1a84b4d31f 100644 --- a/docs/docs/development/docs.mdx +++ b/docs/docs/development/docs.mdx @@ -24,6 +24,7 @@ invoke -l docs The primary commands are as follows: +- `invoke docs.install`: Install the documentation dependencies via `npm`. - `invoke docs.build`: Build the documentation website. - `invoke docs.generate`: Generate source-derived documentation pages (such as the schema and Jinja templates). - `invoke docs.serve`: Run a local development server for the documentation website. diff --git a/docs/docs/development/editor.mdx b/docs/docs/development/editor.mdx index 7cec9d2a88..8cdfb32f85 100644 --- a/docs/docs/development/editor.mdx +++ b/docs/docs/development/editor.mdx @@ -18,7 +18,7 @@ More details coming soon - Jinja: https://marketplace.visualstudio.com/items?itemName=wholroyd.jinja - Pylance: https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance - Trailing Space: https://marketplace.visualstudio.com/items?itemName=shardulm94.trailing-spaces -- Better Toml: https://marketplace.visualstudio.com/items?itemName=bungcip.better-toml +- Even Better Toml: https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml - GraphQL: https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql - Ruff: https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff diff --git a/docs/docs/development/frontend/readme.mdx b/docs/docs/development/frontend/readme.mdx index 5bc9120ed6..2a1c46b860 100644 --- a/docs/docs/development/frontend/readme.mdx +++ b/docs/docs/development/frontend/readme.mdx @@ -25,7 +25,7 @@ For testing, we rely on: ## Accessing the frontend code -To access Infrahub's codebase, use git and switch to the `develop` branch to access the latest changes. All frontend code resides in `/frontend`. +To access Infrahub's codebase, use Git and switch to the `develop` branch to access the latest changes. All frontend code resides in `/frontend`. ```bash git clone git@github.com:opsmill/infrahub.git diff --git a/docs/docs/faq/faq.mdx b/docs/docs/faq/faq.mdx new file mode 100644 index 0000000000..ffb9694f0c --- /dev/null +++ b/docs/docs/faq/faq.mdx @@ -0,0 +1,174 @@ +--- +title: FAQ +--- +# Frequently asked questions + +Here are the key details about Infrahub: + +## About Infrahub + +### What is Infrahub? + +Infrahub is an open-source platform that enables infrastructure as code by providing a unified system to model, store, version, validate, and generate infrastructure data and configurations. It acts as a centralized source of truth for all infrastructure resources across an organization. + +### What are the main features and capabilities? + +- User-Defined Schema: Build and update data models to support business requirements for infrastructure resources. +- Unified Storage: Version control for data and files +- Versioning: Track current state and future intended state of the infrastructure with built-in peer review and a CI pipeline for validation. +- Immutable Database: Go back in time to view the state of infrastructure at any point. +- Artifact Generation: Transform infrastructure data into any format (text configurations, XML, JSON, etc.) using generators and templates. +- Data Lineage: View the source and owner for each piece of infrastructure data. +- Multiple interfaces for each team and need: + - Web UI: View and manage all infrastructure data, configurations, and CI/CD pipelines through a user interface. + - Query Engine: Powerful API and support for GraphQL and REST to query and retrieve infrastructure data. +- Git Integration: File storage for code and templates +- Integrations: Integrations with tools like NetBox, Nautobot, Ansible, and Nornir. Ability to build custom integrations. +- Python SDK: Programmatically interact with Infrahub using a Python SDK. + +For more information, see our [Infrahub overview](../overview/). + +### I’m just getting started with infrastructure automation. Do I need Infrahub? + +If you're new to infrastructure automation, Infrahub can be a valuable tool to help you manage and automate your infrastructure resources without having to learn and assemble multiple automation tools into a workable system. + +It provides a centralized platform to define, version, and generate your infrastructure configurations, making it easier to achieve the goals of automation without the significant up-front effort. + +Please see our [Getting Started](../tutorials/getting-started/) tutorial to learn how to use Infrahub. + +### Where can I deploy Infrahub? + +You can test out Infrahub via [GitHub Codespaces](https://github.com/opsmill/infrahub#quick-start) + +Infrahub is a platform-agnostic solution that can be deployed in various environments, including: + +- Cloud platforms such as AWS, Azure, or GCP +- On-premises data centers +- Kubernetes clusters (via Helm charts) +- Docker containers (using Docker Compose) + +The specific system requirements may vary depending on the deployment environment and the scale of your infrastructure. + +In the future, we plan to offer a managed Cloud SaaS offering of Infrahub. Please [subscribe to our mailing list](https://opsmill.com) to stay updated. + +### Installation and deployment + +To install and set up Infrahub: + +1. Download the latest version of Infrahub from the [GitHub repository](https://github.com/opsmill/infrahub) +2. [Deploy](../guides/installation): Deploy Infrahub using the appropriate method for your environment such as Docker Compose, Helm charts + +Detailed installation guides and tutorials are available in [Installing Infrahub](../guides/installation) guide. + +### I deployed Infrahub, now what? + +After deploying Infrahub, you can start using it to manage your infrastructure resources. Here are some common initial steps: + +- [Load Schema](../topics/schema): Define your infrastructure data model by loading a schema into Infrahub. This schema will define the structure and relationships of your infrastructure resources. +- [Load Data](../overview/data.mdx): Populate Infrahub with your existing infrastructure data, either manually or by importing from other sources. +- Inventory: Use Infrahub's inventory capabilities to view and manage your infrastructure resources based on the loaded data. + +### How do I load my own schema into Infrahub? + +Infrahub allows you to load custom schemas to define your infrastructure data model. Currently, you can load schemas using the following methods: + +- [CLI and SDK](../topics/schema): Use the Infrahub command-line interface (CLI) or the Python SDK to load and manage schemas programmatically. +- Frontend (Coming Soon): A user-friendly web interface for managing schemas is planned for future releases. + +### What is the status of the project? + +Infrahub is currently in beta, and the team is actively working towards reaching version 1.0 by the end of the year. The project is committed to ensuring data safety and providing a migration path for future releases. + +Upcoming features and improvements include: + +- Scale and Performance: Enhancements to handle larger volumes of data and improve overall performance. +- Proposed Changes & CI Pipeline +- Resource Manager: A dedicated resource management module for better visibility and control over infrastructure resources. +- Profiles: Support for defining and managing different profiles or environments within Infrahub. + +### How much data can Infrahub handle right now? + +The current data handling capabilities of Infrahub are still being actively developed and tested. If you have specific requirements or want to assess Infrahub's performance and scalability in your environment, please reach out to the team at contact@opsmill.com or through the [Discord](https://discord.gg/jXMRp9hXSX) server. + +### Can I deploy Infrahub in production? + +Yes, Infrahub can be deployed in production but keep in mind we are still in beta so please ensure to have the right backup and safeguard in place. + +If you are planning to deploy Infrahub in a critical environment we recommend reaching out to our customer success team via [Discord](https://discord.gg/jXMRp9hXSX) or contact@opsmill.com + +### How can I get involved? + +We develop Infrahub for customers and with the community. There are a few different ways to get involved with Infrahub: + +- As you use Infrahub, please submit bugs and feature requests. +- Reach out to OpsMill on [Discord](https://discord.gg/jXMRp9hXSX) and set up a user feedback session to share your thoughts with us. +- If you are a developer, we are open to pull requests. Please first discuss your intentions via [GitHub Discussions](https://github.com/opsmill/infrahub/discussions) and send a pull request our way to fix it. + +Please see our [development docs](https://docs.infrahub.app/development/) for a guide to getting started developing for Infrahub. + +We maintain a [list of issues that are appropriate to newcomers](https://github.com/opsmill/infrahub/issues?q=is:open+is:issue+label:type/newcomers) to the Infrahub development community. This is a great place to get started! + +### How do I get help with Infrahub? + +If you need assistance with Infrahub, you can reach out to the community and the development team through the following channels: + +- Discord: Join the Infrahub [Discord](https://discord.gg/jXMRp9hXSX) server to ask questions, get support, and engage with other users. +- GitHub Issues: Submit issues or questions on the Infrahub GitHub repository (https://github.com/opsmill/infrahub/issues). + +### Will there be paid support or an Enterprise version of Infrahub? + +While Infrahub is currently an open-source project, the team is developing a plan for paid support and an enterprise version with additional features and services in the future. More information about these plans will be shared as the project progresses. + +### I have generated my configurations with Infrahub, how can I deploy them to my devices? + +Infrahub is designed to be the source of truth for your infrastructure data and configurations. It does not directly connect to or deploy configurations to your infrastructure devices. Instead, Infrahub integrates with tools like Nornir and Ansible, which can be used to deploy the generated configurations to your infrastructure. + +Please see the documentation on [integrations](../integrations) for more information. + +### Does Infrahub send telemetry? And how can I disable it? + +Infrahub collects anonymous usage metrics and sends them to OpsMill servers for analysis and improvement purposes. No personally identifiable information is collected. If you prefer to opt-out of telemetry collection, you can do so by setting the `INFRAHUB_TELEMETRY_OPTOUT` environment variable to `true`: + +```bash +export INFRAHUB_TELEMETRY_OPTOUT=true +``` + +### What telemetry does Infrahub send? + +The following information is included in telemetry: + +- Infrahub version +- Platform information +- Anonymous counters about the graph and the schema + +This information is used as aggregated analysis to better understand what and how to improve the project. All information collected are anonymous and the implementation is open source on Github. + +## About OpsMill + +### Who is behind this project? + +Infrahub is sponsored and developed by OpsMill, a startup focused on infrastructure management. The OpsMill team is distributed across Europe and the United States, with members who have extensive experience in managing infrastructure and building automation solutions. + +You can learn more about the OpsMill team and the company on our website: https://www.opsmill.com/about-us + +### Why is OpsMill’s mascot an Otter? + +Otters are really cool, and they are considered a keystone species, meaning they have a disproportionately large impact on their natural environment relative to their representation. + +Similarly, Infrahub aims to be a keystone platform for managing and automating infrastructure, providing a central and influential role in shaping and maintaining your infrastructure ecosystem. + +### What is the name of the otter? + +![otto](../media/otto.png) + +The OpsMill’s mascot is an otter named Otto. + +You can send fan mail to Otto at otto@opsmill.com! + +### Can Infrahub make me as cool as Tony Stark? + +Almost! You’ll definitely feel like a tech genius managing your infrastructure with Infrahub! + +### Made it this far? We'd love to hear from you + +If you've made it this far, please feel free to reach out on the [Discord](https://discord.gg/jXMRp9hXSX) server to share your thoughts or schedule a customer interview session. The Infrahub team is always eager to receive feedback and engage with the community. diff --git a/docs/docs/guides/artifact.mdx b/docs/docs/guides/artifact.mdx index cac01bf806..1e75825da5 100644 --- a/docs/docs/guides/artifact.mdx +++ b/docs/docs/guides/artifact.mdx @@ -129,7 +129,7 @@ git commit -m "add tags_config_file artifact definition" git push origin main ``` -The artifact definition will be created in the database, when the git agent(s) notice the change in the git repository. The `tags_config_file` should now be visible in the Artifact Definition view in the web interface. +The artifact definition will be created in the database, when the Git agent(s) notice the change in the Git repository. The `tags_config_file` should now be visible in the Artifact Definition view in the web interface. ![Artifact Definition](../media/guides/artifact/artifact_definition.png) ## Accessing the artifacts diff --git a/docs/docs/guides/check.mdx b/docs/docs/guides/check.mdx new file mode 100644 index 0000000000..142bfd5a8f --- /dev/null +++ b/docs/docs/guides/check.mdx @@ -0,0 +1,530 @@ +--- +title: Creating a Check +--- + +## Creating a Check + +Within Infrahub a [Check](/topics/check) is defined in an [external repository](/topics/repository). However, during development and troubleshooting it is easiest to start from your local computer and run the check using [infrahubctl check](/infrahubctl/infrahubctl-check). + +The goal of this guide is to develop a Check and add it to Infrahub, we will achieve this by following these steps. + +1. Identify the relevant data in the database that you want to use as input for the check using a [GraphQL query](/topics/graphql), that can take an input parameter to filter the data +2. Write a Python script that will process and validate the data using your custom business logic +3. Create an entry for the check within an .infrahub.yml file +4. Create a Git repository +5. Test the Check with the `infrahubctl` command +6. Add the repository to Infrahub as an external repository +7. Test the Check in a proposed change + +In this guide we are going to work with the builtin tag objects in Infrahub. The goal will be to use a check to validate the naming convention of an object using a Regex. Validating a string with a Regex is something we can do directly in the schema so this check won't be super helpful but the goal is instead to show how Checks work. Once you have mastered the basics you will be ready to go on to create more advanced Checks. + +### 1. Creating a query to collect the desired data + +As the first step we need to have some data in the database to actually query. + +Create three tags, called "color-red", "color-green", "blue", either using the frontend or by submitting three GraphQL mutations as per below (just swapping out the name of the color each time). +Note that the "blue" tag is following a different naming scheme compared to the other tags. This is on purpose and is needed for the rest of the guide. + +```GraphQL +mutation CreateTags { + BuiltinTagCreate( + data: {name: {value: "color-red"}, description: {value: "The red tag"}} + ) { + ok + object { + id + } + } +} +``` + +The next step is to create a query that returns the data we just created. The rest of this guide assumes that the following query will return a response similar to the response below the query. + +```GraphQL +query TagsQuery { + BuiltinTag { + edges { + node { + name { + value + } + description { + value + } + } + } + } +} +``` + +Response to the tags query: + +```json +{ + "data": { + "BuiltinTag": { + "edges": [ + { + "node": { + "name": { + "value": "blue" + }, + "description": { + "value": "The blue tag" + } + } + }, + { + "node": { + "name": { + "value": "color-green" + }, + "description": { + "value": "The green tag" + } + } + }, + { + "node": { + "name": { + "value": "color-red" + }, + "description": { + "value": "The red tag" + } + } + } + ] + } + } +} +``` + +Create a local directory on your computer. + +```bash +mkdir tags_check +``` + +Then save the `TagsQuery` as a text file named `tags_check.gql`. + +### 2. Create the Python check file + +The next step is to create the Check Python business logic. The check is a Python class that inherits from `InfrahubCheck` from the [Python SDK](/python-sdk). Create a file called `tags_check.py`: + +```python +import re + +from infrahub_sdk.checks import InfrahubCheck + + +RE_TAG = re.compile(r"^color-[a-z]+") + +class ColorTagsCheck(InfrahubCheck): + query = "tags_check" + + def validate(self, data): + for tag in data["BuiltinTag"]["edges"]: + if not RE_TAG.match(tag["node"]["name"]["value"]): + self.log_error( + message=f"Invalid tag name: {tag['node']['name']['value']}", + object_id=tag["node"]["name"]["value"], + object_type="BuiltinTag" + ) + +``` + +The example is a simple example of what a naming convention logic for a tag could look like. + +1. We import the `InfrahubCheck` class. + +```python +from infrahub_sdk.checks import InfrahubCheck +``` + +2. We create and compile a regular expression against which we will match the tag names + +```python +RE_TAG = re.compile(r"^color-[a-z]+") +``` + +3. We define our own class that inherits from `InfrahubCheck`. + +```python +class ColorTagsCheck(InfrahubCheck): +``` + +Here we need to take note of the name of the class as we will need it later, optionally we can just call it `Check` which is the default name. + +4. We define the query that will provide us the input data + +```python + query = "tags_check" +``` + +The query references to the file `tags_check.gql` that we created earlier. + +5. We define the validate method + +```python + def validate(self, data): + for tag in data["BuiltinTag"]["edges"]: + if not RE_TAG.match(tag["node"]["name"]["value"]): + self.log_error( + message=f"Invalid tag name: {tag['node']['name']['value']}", + object_id=tag["node"]["name"]["value"], + object_type="BuiltinTag" + ) +``` + +When running the check, the `data` argument will contain the response to the GraphQL query we created. We loop over every `BuiltinTag` node in `data` and validate that the name of the tag matches with the regular expression we created earlier. + +If the name does not match the regular expression, we log an error. A check will have failed if it has encountered errors during the execution. + +### 3. Create a .infrahub.yml file + +In the `.infrahub.yml` file you define what checks you have in your repository that you want to use in Infrahub. + +Create a `.infrahub.yml` file in the root of the directory. + +```yaml +--- +check_definitions: + - name: "check_color_tags_name" + class_name: "ColorTagsCheck" + file_path: "tags_check.py" +``` + +Two parts here are required, first the `name` of the check which should be unique across Infrahub and also the `file_path` that should point to the Python file within the repository. In this example we have also defined `class_name`, the reason for this is that we gave our class the name `ColorTagsCheck` instead of the default `Check`. + +### 4. Create a Git repository + +Within the `tags_check` folder you should now have 3 files: + +- `tags_check.gql`: Contains the GraphQL query +- `tags_check.py`: Contains the Python code with the business logic for the check +- `.infrahub.yml`: Contains the definition of the check + +Before we can test our transform we must add the files to a local Git repository. + +```bash +git init --initial-branch=main +git add . +git commit -m "First commit" +``` + +### 5. Test the check using infrahubctl + +Using infrahubctl you can first verify that the `.infrahub.yml` file is formatted correctly by listing available checks. + +```bash title="❯ infrahubctl check --list" +Python checks defined in repository: 1 +check_color_tags_name (tags_check.py::ColorTagsCheck) Target: -global- +``` + +Run the check by specifying the name of the check as an argument. + +```bash title="❯ infrahubctl check check_color_tags_name" +[09:23:25] INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + ERROR tags_check::ColorTagsCheck: FAILED + ERROR Invalid tag name: blue +``` + +We have now successfully created a check. Most of the checks you will create would be more complex than this, however the main building blocks will always remain the same. + +### 6. Adding the repository to Infrahub + +In order to avoid having the same instructions over and over please refer to the guide [adding a repository to Infrahub](/guides/repository) in order to sync the repository you created and make it available within Infrahub. + +### 7. Using the check within Infrahub + +Once the repository is synced to Infrahub, the check will be run as part of a proposed change. + +1. Open a branch named `test` +2. Create a new `BuiltinTag` object named `orange` in the `test` branch +3. Open a proposed change +4. Navigate to the Checks tab +5. The User Checks should have a red color, indicating a Check has failed +6. Expanding the Check `check_color_tags_name` should show us that the check failed because the `BuiltinTag` objects `blue` and `orange` do not match with our naming scheme + +![Check details](../media/guides/check_proposed_change.png) + +## Creating a targeted check + +Let's extend our example. We want to introduce a second set of tags. The naming scheme for these tags is different so we would need to introduce a second check. + +Therefor we will redefine our `check_color_tags_name` check as a targeted check, and define a new targeted check for the tags with a different naming scheme. + +We will be performing the following steps: + +1. Define targets for the `check_color_tags_name` check in the repository configuration file +2. Create a new group `ColorTags` +3. Add the existing tags to a group named `ColorTags` +4. Modify the `tags_check` GraphQL query +5. Test the `check_color_tags_name` check +6. Add new `BuiltinTags` using the other naming schema +7. Create a new group `NumberTags` +8. Add the tags with the number naming scheme to the group +9. Add a new check to the Python `tags_checkk.py` script for the number naming scheme +10. Define a new targeted check in the repository configuration file +11. Test the new check + +Before we start, make sure that you switch back to the `main` branch in Infrahub. + +### 1. Define the targets for the `check_color_tags_name` check in the repository configuration file + +Replace the contents of the `.infrahub.yml` file with this content. + +```yaml +--- +check_definitions: + - name: "check_color_tags_name" + class_name: "ColorTagsCheck" + file_path: "tags_check.py" + targets: "ColorTags" + parameters: + name: "name__value" +``` + +We added 2 definitions to the `check_color_tags_name`: + +- `targets` the name of the group with the nodes that we want to target `ColorTags` +- `parameters` we define a `name` parameter that will be passed to the check's GraphQL query, in this case we will pass the value of the name attribute of each tag in the group + +### 2. Creating a `ColorTags` group + +Targeted checks use nodes in a group a their targets. Create the `ColorTags` group with this GraphQL query. Take node of the id of the group, we will need it in the next steps. + +```graphql +mutation { + CoreStandardGroupCreate(data: {name: {value: "ColorTags"}}) { + ok + object { + id + } + } +} +``` + +### 3. Add the existing tags to a the `ColorTags` group + +First we need to get the id of the existing tags. + +```graphql +query { + BuiltinTag { + edges { + node { + id + } + } + } +} +``` + +We can then use the id's of the tags to add them to the `ColorTags` group. + +- replace the first id with the id of the group +- replace the second id with the id of the first tag returned by the previous query +- replace the third id with the id of the second tag returned by the previous query +- replace the fourth id with the id of the third tag returned by the previous query + +```graphql +mutation { + CoreStandardGroupUpdate( + data: { + id: "", + members: [ + {id: ""}, + {id: ""}, + {id: ""} + ] + } + ) { + ok + } +} +``` + +### 4. Modify the tags_check GraphQL query + +We need to modify the GraphQL query with the `name` parameter. The GraphQL query will be executed for every node that is part of the target group. + +Replace the contents of the `tags_check.gql` file with the following contents. + +```GraphQL +query TagsQuery($name: String!) { + BuiltinTag(name__value: $name) { + edges { + node { + name { + value + } + description { + value + } + } + } + } +} +``` + +### 5. Test the `check_color_tags_name` check + +```bash title="❯ infrahubctl check check_color_tags_name" +``[11:50:43] INFO HTTP Request: GET http://localhost:8000/api/schema/?branch=main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO color_tags_check::ColorTagsCheck: PASSED - {'name': 'color-red'} + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO color_tags_check::ColorTagsCheck: PASSED - {'name': 'color-green'} +[11:50:44] INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + ERROR color_tags_check::ColorTagsCheck: FAILED - {'name': 'blue'} + ERROR Invalid tag name: blue +``` + +Notice that the end-result is still the same, the check fails on the blue tag. However we can see that there was now an individual execution of the GraphQL and check per tag in the target group. + +### 6. Add new `BuiltinTags` using the other naming schema + +Create two tags, called "1-one", "2-two" either using the frontend or by submitting two GraphQL mutations as per below (just swapping out the name of the tag each time). + +```graphql +mutation CreateTags { + BuiltinTagCreate( + data: {name: {value: "1-one"}, description: {value: "The first tag"}} + ) { + ok + object { + id + } + } +} +``` + +Take note of their id as we will need it in the next steps. + +### 7. Create a new group `NumberTags` + +```grapql +mutation { + CoreStandardGroupCreate(data: {name: {value: "NumberTags"}}) { + ok + object { + id + } + } +} +``` + +Take note of the id as we will need it in the next step. + +### 8. Add the tags with the number naming scheme to the group + +Add the newly created tags to the `NumberTags` group with the following mutation. + +- replace the first id with the id of the group +- replace the second id with the id of the first tag +- replace the third id with the id of the second tag + +```graphql +mutation { + CoreStandardGroupUpdate( + data: { + id: "", + members: [ + {id: ""}, + {id: ""} + ] + } + ) { + ok + } +} +``` + +### 9. Add new check logic + +Add the following Python code to the `tags_check.py` script in the repository. + +```python +RE_NUMBER_TAG = re.compile(r"^\d+-[a-z]+$") + +class NumberTagsCheck(InfrahubCheck): + query = "tags_check" + + def validate(self, data): + for tag in data["BuiltinTag"]["edges"]: + if not RE_NUMBER_TAG.match(tag["node"]["name"]["value"]): + self.log_error( + message=f"Invalid number tag name: {tag['node']['name']['value']}", + object_id=tag["node"]["name"]["value"], + object_type="BuiltinTag" + ) +``` + +### 10. Define a new targeted check + +Replace the contents of `.infrahub.yml` file with the following contents. + +```yaml +--- +check_definitions: + - name: "check_color_tags_name" + class_name: "ColorTagsCheck" + file_path: "tags_check.py" + targets: "ColorTags" + parameters: + name: "name__value" + - name: "check_number_tags_name" + class_name: "NumberTagsCheck" + file_path: "tags_check.py" + targets: "NumberTags" + parameters: + name: "name__value" +``` + +We now have 2 targeted checks defined, each targeting its own set of tags, with its own validation logic. + +### 11. Test the new check + +Verify that we have 2 checks defined using the `infrahubctl` command. + +```bash title="❯ infrahubctl check --list" +Python checks defined in repository: 2 +check_color_tags_name (tags_check.py::ColorTagsCheck) Target: ColorTags +check_number_tags_name (tags_check.py::NumberTagsCheck) Target: NumberTags +``` + +Check that the `check_color_tags_name` fails because of the tag `blue` not complying with the naming scheme: + +```bash title="❯ infrahubctl check check_color_tags_name" +[14:04:50] INFO HTTP Request: GET http://localhost:8000/api/schema/?branch=main "HTTP/1.1 200 OK +[14:04:51] INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO tags_check::ColorTagsCheck: PASSED - {'name': 'color-red'} + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO tags_check::ColorTagsCheck: PASSED - {'name': 'color-green'} + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + ERROR tags_check::ColorTagsCheck: FAILED - {'name': 'blue'} + ERROR Invalid tag name: blue +``` + +Check that the `check_number_tags_name` succeeds: + +```bash title="❯ infrahubctl check check_number_tags_name" +[14:09:32] INFO HTTP Request: GET http://localhost:8000/api/schema/?branch=main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql/main "HTTP/1.1 200 OK" + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO tags_check::NumberTagsCheck: PASSED - {'name': '1-one'} + INFO HTTP Request: POST http://localhost:8000/graphql "HTTP/1.1 200 OK" + INFO tags_check::NumberTagsCheck: PASSED - {'name': '2-two'} +``` diff --git a/docs/docs/guides/create-schema.mdx b/docs/docs/guides/create-schema.mdx index 8b5171da01..286bef8413 100644 --- a/docs/docs/guides/create-schema.mdx +++ b/docs/docs/guides/create-schema.mdx @@ -22,6 +22,12 @@ For a more detailed explanation of the different Attributes and Relations, you c Throughout this guide we will load different schemas into Infrahub into different branches. The fact that multiple schemas can exist simultaneously is a core feature of Infrahub. It is a recommendation and best practice to always use a branch to make changes to the schema. +:::note + +To help with the development process of a schema definition file, you can leverage [schema validation](/reference/schema-validation) within your editor. + +::: + ## 1. Adding nodes and attributes Create a file named `schema_guide.yml` on your computer. The place where you create the file on the file system is not that important, as long as you know the path to the file. For this guide we will be storing the schema file in the `/tmp` directory. diff --git a/docs/docs/guides/generator.mdx b/docs/docs/guides/generator.mdx index cc0b3ca524..03c38a4cd8 100644 --- a/docs/docs/guides/generator.mdx +++ b/docs/docs/guides/generator.mdx @@ -138,7 +138,7 @@ generator_definitions: This defines a generator definition with the following properties: - **name**: a unique name for the generator -- **file_path**: the relative file path to the file containing the generator as seen from within a git repository +- **file_path**: the relative file path to the file containing the generator as seen from within a Git repository - **targets**: the name of a group of which the members will be a target for this generator - **query**: the name of the GraphQL query used within this generator - **parameters**: the parameter to pass to the generator GraphQL query, in this case this we will pass the name of the object (widget) as the name parameter diff --git a/docs/docs/guides/installation.mdx b/docs/docs/guides/installation.mdx index fa0355b735..be65c06990 100644 --- a/docs/docs/guides/installation.mdx +++ b/docs/docs/guides/installation.mdx @@ -8,21 +8,35 @@ import ReferenceLink from "../../src/components/Card"; # Installing Infrahub -Infrahub is composed of multiple components. The backend is mostly written in Python and the frontend in React. +Infrahub is deployed as a container-based architecture, comprised of multiple components. The main components are: -The main components are: - -- A **Frontend** written in react. +- A **Frontend** written in React. - An **API server** written in Python with FastAPI. - A **Git agent** to manage the interaction with external Git repositories. -- A **Graph database** based on `Neo4j` 5.x. +- A **Graph database** based on `Neo4j`. - A **Message bus** based on `RabbitMQ`. +- A **Cache** based on `redis`. -Refer to [Architecture](/topics/architecture) for a more in-depth view of the components interaction. +Refer to [Architecture](/topics/architecture) for a more in-depth view of the components' interaction. ## Hardware requirements -Systems on which you want to install Infrahub, have to meet the [hardware requirements](/topics/hardware-requirements). +Please ensure the systems on which you want to install Infrahub meet the [hardware requirements](/topics/hardware-requirements). + +## Quick start via curl + +To quickly test Infrahub locally: + +```bash +curl https://infrahub.opsmill.io | docker compose -f - up -d +``` + +Alternative examples: + +```bash +curl https://infrahub.opsmill.io/develop | docker compose -f - up -d +curl https://infrahub.opsmill.io/0.13.0 | docker compose -f - up -d +``` ## From Git repository @@ -142,12 +156,20 @@ invoke demo.build demo.start demo.load-infra-schema demo.load-infra-data ### GitHub Codespaces -The project is pre-configured to run in GitHub Codespaces. We have two devcontainer configuration: +The Infrahub GitHub repository is designed to launch an instance via [GitHub Codespaces](https://docs.github.com/en/codespaces/overview). We have two devcontainer configurations: -- Infrahub: bare-bones container with the app running without any [Schema extension](/tutorials/getting-started/schema) or data -- Infrahub-demo: container running the [demo environment](/topics/local-demo-environment.mdx) +- **infrahub:** a deployment running without any [Schema](/tutorials/getting-started/schema) or data pre-installed +- **infrahub-demo:** a deployment running the [demo environment](/topics/local-demo-environment) -The default devcontainer `.devcontainer/devcontainer.json` is the bare-bones one. If you want to run the demo, you will need to choose it in your GitHub Codespaces options. +| No Data | Demo Data | +|---|---| +| [![Launch in GitHub Codespaces (No Data)](https://img.shields.io/badge/Launch%20Infrahub-0B6581?logo=github)](https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=stable) | [![Launch in GitHub Codespaces (Demo Data)](https://img.shields.io/badge/Infrahub%20with%20Data-0B6581?logo=github)](https://codespaces.new/opsmill/infrahub?devcontainer_path=.devcontainer%2Fdevcontainer.json&ref=stable) | + +:::note + +The default devcontainer `.devcontainer/devcontainer.json` launches Infrahub with no schema or data. If you want to launch a deployment with the demo schema and data, you will need to choose the alternate `Dev container configuration` in the GitHub Codespaces creation options. + +::: @@ -195,7 +217,7 @@ infrahubServer: INFRAHUB_DB_TYPE: neo4j INFRAHUB_LOG_LEVEL: INFO INFRAHUB_PRODUCTION: "true" - INFRAHUB_SECURITY_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec + INFRAHUB_INITIAL_ADMIN_TOKEN: 06438eb2-8019-4776-878c-0941b1f1d1ec INFRAHUB_SECURITY_SECRET_KEY: 327f747f-efac-42be-9e73-999f08f86b92 INFRAHUB_STORAGE_DRIVER: s3 AWS_ACCESS_KEY_ID: xxxx @@ -233,3 +255,9 @@ nfs-server-provisioner: ```bash helm install infrahub -f values.yml path/to/infrahub/chart ``` + +You can also install the chart using the OpsMill registry. + +```bash +helm install infrahub -f values.yml oci://registry.opsmill.io/opsmill/chart/infrahub +``` diff --git a/docs/docs/guides/jinja2-transform.mdx b/docs/docs/guides/jinja2-transform.mdx index 5db92173ec..9ad891f941 100644 --- a/docs/docs/guides/jinja2-transform.mdx +++ b/docs/docs/guides/jinja2-transform.mdx @@ -1,8 +1,8 @@ --- -title: Creating a Jinja Transform +title: Creating a Jinja transform --- -# Creating a Jinja rendered File (Transform) +# Creating a Jinja rendered file (transform) Within Infrahub a [Transform](/topics/transformation) is defined in an [external repository](/topics/repository). However, during development and troubleshooting it is easiest to start from your local computer and run the render using [infrahubctl render](/infrahubctl/infrahubctl-render). @@ -24,7 +24,7 @@ As the first step we need to have some data in the database to actually query. Create three tags, called "red", "green", "blue", either using the frontend or by submitting three GraphQL mutations as per below (just swapping out the name of the color each time). -```GraphQL {1-2} +```GraphQL mutation CreateTags { BuiltinTagCreate( data: {name: {value: "red"}, description: {value: "The red tag"}} @@ -39,7 +39,7 @@ mutation CreateTags { The next step is to create a query that returns the data we just created. The rest of this guide assumes that the following query will return a response similar to the response below the query. -```GraphQL {1-2} +```GraphQL query TagsQuery { BuiltinTag { edges { @@ -109,7 +109,7 @@ mkdir tags_render Then save the below query as a text file named tags_query.gql. -```GraphQL {1-2} +```GraphQL query TagsQuery($tag: String!) { BuiltinTag(name__value: $tag) { edges { @@ -134,7 +134,7 @@ Here the query will require an input parameter called `$name` what will refer to } ``` -## 2. Create the Jinja Template +## 2. Create the Jinja template The next step is to create the actual Jinja Template file. Create a file called tags_tpl.j2 diff --git a/docs/docs/guides/object-storage.mdx b/docs/docs/guides/object-storage.mdx new file mode 100644 index 0000000000..fd5c21a49f --- /dev/null +++ b/docs/docs/guides/object-storage.mdx @@ -0,0 +1,89 @@ +--- +title: Using the object-storage +--- + +In this guide we will be showing you how you can store and retrieve objects or files in Infrahub's object-storage. +For more information on the object-storage please see the [object-storage topic](/topics/object-storage). + +## Uploading a file to the object-storage + +To upload a file to the object-storage we can use the `/api/storage/upload/file` REST API endpoint. + +Create a file on your system. You can save the file anywhere you want, with any filename you want. But in this guide we will be using `/tmp/test.json` + +```json +{ + "key": "value", + "list": [ + "item1", + "item2", + "item3" + ] +} +``` + +We will be using the `curl` command to upload the file. + +:::note + +You might have to change the X-INFRAHUB-KEY header value to the API token of your user, if you are not using the default. + +::: + +```sh +curl -X POST --header "X-INFRAHUB-KEY: 06438eb2-8019-4776-878c-0941b1f1d1ec" http://localhost:8000/api/storage/upload/file -F file=@/tmp/test.json +``` + +The response will be a JSON object representing the object in the object-storage. Take note of the identifier. + +```json +{"identifier":"17d198df-3102-00e0-3349-c51ae276e246","checksum":"f4516d51f2c894fc47df1782c6661ebc"} +``` + +## Retrieving the object from the object-storage + +To retrieve objects from the object-storage we can use the `/api/storage/object/` REST API endpoint. +The identifier in the URL should be the identifier that you gathered from the previous step. + +:::note + +You might have to change the X-INFRAHUB-KEY header value to the API token of your user, if you are not using the default. + +::: + +```curl +curl --header "X-INFRAHUB-KEY: 06438eb2-8019-4776-878c-0941b1f1d1ec" http://localhost:8000/api/storage/object/17d198df-3102-00e0-3349-c51ae276e246 +{ + "key": "value", + "list": [ + "item1", + "item2", + "item3" + ] +} +``` + +## Storing objects in the object-storage + +You can upload any string based object into the object-storage, as an alternative to uploading a file. +In this step we will be storing the string "interface Ethernet1\n description: Connected to Ethernet2" into the object-storage. + +:::note + +You might have to change the X-INFRAHUB-KEY header value to the API token of your user, if you are not using the default. + +::: + +```sh +curl -X POST --header "Content-Type: application/json" --header "X-INFRAHUB-KEY: 06438eb2-8019-4776-878c-0941b1f1d1ec" http://localhost:8000/api/storage/upload/content --data '{"content": "interface Ethernet1\n description: Connected to Ethernet2"}' +``` + +```json +{"identifier":"17d19962-4420-4972-334d-c51beb03e477","checksum":"843cde3df258ab3027618712952499cd"} +``` + +Retrieving the object works as described in the previous step. + +```sh +curl --header "X-INFRAHUB-KEY: 06438eb2-8019-4776-878c-0941b1f1d1ec" http://localhost:8000/api/storage/object/17d19962-4420-4972-334d-c51beb03e477 +``` diff --git a/docs/docs/guides/repository.mdx b/docs/docs/guides/repository.mdx index be44e62719..e526aafea2 100644 --- a/docs/docs/guides/repository.mdx +++ b/docs/docs/guides/repository.mdx @@ -4,14 +4,14 @@ title: Adding/updating external repositories import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; -# Summary +# External repositories Infrahub supports two different types of connections to external Git repositories: - [**CoreRepository**](/topics/repository#core-repository) fully integrates with Git version control, including branch tracking and two-way branch synchronization. - [**Read-only Repository**](/topics/repository#read-only-repository) links a particular branch in Infrahub to a particular ref in the Git repository. It will only read from the Git repository. It will never make any changes to the external repository. -## Personal access token {#personal-access-token} +## GitHub personal access token {#personal-access-token}
Generate a GitHub fine-grained personal access token @@ -156,7 +156,9 @@ Read-only repositories and CoreRepositories work in different ways when it comes The [Infrahub Git agent](/reference/git-agent) checks for changes in external repositories several times per minute. If there are no conflicts between the remote and the Infrahub branches, the Git agent will automatically pull any new changes into the appropriate Infrahub branch. -### Read-only repository + +### Read-only Repository + Infrahub does not automatically update Read-only Repositories with changes on the external repository. To pull in changes from the external repository you must either set the `ref` **and/or** `commit` of the Read-only Repository to the desired value. You can perform this update either through the user interface or via an update mutation through the GraphQL API. Either way, the Infrahub web server will use the Git agent to retrieve the appropriate changes in a background task. @@ -188,6 +190,8 @@ Infrahub does not automatically update Read-only Repositories with changes on th When a [Proposed Change](/topics/proposed-change) is merged, if the source and destination Infrahub branches are both linked to branches on the same external Git repository, then Infrahub will handle merging the branches on the external Git repository. This is the only time that Infrahub will push changes to the external repository. Other changes made within Infrahub will not be pushed to an external repository and **could potentially be overwritten** when Infrahub pulls new commits from the external repository. + ### Read-only Repository + No changes to objects owned by a Read-only Repository are ever pushed to the external Git repository. diff --git a/docs/docs/guides/schema.mdx b/docs/docs/guides/schema.mdx index 99c574d91a..e79b859089 100644 --- a/docs/docs/guides/schema.mdx +++ b/docs/docs/guides/schema.mdx @@ -29,6 +29,12 @@ extensions: {infrastructureExtensionRackYaml}
+:::note + +To help with the development process of a schema definition file, you can leverage [schema validation](/reference/schema-validation) within your editor. + +::: + ## Load a schema file Schema files can be loaded into Infrahub with the `infrahubctl` command or directly via the Git integration. diff --git a/docs/docs/infrahubctl/infrahubctl-branch.mdx b/docs/docs/infrahubctl/infrahubctl-branch.mdx index dfcebaebf9..1a6c0b3e77 100644 --- a/docs/docs/infrahubctl/infrahubctl-branch.mdx +++ b/docs/docs/infrahubctl/infrahubctl-branch.mdx @@ -43,7 +43,6 @@ $ infrahubctl branch create [OPTIONS] BRANCH_NAME * `--description TEXT`: Description of the branch * `--sync-with-git / --no-sync-with-git`: Extend the branch to Git and have Infrahub create the branch in connected repositories. [default: no-sync-with-git] -* `--isolated / --no-isolated`: Set the branch to isolated mode [default: no-isolated] * `--config-file TEXT`: [env var: INFRAHUBCTL_CONFIG; default: infrahubctl.toml] * `--help`: Show this message and exit. diff --git a/docs/docs/integrations/infrahub-ansible/readme.mdx b/docs/docs/integrations/infrahub-ansible/readme.mdx new file mode 100644 index 0000000000..e17cfd7e97 --- /dev/null +++ b/docs/docs/integrations/infrahub-ansible/readme.mdx @@ -0,0 +1,13 @@ +--- +title: Infrahub Ansible collection +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Infrahub Ansible collection + + +OpsMill maintains the [opsmill.infrahub Ansible Collection](https://galaxy.ansible.com/ui/repo/published/opsmill/infrahub/). + + +Please see the [infrahub-ansible documentation](https://infrahub-ansible.readthedocs.io/en/latest/) for installation and usage details. diff --git a/docs/docs/integrations/nornir-infrahub/readme.mdx b/docs/docs/integrations/nornir-infrahub/readme.mdx new file mode 100644 index 0000000000..5889215060 --- /dev/null +++ b/docs/docs/integrations/nornir-infrahub/readme.mdx @@ -0,0 +1,11 @@ +--- +title: Nornir plugin for Infrahub +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Nornir plugin for Infrahub + + +OpsMill maintains the [nornir-infrahub](https://github.com/opsmill/nornir-infrahub) plugin for Infrahub. Infrahub can be used as an inventory source for Nornir. + \ No newline at end of file diff --git a/docs/docs/integrations/readme.mdx b/docs/docs/integrations/readme.mdx new file mode 100644 index 0000000000..e04d93c66a --- /dev/null +++ b/docs/docs/integrations/readme.mdx @@ -0,0 +1,18 @@ +--- +title: Infrahub integrations +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +# Infrahub integrations + +OpsMill maintains multiple integrations with other infrastructure systems. + +## Integrations + + +- [infrahub-ansible](./infrahub-ansible/) +- [infrahub-sync](./sync/) +- [nornir-infrahub](./nornir-infrahub/) + \ No newline at end of file diff --git a/docs/docs/sync/guides/creation.mdx b/docs/docs/integrations/sync/guides/creation.mdx similarity index 88% rename from docs/docs/sync/guides/creation.mdx rename to docs/docs/integrations/sync/guides/creation.mdx index fe60cca523..0a1e2d309a 100644 --- a/docs/docs/sync/guides/creation.mdx +++ b/docs/docs/integrations/sync/guides/creation.mdx @@ -1,10 +1,10 @@ --- -title: Creating a New Sync Instance +title: Creating a new sync instance --- -# Creating a new Sync instance +# Creating a new sync instance -This guide will walk you through the steps to create a new Sync Instance for Infrahub Sync, allowing you to synchronize data between your source and destination systems efficiently. +This guide will walk you through the steps to create a new sync instance for infrahub-sync, allowing you to synchronize data between your source and destination systems efficiently. ## Step 1: Define your configuration @@ -60,4 +60,4 @@ schema_mapping: reference: "InfraDevice" ``` -For more information on customizing your sync configuration and troubleshooting, see the [Sync Instance configuration reference](/sync/reference/config) \ No newline at end of file +For more information on customizing your sync configuration and troubleshooting, see the [Sync Instance configuration reference](../reference/config) diff --git a/docs/docs/integrations/sync/guides/installation.mdx b/docs/docs/integrations/sync/guides/installation.mdx new file mode 100644 index 0000000000..dad9d866a9 --- /dev/null +++ b/docs/docs/integrations/sync/guides/installation.mdx @@ -0,0 +1,12 @@ +--- +title: Installing Infrahub sync +--- +# Installing Infrahub sync + +Infrahub Sync is available on [PyPI](https://pypi.org/project/infrahub-sync/) and can be installed using the pip package installer. It is recommended to install the Sync into a virtual environment. + +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install infrahub-sync +``` diff --git a/docs/docs/sync/guides/run.mdx b/docs/docs/integrations/sync/guides/run.mdx similarity index 92% rename from docs/docs/sync/guides/run.mdx rename to docs/docs/integrations/sync/guides/run.mdx index 46975eaea4..87bccf7e57 100644 --- a/docs/docs/sync/guides/run.mdx +++ b/docs/docs/integrations/sync/guides/run.mdx @@ -1,19 +1,19 @@ --- -title: Running Sync Tasks +title: Running sync tasks --- # Running sync tasks with Infrahub Sync Learn how to use Infrahub Sync's commands to generate sync adapters, calculate differences, and synchronize data between your source and destination systems. -![Infrahub-Sync process](../../media/infrahub_sync_process.excalidraw.svg) +![Infrahub-Sync process](../../../media/infrahub_sync_process.excalidraw.svg) -## Generating Sync Adapters and Models +## Generating sync adapters and models Before you can run a synchronization task, you need to generate the necessary Python code for your sync adapters and models based on your configuration. -To create a new configuration, please refer to the guide [Creating a new Sync Instance](/sync/guides/creation) +To create a new configuration, please refer to the guide [Creating a new Sync Instance](./creation) ### Command diff --git a/docs/docs/integrations/sync/readme.mdx b/docs/docs/integrations/sync/readme.mdx new file mode 100644 index 0000000000..8d2170b854 --- /dev/null +++ b/docs/docs/integrations/sync/readme.mdx @@ -0,0 +1,20 @@ +--- +title: Infrahub Sync +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +# Infrahub Sync + +Infrahub Sync is a versatile Python package that synchronizes data between a source and a destination system. It builds on the robust capabilities of `diffsync` to offer flexible and efficient data synchronization across different platforms, including Netbox, Nautobot, and Infrahub. This package features a Typer-based CLI for ease of use, supporting operations such as listing available sync projects, generating diffs, and executing sync processes. + +## Guides + +- [Installing Infrahub Sync](./guides/installation) +- [Creating a new sync instance](./guides/creation) +- [Run a sync instance](./guides/run) + +## Reference + +- [Sync instance configuration](./reference/config) diff --git a/docs/docs/sync/reference/cli.mdx b/docs/docs/integrations/sync/reference/cli.mdx similarity index 100% rename from docs/docs/sync/reference/cli.mdx rename to docs/docs/integrations/sync/reference/cli.mdx diff --git a/docs/docs/sync/reference/config.mdx b/docs/docs/integrations/sync/reference/config.mdx similarity index 100% rename from docs/docs/sync/reference/config.mdx rename to docs/docs/integrations/sync/reference/config.mdx diff --git a/docs/docs/media/branch_conflict.excalidraw.svg b/docs/docs/media/branch_conflict.excalidraw.svg index 294ec2b6f9..b82e021da7 100644 --- a/docs/docs/media/branch_conflict.excalidraw.svg +++ b/docs/docs/media/branch_conflict.excalidraw.svg @@ -1,21 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO19aVNcIt2y7vf3V3T0+XpYe61cXPOJuHFcdTAwMDOcXHUwMDExVFRQvH3CYFx1MDAxZWRcdTAwMTJQwVx1MDAxZPu/31xc9kA1UFiMVrfFjt3dL6VUUZVPPjnnv//58uXrcNyrfP2fL18ro1Kh1Sj3XHUwMDBiL1//273/XFzpXHUwMDBmXHUwMDFh3Vx1MDAwZVx1MDAxZYK3/1x1MDAxZXSf+qW3n6xcdTAwMGaHvcH//Otf7UL/oTLstVxupVxueW5cZp5cbq3B8Knc6JJSt/2vxrDSXHUwMDFl/F/351mhXfk/vW67POyTyUlilXJj2O1/P1elVWlXOsNcdTAwMDF++v/D//7y5d9vf3qublhcdTAwMTlcct9+9u1dz7WBmX73rNt5u06tpbTG2F/HXHUwMDFig3080bBSxoNVvNjK5Ih76+tB7ag8SNb0gy2f7jPbOMvd554mJ602Wq2r4bj1dj2DLn6NybHBsN99qNw0ysM6XHUwMDFlZVPv+/1Wv/tUq3cqg8Fvv9PtXHUwMDE1So3h2L1H6a93XHUwMDBindrbZ0zeXHUwMDE5uZ8wnCjglGnJXHUwMDE1pYrKX4fdXHUwMDA3xFx1MDAwMIBcdTAwMTJcbnhIXGLDqLVTV7bXbeEzwCv7L/r2mlxcW7FQeqjhXHUwMDA1dsqTnzFQsqwy+ZmXXHUwMDFm31x1MDAxN1x1MDAxOFx1MDAxMdZaI7RggGfhk2dSrzRq9aH7mcmVXH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sbOBcZjzl8qEgXHUwMDE4s1x1MDAwYpLgLot7ya1qXHUwMDBl4vNcdTAwMWKdtvbdglx1MDAwM1tcZlx1MDAwNlx1MDAwZlx1MDAxY7Oca1x1MDAwNDXH1MxY7VZcdTAwMTZbkfLzRad1kzYwMPryQ8RcdTAwMGZrXHUwMDFi2EKYIzGNjHGw4IpcdTAwMGXGskHSeI5uhURcIilcdTAwMTM7xcBbZGBcdTAwMGJzdJ6CXGZNJYRVJFx1MDAwZd6sureRLVxceMb1I1x1MDAxYeayrL6xhL+nZpKHyLifwWlz1YnvKX/5iS3BL999XCKj7/3tcP/4f34kYIjBvYuGdI0mXHQ7uy35UGtcdTAwMTWaXCLei9+m00zUW5nHZmGwVPW7fPdcdTAwMGW09lxcjldqQc/XjmtfXHUwMDAxnlx1MDAwMuk8KuvAXHUwMDE13I41XHUwMDBi+lx1MDAwYmVRKFx1MDAxNVZlTTruXHUwMDFh+JszUD7BN0ZhRLjSXG5mtyVP6lxubFwieZMqXHUwMDFhedG9278/SFx1MDAwZvthX8xGeS6XKlxyd9Mxxy1J40layG6qJnJcZktcdTAwMDJKolx1MDAxNcY/rHprSv5ewp9rSv7zS2F9z3e7P+ei/JZcZvSK6qVft/126u9cdTAwMGb18mNsktHz8nHl7y+QduApv4iZ//zzn/9cdTAwMGZcdTAwMGW6RdAifQ== - T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B24CreateBranchInitialStateUpdateObject AUpdateObject A13UpdateObject BMerge OperationWith Conflict3Identify Conflicts434A4 DROP223B3 KEEP33T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B24CreateBranchInitialStateUpdateObject AUpdateObject A13UpdateObject BRebase OperationWith Conflict3Identify Conflicts434A4 DROP223B3 KEEP33 \ No newline at end of file + T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B24CreateBranchInitialStateUpdateObject AUpdateObject A13UpdateObject BMerge OperationWith Conflict3Identify Conflicts434A4 DROP223B3 KEEP33T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B24CreateBranchInitialStateUpdateObject AUpdateObject A13UpdateObject BRebase OperationWith Conflict3Identify Conflicts434A4 DROP223B3 KEEP33 \ No newline at end of file diff --git a/docs/docs/media/branch_merge.excalidraw.svg b/docs/docs/media/branch_merge.excalidraw.svg index c323d607d6..5d5c7e609f 100644 --- a/docs/docs/media/branch_merge.excalidraw.svg +++ b/docs/docs/media/branch_merge.excalidraw.svg @@ -1,21 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO2daVPjvLKAv8+voDhfX/RKaq2n6tYtXHUwMDEyQibsW4blvqeoLE4wOFx1MDAwYtkgnJr/flthhlx1MDAxOCdcdTAwMDaHJWTA+TCL7ViO1Y+6W91q/ffb0tJyb9j2lv+9tOzdVkqBX+2Ubpb/csdcdTAwMDdep+u3mniKj/7fbfU7ldGVXHUwMDE3vV67+++//26UOlder1x1MDAxZJQqXHUwMDFlXHUwMDE5+N1+Kej2+lW/RSqtxt9+z2t0/9f9uVNqeP/TbjWqvVx1MDAwZVx1MDAxOTey4lX9Xqtz35ZcdTAwMTd4XHKv2evi3f9cdTAwMGb/v7T039Gfoafrebe90bWjo6FnMzx6dKfVXHUwMDFjPSeTwClTituHK/zuXHUwMDFhNtXzqni6ho/rjc+4Q8uZnKdZ1dROr2rHXHUwMDE3xaw3POh6rXGzNT9cYlx1MDAwZXvDYPRE3Vx1MDAxNv6Q8blur9O68o79au/CtVx1MDAxZDlcdTAwMWX3rU6rX79oet3uo++02qWK31x1MDAxYrpjlD5cdTAwMWMtNeuje4yP3LorNCfMXHUwMDAwo0ppyqjm4uG0u8GKVYowzlx1MDAwMVx1MDAwNKeKXHRcbpEny7ZcdTAwMDLsXHUwMDA1fLJ/0dFn/GzlUuWqjlx1MDAwZtisjq8xvGK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WDx++HirOUyxlmr825yT5n9Xgq2mXHUwMDE2x3LFXHUwMDA1lcbFY0dcbsehV6yVK9SmXHUwMDA15fEzrH9kfi1MIZ3jjPLF59e+oS8+Ob/2tdiHeaVMv7Q4UMspKjpu57eK5c1q+lZXd3i311kvbt+Xkq5cdTAwMTa1q5qs0Z7mxlXlflx0plx1MDAxMlx1MDAxY/WRQeVcdK6IjolfupWA2IerLUz1LJZcIi/cJn+Xklx0j1x1MDAxNNHsNDBcdTAwMWNATjH12jutXFxfXHUwMDFmXFxxc31cdTAwMWGkK8HhXYHtnyVbltF+I9atkFx1MDAxN2hhS1x1MDAxMXUvXehcdTAwMDNlh6H5pCyaV8lcYn1IM1hysvgqiPPTMr/nzCunsWF0wJHLoOsxxY4vR/zYdPfbwU11N3vSyJxlq3s2k2z81lx1MDAxOEXnhWsuXWaoXHUwMDExOpqFxihcYsJcZnpgOFx1MDAxMKHAvbK52yTaxEDJMm+UQNRUxFx1MDAxOFRcdTAwMTNoamJbxJg9X5QkoLTAkcBlsUJ4XHUwMDE2+NfiYOHmp2ay5cuCqTSEa8241Hg7KkG8uOi1kmxeq+p93W96rUJcdTAwMDdF+Vx1MDAxZlx1MDAxNOav6Ua9XHUwMDEy+KXOfPmdrCVcdTAwMTOhLd+Htnxlh1x1MDAwN6uUMsJOsa3Lte7T46P80dnWRkpWb9KbxWpZJ1x1MDAxYm1UZoQrXG5cdTAwMWOtq8HU1Uuw8f2g+2ZBU7dVtYiv1zbX9Vx1MDAxOKhZlVswvPCgykdcdTAwMTmePKgyQGVBdVx1MDAxNMc/eqpwypdfMzXfXG7N5mPy+JMpjl3nl3+9jmEzvvV87y41ztFcdTAwMTh83DzQXHUwMDAwdceUN7Drf375+f/bUORkIn0= - T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B23CreateBranchInitialStateUpdateObject AUpdateObject A12UpdateObject B32Merge OperationNo ConflictMergeBranch \ No newline at end of file + T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B23CreateBranchInitialStateUpdateObject AUpdateObject A12UpdateObject B32Merge OperationNo ConflictMergeBranch \ No newline at end of file diff --git a/docs/docs/media/branch_rebase_no_conflict.excalidraw.svg b/docs/docs/media/branch_rebase_no_conflict.excalidraw.svg index 07fe7ed624..22e4ef076b 100644 --- a/docs/docs/media/branch_rebase_no_conflict.excalidraw.svg +++ b/docs/docs/media/branch_rebase_no_conflict.excalidraw.svg @@ -1,21 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO2d6VNcIsm2wL/PX9Hh/Trm5L7ciFx1MDAxNy9UUFFcdTAwMTFcdTAwMDTF5c1ccqOAXHUwMDAyS1ZZZLkx//s7ia2UXHUwMDA1hVx1MDAwNVx1MDAwMtItxMR0d1VRVWSe31ky85z871x1MDAxZj9+7HRcdTAwMDZNd+ffP3bcfsGpesWW09v501x1MDAxZX92W22vUYdTdPTvdqPbKoyufOh0mu1///VXzWlV3E6z6lx1MDAxNFxc9Oy1u0613elcdTAwMTa9XHUwMDA2KjRqf3lcdTAwMWS31v5f+/9zp+b+T7NRK3ZaaPyQXbfodVx1MDAxYa2XZ7lVt+bWO224+//Bv3/8+O/o/76367j9zuja0VHfu1FcdTAwMTk8et6oj96TYiGUppSLtyu8dlxmXHUwMDFl1XGLcLpcdTAwMDSv647P2EM7d/vq4U7krujgMn/1LG7aXHUwMDBmpVZq/NiSV61mO4Pq6I3aXHL4IeNz7U6rUXGvvWLnXHUwMDAxzpLA8bBvtVx1MDAxYd3yQ91tt999p9F0XG5eZ2CPYfx21KmXR/dcdTAwMThcdTAwMWbp2yuUQVxcaKNcdTAwMTRhRlHD9dtpe4NdXCIkQ4ZxqVx1MDAwNZeGMmNcdTAwMDKvdtCoQjfAq/1cdTAwMGKPPuOXyzuFSlx1MDAxOd6wXlx1MDAxY1+jacFcdTAwMTB3fE3v51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HJUaftcdTAwMTVcXLhIK0+Zt1x1MDAxNLnl4MdNTTN8Mlx1MDAxMFxipftB7/HcKlx1MDAwMiSdXHUwMDE5uUDCXHUwMDBlXHUwMDE3w3Jccum3XHUwMDA278Bj1MjEXHUwMDAzPVx1MDAxNHBpxFij/Fx1MDAxM1x1MDAxM6b++HmBb36r9SOC/NfboFx1MDAwZVx1MDAxOJZ/iuBhI3x7XGKD3uYkOlx1MDAwNlx1MDAxZjdcdTAwMDY9aFAnLYJBb/z7j7//XHUwMDFml1qxXSJ9 - T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B23CreateBranchInitialStateUpdateObject AUpdateObject A12UpdateObject B32Rebase OperationNo ConflictRebaseBranch \ No newline at end of file + T1T2T3T4T5T5T6T7T8T9T101Object AObject BMain BranchBranch AObject AObject B23CreateBranchInitialStateUpdateObject AUpdateObject A12UpdateObject B32Rebase OperationNo ConflictRebaseBranch \ No newline at end of file diff --git a/docs/docs/media/demo_edge.excalidraw.svg b/docs/docs/media/demo_edge.excalidraw.svg index be733f6df5..c17903d92b 100644 --- a/docs/docs/media/demo_edge.excalidraw.svg +++ b/docs/docs/media/demo_edge.excalidraw.svg @@ -1,16 +1,21 @@ - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1daW9iSbL93r+iVPO1nZN7ZI709ORcdTAwMDUv5b28+2lkYcCAzWbA66j/+0TccptcdTAwMGJ3MZed0qOlriqWS5I34pyIyFj+88e3b9+7b63S9399+156LeRr1WI7//L9T3r+udTuVJtccnxJXHUwMDA2/+40n9qF4J2VbrfV+dc//1nPt1x1MDAxZkrdVi1fKLHnaucpX+t0n4rVJis06/+sdkv1zv/S/1x1MDAwZvL10v+0mvVit816X7JSKla7zfav7yrVSvVSo9vBq/9cdTAwMWb++9u3/1x1MDAwNP9cdTAwMGatrl0qdPONcq1cdTAwMTR8IHgptEBv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aa9mMVY0tLjR1Fx1MDAxMlx1MDAxMotmKTmBe5vhwLr+9HZdtSvq5FG9Pezmyuu5WmN/XHS0UjBqOmZcdTAwMTDsyJdcdTAwMThojiatRbxUXHUwMDBlfVNOffKnpJSSoTklg8orTeU/Iyilp440ZkY9t1x1MDAwM6VcdTAwMWN7WNP4Srm2yEq59qGUf3yw8fd8q3XSxY38NHjwXHUwMDE2VYtcdTAwMWa70bvm9+dq6WUtzm5cdTAwMGJcdTAwMWV01UDRSaVKgfX011x1MDAxZn/9XHUwMDE3ey/M1iJ9 + + - ord1-edge1ord1-edge2atl1-edge1atl1-edge2jfk1-edge1jfk1-edge2ORD1JFK1ATL1TransitPeeringTransitPeeringTransitPeeringProvider AProvider B \ No newline at end of file + ord1-edge1ord1-edge2atl1-edge1atl1-edge2jfk1-edge1jfk1-edge2ORD1JFK1ATL1TransitPeeringTransitPeeringTransitPeeringProvider AProvider B \ No newline at end of file diff --git a/docs/docs/media/demo_edge_topology.png b/docs/docs/media/demo_edge_topology.png index 688c41352a..355232fc96 100644 Binary files a/docs/docs/media/demo_edge_topology.png and b/docs/docs/media/demo_edge_topology.png differ diff --git a/docs/docs/media/design-data.excalidraw.svg b/docs/docs/media/design-data.excalidraw.svg new file mode 100644 index 0000000000..6ae34d6829 --- /dev/null +++ b/docs/docs/media/design-data.excalidraw.svg @@ -0,0 +1,21 @@ + + + + + + + + python scriptOther SoTsState / AssuranceDataInfra MgmtToolsinfrahub-syncinfrahubinfrahub-sdkGraphQLAPIinfrahubctl \ No newline at end of file diff --git a/docs/docs/media/design-interfaces.excalidraw.svg b/docs/docs/media/design-interfaces.excalidraw.svg new file mode 100644 index 0000000000..b68036834d --- /dev/null +++ b/docs/docs/media/design-interfaces.excalidraw.svg @@ -0,0 +1,21 @@ + + + + + + + + infrahub-sdkGraphQLGraphQLRESTinfrahubctlGraphQLRESTbrowser (frontend)infrahubAPI ServerGraphQLRESTinfrahubGit AgentGraphQLRPCGITgit repogit clientGIT \ No newline at end of file diff --git a/docs/docs/media/design-schema.excalidraw.svg b/docs/docs/media/design-schema.excalidraw.svg new file mode 100644 index 0000000000..1bfd488299 --- /dev/null +++ b/docs/docs/media/design-schema.excalidraw.svg @@ -0,0 +1,21 @@ + + + + + + + + Graph DB(neo4j)git repo(github, gitlab, etc.)schemainfrahubschema \ No newline at end of file diff --git a/docs/docs/media/design.excalidraw.svg b/docs/docs/media/design.excalidraw.svg new file mode 100644 index 0000000000..c861ab2ca0 --- /dev/null +++ b/docs/docs/media/design.excalidraw.svg @@ -0,0 +1,21 @@ + + + + + + + + unified storageobject store (local or S3 bucket)git repo(github, gitlab, etc.)Other SoTsState / AssuranceDataInfra MgmtToolsGraph DB(neo4j)infrahub-syncgeneratorstransformationsschemachecksartifacts3rd party containeror systemuser-providedcode to infrahubcode-generatedoutput from infrahubinfrahub open-sourcecontainer or systemLegendinfrahub-bundledcontainer or systemmessage bus(rabbit-mq)cache(redis)infrahubdeployment systems(ansible, nornir, terraform, etc)nornir-infrahubinfrahub-ansibleschemainfrahub-sdkGraphQLAPIinfrahubctl \ No newline at end of file diff --git a/docs/docs/media/guides/check_proposed_change.png b/docs/docs/media/guides/check_proposed_change.png new file mode 100644 index 0000000000..b3d57a8169 Binary files /dev/null and b/docs/docs/media/guides/check_proposed_change.png differ diff --git a/docs/docs/media/high_level_architecture.excalidraw.svg b/docs/docs/media/high_level_architecture.excalidraw.svg index 60fce64d6b..79125a302f 100644 --- a/docs/docs/media/high_level_architecture.excalidraw.svg +++ b/docs/docs/media/high_level_architecture.excalidraw.svg @@ -1,16 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO19aVNcdTAwMWJZtu13/1xuh/vLvVx1MDAxMUX2mYeOePFcdTAwMDIwtsHMXHUwMDE4Y/t1h0NGXHUwMDAyXHUwMDA0QoAk8NDR//2tldgoM6VUpkBcZq5qqqJcXJbE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raphQLGITAMQBoltCypherCache(Redis)RedisGit AgentGit AgentAPI ServerAPI ServerFrontend \ No newline at end of file + Graph DB(neo4j)3rd party containeror systeminfrahub open-sourcecontainer or systemLegendinfrahub-bundledcontainer or systeminfrahub-sdkGraphQLGraphQLRESTinfrahubctlGraphQLRESTbrowser (frontend)infrahubAPI ServerGraphQLRESTinfrahubGit AgentGraphQLRPCmessage bus(rabbit-mq)cache(redis)repository store (NFS or local)git repoGQL (Cypher)AMQAMQREDISREDISGITNFSobject store (s3 bucket)https \ No newline at end of file diff --git a/docs/docs/media/high_level_architecture_ha.excalidraw.svg b/docs/docs/media/high_level_architecture_ha.excalidraw.svg index bc41f023df..7894d8d129 100644 --- a/docs/docs/media/high_level_architecture_ha.excalidraw.svg +++ b/docs/docs/media/high_level_architecture_ha.excalidraw.svg @@ -1,21 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO19aU9cdTAwMWJb2u33/FxulP7Sr9Su3vPQ0tVcdTAwMTVTXHUwMDEyQpghJLn9KjLYgFx1MDAxOcxkIKTV//2uVSS4quyyy2DAnHPcrUOCne1dez/Deub/vJmaetu5PWu+/dfU2+aP3fpxq3FRv3n7XHUwMDBm/v66eXHZOm3jLZX+/fL06mI3/eRBp3N2+a9//vOkfnHU7JxcdTAwMWTXd5vJdevyqn582blqtE6T3dOTf7Y6zZPL/8v/LtdPmv/n7PSk0blIul9SazZandOLu+9qXHUwMDFlN0+a7c4lVv9/+PvU1H/S/2Z2d9Hc7dTb+8fN9Fx1MDAxZqRvdTdobCz+dvm0nW5WmiB18Mqb+0+0LufwfZ1mXHUwMDAzb+9hz83uO/zV24Xa+tl2/d3SQlxc+HS9uvbp4Hhh90v3a/dax8dcdTAwMWKd2+N0W5eneJrue5edi9Oj5nar0Tn4fW6Z35f9q4vTq/2DdvOSjy/vf3t6Vt9tdW7xOy3uf3l3XHUw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vdl8y6Dm89K+mOeXQm1x1MDAxMGA6KSfy4EOqJK1cdTAwMDcg+DY2OlNcdTAwMWWaqVx1MDAwMj9K62GFSGSwtqTZrOrpXHUwMDAxXHUwMDA2ac64jHhBr61cdTAwMTVaiUx3smeo8vvX1HqzgVxy1tu7t1Ok/cbUaXtqbnlcdTAwMDNcdTAwMWbrz7DHzb3OXHUwMDEzsGvVvVRcbsH85tw3v7T42/rZ2UZcdTAwMDdnfVx1MDAwZnlwua3Gr1x1MDAwM+vu6+11q3kz06/RSfpiXHUwMDFjOJVcdTAwMDZkuyYv8z//ffPf/1x1MDAwZrpnVXcifQ== + - BrowserinfrahubctlGit ServerGraph DB(Memgraph or Neo4j)Message Bus(Rabbit MQ)GraphQLGraphQLRestRPCGraphQLGITAMQBoltCypherCache(Redis)RedisGit AgentGit AgentAPI ServerAPI ServerFrontendLB (HA Proxy)Object Store(S3)BackupBackupBackupRepository Storage On DiskNFSHTTPSLB : Redundancy based on DNS \ No newline at end of file + Graph DB(neo4j)3rd party containeror systeminfrahub open-sourcecontainer or systemLegendinfrahub-bundledcontainer or systeminfrahub-sdkinfrahubctlbrowserinfrahubGit Agentmessage bus(rabbit-mq)cache(redis)repository store (NFS or local)git repoLoad Balancer(HA Proxy)infrahubAPI Server*System needsbackup**object store (s3 bucket)* \ No newline at end of file diff --git a/docs/docs/media/infrahub-readme.gif b/docs/docs/media/infrahub-readme.gif new file mode 100644 index 0000000000..d19b082383 Binary files /dev/null and b/docs/docs/media/infrahub-readme.gif differ diff --git a/docs/docs/media/infrahub-readme.png b/docs/docs/media/infrahub-readme.png new file mode 100644 index 0000000000..0adbea45a8 Binary files /dev/null and b/docs/docs/media/infrahub-readme.png differ diff --git a/docs/docs/media/otto.png b/docs/docs/media/otto.png new file mode 100644 index 0000000000..50692cbbad Binary files /dev/null and b/docs/docs/media/otto.png differ diff --git a/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_form.png b/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_form.png new file mode 100644 index 0000000000..eaa4d5d1bf Binary files /dev/null and b/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_form.png differ diff --git a/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_overview.png b/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_overview.png new file mode 100644 index 0000000000..96400367a8 Binary files /dev/null and b/docs/docs/media/release_notes/infrahub_0_14_0/resource_manager_overview.png differ diff --git a/docs/docs/media/repository_architecture.excalidraw.svg b/docs/docs/media/repository_architecture.excalidraw.svg index f693c0dafe..8799249a6f 100644 --- a/docs/docs/media/repository_architecture.excalidraw.svg +++ b/docs/docs/media/repository_architecture.excalidraw.svg @@ -1,21 +1,21 @@ - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nOVbaVPbSFx1MDAxM/7Or6DYr0GZ+0jVW29xbMBcXFx1MDAwYlx1MDAwMV6WbLYoYVx0WyBLiiRzbeW/b49irMOWL2xi6jVVXHUwMDA2Zsajnpl++unuaf+zsrq6lj5F7tqn1TX3sWn7nlx1MDAxM9tcdTAwMGZrXHUwMDFmTPu9XHUwMDFiJ15cdTAwMThAXHUwMDE3yf5Pwm7czEa20zRKPn382LHjOzeNfLvpWvde0rX9JO06Xmg1w85HL3U7yX/N+5Hdcf9cdTAwMTOFXHUwMDFkJ42t/CHrruOlYfzzWa7vdtwgTWD2v+D/1dV/sveCdLHbTO2g5bvZXHUwMDA3sq5cXECMWbX1KFxmMmE1pohcIqL6/V6yXHJPS11cdTAwMDc6b0BiN+9xslx1MDAwN21cdTAwMWafUW9cdTAwMWRvuc9xeL733L2/ujrKXHUwMDFmeuP5/mn65GdCJSGsJe9L0ji8cy88J22/7Fqhve5TcdhttVx1MDAwMzcxi8f91jCym176ZNpcdTAwMTDqt/7cgU+recujeVx1MDAxMmeWQPBcdTAwMTJcdTAwMThRjrnIXHUwMDFmbSYgRNd1/5RsK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wMDFlXHRcIlx1MDAxNlx1MDAxMrWlkXSB6VStsm8nQHhgvns07MZjSJGHYlx1MDAwMFx1MDAwMVxc/N7Wr2BJ8/NmXHUwMDAw3IntqH1y8C047KZ2XG5cdTAwMWE6c4XHrHBcdTAwMWMlwVSlXHUwMDFjKz2Pec2OolOYyu1cdTAwMDdcdTAwMTdwjJ7T25pcXJa1e8992Fx1MDAxY9Sr326yl1x0yDLAXHUwMDFiaLlZiPhj5ce/lXC/XFwifQ== + - Infrahub Web ServerMessageBrokerGit AgentRemote RepositoriesRPCHTTPAMQPGraphQLMutations \ No newline at end of file + Infrahub Web ServerMessage BrokerGit AgentRemote RepositoriesRPCHTTPAMQPGraphQLMutations \ No newline at end of file diff --git a/docs/docs/media/temporal_graph.excalidraw.svg b/docs/docs/media/temporal_graph.excalidraw.svg index bee825251a..c3bb0bb62d 100644 --- a/docs/docs/media/temporal_graph.excalidraw.svg +++ b/docs/docs/media/temporal_graph.excalidraw.svg @@ -1,16 +1,21 @@ - + - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1daVNcItuy/d6/oqPv12PdvXNPuU/Ei1x1MDAxN47t3Nri+O5cclx1MDAwM6FQlEnA8cb57y+TtqWoospCQcFzOXFapaDYVOVaOef+z5evX791XHUwMDFmWuG3P79+XHUwMDBi70vFWrXcLt59+4Ofv1xy251qs0GHoPd3p3nTLvVeedHttjp//vOf9WL7Kuy2asVSXHUwMDE43FY7N8Vap3tTrjaDUrP+z2o3rHf+l//dLtbD/2k16+VuO+h/yFxcWK52m+1fn1x1MDAxNdbCetjodujs/0d/f/36n96/0dXVatVWJ+y9vHegvzzrVfzZ7Wajt1RcdTAwMDXKOSVQPr+g2lmiXHUwMDBm64ZlOlqhXHUwMDA1h/0j/NS388fQtDZujyviZLlcdTAwMTGqS1Vv7lX7n1qp1mp73Ydab02ldrPTmbsodktcdTAwMTf9V3S67e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jCXlx1MDAwMtzff/z9/5TCaCMifQ== + - NodeAttributenameRepositoryAttributedescriptionAttributecommitrepo01NULL7ed3c51eab95b4ca4e9a6branch: mainfrom: time1Status: ActiveBRANCHMAINNodeDeviceNodeInterfaceNodeInterfaceRelationshipRelationshipBRANCHMAIN \ No newline at end of file + NodeAttributenameRepositoryAttributedescriptionAttributecommitrepo01NULL7ed3c51eab95b4ca4e9a6branch: mainfrom: time1Status: ActiveBRANCHMAINNodeDeviceNodeInterfaceNodeInterfaceRelationshipRelationshipBRANCHMAIN \ No newline at end of file diff --git a/docs/docs/media/topics/checks.excalidraw.svg b/docs/docs/media/topics/checks.excalidraw.svg new file mode 100644 index 0000000000..afc5bf36c6 --- /dev/null +++ b/docs/docs/media/topics/checks.excalidraw.svg @@ -0,0 +1,21 @@ + + + eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1bWVPbylx1MDAxMn7Pr3BxXu6tXG46sy95ucVcdTAwMGVhX+JcdTAwMTBunaJkWbZcdTAwMDWyZSRcdTAwMTlcdTAwMDKn8t9vj2wsWYuxiTlx6jJQXmaRemb666+7Nf77Q622XHUwMDEyP/bdlU+1XHUwMDE197tj+14ztFx1MDAxZlY+mvp7N4y8oFx1MDAwN00k+Vx1MDAxZVx1MDAwNYPQSXp24rhcdTAwMWZ9+vPPdITlXHUwMDA03eEo13e7bi+OoN9/4Xut9nfymrlP6Dqx3Wv7bjIgaUpvxVx1MDAwNcvXXHUwMDFlXHUwMDA1veS2Slx1MDAwYs64wGTcwes13e/mkjZJr+VFmyBD7DahoWX7kZu2mKqVnW94Naqrc9roXHUwMDA2x2d6XHUwMDBi3XR2v6fDW57vn8ePflwialx1MDAxNMD00rYoXHUwMDBlg1v3q9eMO9CKc/VVo8Jg0O703CiaXHUwMDE4XHUwMDEz9G3Hi1x1MDAxZk1cdTAwMWRC49rhunyqpTVmfpxji1wiLlx1MD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Kg++4KF0JJgtIy55/OB45hcdTAwMTmnK/bq8PZnzzi9QDj5sLcg+aJcdTAwMDLeXHUwMDAyo2Ws35RcdTAwMTNOUlx1MDAxYv6dSGWMtSyY3e1d65Kzvetz3lx0vJvTsL/1rc7Z6bKArMLpTdl+mKRLrU/i9HLyfGIxKdUnXHUwMDE2XUQxxfNZnYLjXHUwMDAwjlx1MDAwZTU/XHUwMDFiKFpATSyGTZpcblx1MDAxOfdcdTAwMDNngDM+tI9cdTAwMDTESlS90qzMS7hcdTAwMGJcIsGT/f14nTSutvy1J965eTo6fnikv4xcdTAwMDTLpZmJXHUwMDA0pbRcdTAwMThcdTAwMTeKYHNcdTAwMDCFqFxc4kRcdEtjxlx1MDAxOWwvYUrwglxuMFx1MDAwNsNN2CRcdTAwMDXRoFx1MDAwM9N/qPEyXHS+Rlx1MDAxZH9LXHUwMDEy7M/OgVx1MDAwNJxvhlx1MDAxOJFlXHUwMDA3XGKEzFc+W0cqXHTRKnuqaHkocFx1MDAwYlx1MDAwMrRwXHUwMDE5XGLwXHUwMDA1058nwJzcc9Pfh5FJgP3vn8ewqmOrtXLvuVx1MDAwZuul2m6KMS1cdPaNtruJsfvx4cf/XHUwMDAwI14osCJ9 + + + + + CheckGraphQL QueryCheck LogicInput dataInfrahub Graph(parameters?)SuccessError \ No newline at end of file diff --git a/docs/docs/media/transformation.excalidraw.svg b/docs/docs/media/transformation.excalidraw.svg index 5da47469c7..3d310123de 100644 --- a/docs/docs/media/transformation.excalidraw.svg +++ b/docs/docs/media/transformation.excalidraw.svg @@ -1,16 +1,21 @@ - eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1cXGtT27pcdTAwMTb93l/BcL/cO1N8tCVtPc7MnTPlVShQKO9yOdMxiSEujpPjOLzO9L/fLUNjx4khQJKmZ8pMXHUwMDFmyLYkS2uvvba05b/fzM3Np7ftYP73ufngpuZHYT3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MDE1L1x1MDAxZHVcdTAwMDH0pNFAkskyJtSEXGbQZSRZUlPD7O9Hp+lcdFx1MDAxNGKKmfZcdTAwMWb2tj9O2+7623xWit6bXHUwMDA3+Tzvt9t7KY1cXC9cdTAwMTaiOVx061x1MDAwZq+ftz5/XHUwMDE1XHUwMDA214vD4z5cdTAwMTf6vXmwYWcsQVx1MDAxNlh9e/Pt/zNcdTAwMDXqjSJ9 + + - GraphQL QueryTransformationLogicTransformationInfrahubGraph(parameters?)InputdataOutput{ "any": "data", "format": True }Plain TextJSON \ No newline at end of file + GraphQL QueryTransformationLogicTransformationInfrahubGraph(parameters?)InputdataOutput{ "any": "data", "format": True }Plain TextJSON \ No newline at end of file diff --git a/docs/docs/overview/data.mdx b/docs/docs/overview/data.mdx new file mode 100644 index 0000000000..54a1d5dd9a --- /dev/null +++ b/docs/docs/overview/data.mdx @@ -0,0 +1,18 @@ +--- +title: Data input and sync +--- + +# Data input and sync + +![Infrahub data input and sync](./../media/design-data.excalidraw.svg) + +When a schema has been loaded in to Infrahub, data can be populated or synced through multiple methods: + +- Via the WebUI: users can add, modify, and delete objects +- Via [infrahub-sync](../integrations/sync/) +- Via the [Infrahub SDK](../python-sdk/), which simplifies working with the GraphQL API: + - One-time imports can done similar to this [python example](https://github.com/opsmill/infrahub-demo-dc-fabric/blob/main/generators/create_basic.py) + - Integration with other systems +- Via the GraphQL or REST API directly + +Infrahub provides [data lineage and metadata](../topics/metadata.mdx) for tracking the origin and ownership of the data, and how the data changes and moves over time. When data comes from other systems and creates objects in the Infrahub database, those objects will have attributes such as it's source and if it's read-only, allowing for unidirectional sync from other sources of truth. diff --git a/docs/docs/overview/interfaces.mdx b/docs/docs/overview/interfaces.mdx new file mode 100644 index 0000000000..c5cbc3a0f2 --- /dev/null +++ b/docs/docs/overview/interfaces.mdx @@ -0,0 +1,59 @@ +--- +title: Ways to interface with Infrahub +--- + +# Ways to interface with Infrahub + +![Infrahub interfaces](./../media/design-interfaces.excalidraw.svg) + +Managing infrastructure at scale often means many people, teams, workflows and other systems must interact with the Infrahub infrastructure management platform. Infrahub provides multiple methods to interact: + +## WebUI + +- By default, exposed on TCP port `8000` +- Built-in documentation +- Global search, including searching data and documentation +- A GraphQL sandbox +- Swagger documentation for the REST API + +## GraphQL API + +GraphQL is the primary API to interact with data, and allows access to everything defined by the schema. The [Python SDK](../python-sdk/) is built on top of the GraphQL API. + +- By default, exposed on TCP port `8000` at the endpoint: `http://:8000/graphql` +- The Frontend utilizes the GraphQL API for most tasks +- More information can be found in the [GraphQL topic](../topics/graphql) + +## REST API + +GraphQL can only accept a query in string format and returns JSON, so there are certain workflows that are available via the REST API. + +- Loading the schema +- Retrieving artifacts +- Accessing the object store +- Executing a saved GraphQL query + +The REST API has the following properties: + +- By default, exposed on TCP port `8000` at the endpoint: `http://:8000/api` +- Swagger docs can be found at: `http://:8000/api/docs` + +## infrahubctl + +`infrahubctl` is a command line utility designed to help with the day to day management of an Infrahub installation. It's meant to run on any laptop or server and it communicates with a remote Infrahub server over the network. + +More information can be found in the [infrahubctl](../infrahubctl/) documentation section. + +## Python SDK + +The Infrahub Python SDK greatly simplifies how you can interact with Infrahub programmatically. + +More information can be found in the [Python SDK](../python-sdk/) documentation section. + +## Git + +One of the three pillars Infrahub is built on is the idea of having unified storage for data and files. The data is stored in the graph database and the files are stored in Git. + +When integrating a Git repository with Infrahub, the Git agent will ensure that both systems stay in sync at any time. Changes to branches or files in a Git repository will be synced to Infrahub automatically. + +More information can be found in the [external repositories guide](../guides/repository) diff --git a/docs/docs/overview/readme.mdx b/docs/docs/overview/readme.mdx new file mode 100644 index 0000000000..9487f26365 --- /dev/null +++ b/docs/docs/overview/readme.mdx @@ -0,0 +1,24 @@ +--- +title: Infrahub Overview +--- +import ReferenceLink from "../../src/components/Card"; + +# Infrahub overview + +![Infrahub architecture](../media/design.excalidraw.svg) + +Infrahub acts as a central hub to manage all of the information and code that powers your infrastructure. At its heart, Infrahub is built on 3 fundamental pillars: + +- **A Flexible Schema**: A model of the infrastructure and the relation between the objects in the model, that's easily extensible. +- **Version Control**: Natively integrated into the graph database which opens up some new capabilities like branching, diffing, and merging data directly in the database. +- **Unified Storage**: By combining a graph database and git, Infrahub stores data and code needed to manage the infrastructure. + +This overview will explore the design and components of Infrahub and how the platform interacts with other systems to manage the infrastructure. To do this we'll walk through workflows and explain key concepts. This overview will cover: + +- [Ways to interface with Infrahub](./interfaces) +- [Schema purpose and concepts](./schema) +- [Data input and sync](./data) +- Data Transformation +- Version Control, CI and Checks +- generators & Design-Driven automation +- External integrations with automation frameworks (Ansible, Nornir) diff --git a/docs/docs/overview/schema.mdx b/docs/docs/overview/schema.mdx new file mode 100644 index 0000000000..6682e2df9e --- /dev/null +++ b/docs/docs/overview/schema.mdx @@ -0,0 +1,27 @@ +--- +title: Schema design +--- + +# Schema design + +![Infrahub schema](./../media/design-schema.excalidraw.svg) + +A core feature of Infrahub is the ability to define a relational model to describe the infrastructure, design and business logic in a way that's specific to each organization's needs, while allowing for the model to be changed via version control over time. + +The schema provides an abstraction layer to the graph database, and as such no knowledge of database administration is needed for daily Infrahub usage. + +The schema is described in YAML format, and consists of nodes, attributes, relationships, and other descriptors. For more detail, see the [guide to creating a schema](../guides/create-schema) + +A new deployment of Infrahub will have no schema by default. It is up to the administrator of the system to define and load the initial schema. See the [commands to load a schema](../topics/schema#load-a-schema-into-infrahub) for more information. + +Example schemas can be found: + +- In the `models` directory of the [Infrahub repository](https://github.com/opsmill/infrahub/tree/develop/models) +- In other OpsMill-provided [demo repositories](https://github.com/opsmill?q=demo&type=all&language=&sort=) +- Via the Infrahub community + +The schema definitional YAML file can be stored in any file storage, however storage in a Git repository would be best practice. The schema can be loaded in to Infrahub via [`infrahubctl load`](../infrahubctl/infrahubctl-load) command or via REST API. Swagger documentation for the REST API can be viewed by clicking the `{...}` Swagger Documentation icon in the bottom-left of the Frontend UI of Infrahub. + +Once the schema is loaded, it's stored and version controlled in the graph database, and distributed to all containers acting as Infrahub API Servers. + +Changes to the schema can be done at any time, and it's best practice to make schema changes in a branch to allow for testing before implementation. diff --git a/docs/docs/python-sdk/guides/batch.mdx b/docs/docs/python-sdk/guides/batch.mdx new file mode 100644 index 0000000000..2177cdf04f --- /dev/null +++ b/docs/docs/python-sdk/guides/batch.mdx @@ -0,0 +1,145 @@ +--- +title: Executing queries in a batch +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The Python SDK client allows you to group the execution of multiple queries in a batch. +Using a batch to execute code concurrently helps reducing the amount of boilerplate code you would have to write. + +Additionally a batch allows you to control how many queries can be executed concurrently, preventing you from overwhelming the Infrahub API server. + +A batch is only available with the async version of the SDK client. + +## Using batches + +Using a batch is a 3 step process: + +1. first, we instantiate a batch object +2. we can then add a tasks to the batch, a task can be any Python `Callable` that returns an `Awaitable`, like a coroutine +3. finally we execute the batch and process the results + +```python +import asyncio +from infrahub_sdk import InfrahubClient + + +async def main(): + client = await InfrahubClient.init() + batch = await client.create_batch() + + for tag in ["red", "green", "blue", "yellow", "orange"]: + batch.add(task=client.get, kind="BuiltinTag", name__value=tag) + + async for _, result in batch.execute(): + print(result.name.value) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +Additional arguments passed in the `batch.add` method call, are being passed as arguments to the task when it gets executed. + +## Controlling the amount of concurrent queries + +By default a batch will execute 5 tasks concurrently, but this can be controlled with the `max_concurrent_execution` configuration variable for the SDK client. + +```python +import asyncio +from infrahub_sdk import Config, InfrahubClient + + +async def main(): + client = await InfrahubClient.init(Config(max_concurrent_execution=10)) + batch = await client.create_batch() + + for tag in ["red", "green", "blue", "yellow", "orange"]: + batch.add(task=client.get, kind="BuiltinTag", name__value=tag) + + async for _, result in batch.execute(): + print(result.name.value) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +## Handling exceptions in tasks + +When a batch executes a task that raises an exception, it will re-raise the exception and this will need to be handled in the calling function. Other tasks that were executing or tasks that have not started yet will not be executed or complete. + +```python +import asyncio +from infrahub_sdk import InfrahubClient + + +async def will_raise(swallowed: bool): + raise Exception() + +async def main(): + client = await InfrahubClient.init() + batch = await client.create_batch() + + batch.add(task=client.get, kind="BuiltinTag", name__value="red") + batch.add(task=will_raise, swallowed=True) + batch.add(task=client.get, kind="BuiltinTag", name__value="green") + + async for _, result in batch.execute(): + print(result.name.value) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +Alternatively we can choose to return the exception raised in a task. This has the advantage that we can still handle the exception in the calling function and that the other batch tasks will be executed. + +```python +import asyncio +from infrahub_sdk import InfrahubClient + + +async def will_raise(swallowed: bool): + raise Exception() + +async def main(): + client = await InfrahubClient.init() + batch = await client.create_batch() + + batch.add(task=client.get, kind="BuiltinTag", name__value="red") + batch.add(task=will_raise, swallowed=True) + batch.add(task=client.get, kind="BuiltinTag", name__value="green" +) + + async for _, result in batch.execute(return_exception=True): + if isinstance(result, Exception): + print("this task has failed") + print(result.name.value) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +## Adding extra contexts for tasks + +A task can be provided with extra context, through the `node` argument. The goal is to be able to provide more context when a task has completed. This can be especially useful when a task does not return a useful value. + +Imagine a scenario where we want to create 100 tag objects. The `save` method that we have to call to save the object in the database does not return a useful result. Therefor we will pass the tag object as the node argument to the task, so we can inform the user when the task completes. + +```python +import asyncio +from infrahub_sdk import InfrahubClient + + +async def main(): + client = await InfrahubClient.init() + batch = await client.create_batch() + + for idx in range(100): + tag = await client.create(kind="BuiltinTag", name=f"tag-{idx}") + batch.add(task=tag.save, node=tag, allow_upsert=True) + + async for node, result in batch.execute(): + print(f"{node.name.value} was created in Infrahub succesfully") + +if __name__ == "__main__": + asyncio.run(main()) +``` diff --git a/docs/docs/python-sdk/guides/client.mdx b/docs/docs/python-sdk/guides/client.mdx index f563f4974e..7338f79c87 100644 --- a/docs/docs/python-sdk/guides/client.mdx +++ b/docs/docs/python-sdk/guides/client.mdx @@ -30,7 +30,7 @@ client = InfrahubClientSync.init(address="http://localhost:8000") ## Authentication -The SDK is using a token-based authentication method to authenticate with the API and GraphQL. The token can be provided using a Config object or you can define it as the `INFRAHUB_SDK_API_TOKEN` environment variable. +The SDK is using a token-based authentication method to authenticate with the API and GraphQL. The token can be provided using a Config object or you can define it as the `INFRAHUB_API_TOKEN` environment variable. @@ -38,7 +38,7 @@ The SDK is using a token-based authentication method to authenticate with the AP ```python from infrahub_sdk import InfrahubClient client = await InfrahubClient.init(config=Config(api_token="token")) - client = await InfrahubClient.init() # token is read from the INFRAHUB_SDK_API_TOKEN environment variable + client = await InfrahubClient.init() # token is read from the INFRAHUB_API_TOKEN environment variable ``` @@ -47,7 +47,7 @@ The SDK is using a token-based authentication method to authenticate with the AP ```python from infrahub_sdk import InfrahubClientSync client = InfrahubClientSync.init(config=Config(api_token="token")) - client = InfrahubClientSync.init() # token is read from the INFRAHUB_SDK_API_TOKEN environment variable + client = InfrahubClientSync.init() # token is read from the INFRAHUB_API_TOKEN environment variable ``` diff --git a/docs/docs/python-sdk/guides/create_update_delete.mdx b/docs/docs/python-sdk/guides/create_update_delete.mdx index 45dac52661..8d90edf6a4 100644 --- a/docs/docs/python-sdk/guides/create_update_delete.mdx +++ b/docs/docs/python-sdk/guides/create_update_delete.mdx @@ -6,7 +6,7 @@ import TabItem from '@theme/TabItem'; # Create, update and deleting nodes -We will be using the following simple schema in this guide: +We will be using the following schema in this guide: ```yaml --- diff --git a/docs/docs/python-sdk/guides/installation.mdx b/docs/docs/python-sdk/guides/installation.mdx index 4b87eec237..fd415da932 100644 --- a/docs/docs/python-sdk/guides/installation.mdx +++ b/docs/docs/python-sdk/guides/installation.mdx @@ -13,7 +13,7 @@ pip install infrahub-sdk ## Installing optional extras -Extra's can be installed as part of the Python SDK and are not installed by default. +Extras can be installed as part of the Python SDK and are not installed by default. ### ctl diff --git a/docs/docs/python-sdk/guides/object-storage.mdx b/docs/docs/python-sdk/guides/object-storage.mdx new file mode 100644 index 0000000000..e6fe993b5d --- /dev/null +++ b/docs/docs/python-sdk/guides/object-storage.mdx @@ -0,0 +1,76 @@ +--- +title: Using the object-storage +--- + +The Python SDK can be used to interface with Infrahub's [object-storage](/topics/object-storage). + +## Storing string objects to the object-storage + +We can use the SDK to store string objects into the object-storage. + +```python +import json + +from infrahub_sdk import InfrahubClientSync + + +client = InfrahubClientSync.init() + +data = { + "key": "value", + "list": [ + "item1", + "item2", + "item3", + ] +} + +response = client.object_store.upload(content=json.dumps(data)) +print(response) +``` + +## Retrieving objects from the object-storage + +Retrieving objects from the object-storage can be done using the object's identifier. In this step we will be using the identifier that we got as a response to the previous step. + +```python +import json + +from infrahub_sdk import InfrahubClientSync + + +client = InfrahubClientSync.init() +identifier = "17d19a20-70f6-3e44-3341-c5124065cda9" + +response = client.object_store.get(identifier="17d19a20-70f6-3e44-3341-c5124065cda9") +print(json.loads(response)) +``` + +## Storing a file to the object-storage + +You can store text files in the object-storage. We have to read the contents of the file into a string object, which we can then store in the object-storage. + +```python +import json +from pathlib import Path + +from infrahub_sdk import InfrahubClientSync + +data = { + "key": "value", + "list": [ + "item1", + "item2", + "item3", + ] +} + +json_file = Path("/tmp/file.json") +json_file.write_text(json.dumps(data)) + +client = InfrahubClientSync.init() +identifier = "17d19a20-70f6-3e44-3341-c5124065cda9" + +response = client.object_store.upload(content=json_file.read_text()) +print(response) +``` diff --git a/docs/docs/python-sdk/guides/query_data.mdx b/docs/docs/python-sdk/guides/query_data.mdx index 271ceb3460..d840beaa73 100644 --- a/docs/docs/python-sdk/guides/query_data.mdx +++ b/docs/docs/python-sdk/guides/query_data.mdx @@ -11,6 +11,7 @@ We can query data in 3 ways using the SDK: - querying a single node of a given kind, based on some filters, using the `get` method - querying multiple nodes of a given kind, based on some filters, using the `filters` method - querying all the nodes of a given kind, using the `all` method +- querying with a GraphQL query, using the `execute_graphql` method ## Query filters @@ -159,6 +160,57 @@ You can query Infrahub for all nodes of a particular kind, by using the `all` me +## Querying with a GraphQL query + +In some scenarios it might be more convenient to query Infrahub using a GraphQL query, rather than using the builtin mechanisms in the SDK. + +An example might be finding all the devices connected to a given circuit. This would require us to execute multiple queries using the nodes provided by the SDK. However with a GraphQL query this can be achieved using only a single query. + +The downside of using this method, is that it will not construct Python objects for the resulting data. Instead the SDK will return a Python dictionary containing the deserialized JSON data returned by the GraphQL API. + + + + + ```python + query = """query { + BuiltinTag(name__values: ["RED", "BLUE"]) { + edges { + node { + name { + value + } + } + } + } + }""" + data = await client.execute_graphql(query=query) + for tag in data["BuiltinTag"]["edges"]: + print(tag["node"]["name"]["value"]) + ``` + + + + + ```python + query = """query { + BuiltinTag(name__values: ["RED", "BLUE"]) { + edges { + node { + name { + value + } + } + } + } + }""" + data = client.execute_graphql(query=query) + for tag in data["BuiltinTag"]["edges"]: + print(tag["node"]["name"]["value"]) + ``` + + + + ## Attributes and relationships By default, the result of a query will include attributes, relationships of cardinality one and relationships of kind Attribute or Parent. Relationships that are included in a query will be automatically initialized which means the ID, type and display name of the peers will be included in the query. But the related node itself will not be included. diff --git a/docs/docs/python-sdk/reference/config.mdx b/docs/docs/python-sdk/reference/config.mdx index 0a5d148a60..0cd5964f85 100644 --- a/docs/docs/python-sdk/reference/config.mdx +++ b/docs/docs/python-sdk/reference/config.mdx @@ -31,14 +31,14 @@ The following settings can be defined in the Config class **Description**: The URL to use when connecting to Infrahub.
**Type**: `string`
**Default value**: http://localhost:8000
-**Environment variable**: `INFRAHUB_SDK_ADDRESS`
+**Environment variable**: `INFRAHUB_ADDRESS`
## api_token **Property**: api_token
**Description**: API token for authentication against Infrahub.
**Type**: `string`
-**Environment variable**: `INFRAHUB_SDK_API_TOKEN`
+**Environment variable**: `INFRAHUB_API_TOKEN`
## echo_graphql_queries @@ -46,21 +46,21 @@ The following settings can be defined in the Config class **Description**: If set the GraphQL query and variables will be echoed to the screen
**Type**: `boolean`
**Default value**: False
-**Environment variable**: `INFRAHUB_SDK_ECHO_GRAPHQL_QUERIES`
+**Environment variable**: `INFRAHUB_ECHO_GRAPHQL_QUERIES`
## username **Property**: username
**Description**: Username for accessing Infrahub
**Type**: `string`
-**Environment variable**: `INFRAHUB_SDK_USERNAME`
+**Environment variable**: `INFRAHUB_USERNAME`
## password **Property**: password
**Description**: Password for accessing Infrahub
**Type**: `string`
-**Environment variable**: `INFRAHUB_SDK_PASSWORD`
+**Environment variable**: `INFRAHUB_PASSWORD`
## default_branch @@ -68,7 +68,7 @@ The following settings can be defined in the Config class **Description**: Default branch to target if not specified for each request.
**Type**: `string`
**Default value**: main
-**Environment variable**: `INFRAHUB_SDK_DEFAULT_BRANCH`
+**Environment variable**: `INFRAHUB_DEFAULT_BRANCH`
## default_branch_from_git @@ -76,14 +76,14 @@ The following settings can be defined in the Config class **Description**: Indicates if the default Infrahub branch to target should come from the active branch in the local Git repository.
**Type**: `boolean`
**Default value**: False
-**Environment variable**: `INFRAHUB_SDK_DEFAULT_BRANCH_FROM_GIT`
+**Environment variable**: `INFRAHUB_DEFAULT_BRANCH_FROM_GIT`
## identifier **Property**: identifier
**Description**: Tracker identifier
**Type**: `string`
-**Environment variable**: `INFRAHUB_SDK_IDENTIFIER`
+**Environment variable**: `INFRAHUB_IDENTIFIER`
## insert_tracker @@ -91,7 +91,7 @@ The following settings can be defined in the Config class **Description**: Insert a tracker on queries to the server
**Type**: `boolean`
**Default value**: False
-**Environment variable**: `INFRAHUB_SDK_INSERT_TRACKER`
+**Environment variable**: `INFRAHUB_INSERT_TRACKER`
## max_concurrent_execution @@ -99,7 +99,7 @@ The following settings can be defined in the Config class **Description**: Max concurrent execution in batch mode
**Type**: `integer`
**Default value**: 5
-**Environment variable**: `INFRAHUB_SDK_MAX_CONCURRENT_EXECUTION`
+**Environment variable**: `INFRAHUB_MAX_CONCURRENT_EXECUTION`
## mode @@ -108,7 +108,7 @@ The following settings can be defined in the Config class **Type**: `string`
**Default value**: default
**Choices**: default, tracking
-**Environment variable**: `INFRAHUB_SDK_MODE`
+**Environment variable**: `INFRAHUB_MODE`
## pagination_size @@ -116,7 +116,7 @@ The following settings can be defined in the Config class **Description**: Page size for queries to the server
**Type**: `integer`
**Default value**: 50
-**Environment variable**: `INFRAHUB_SDK_PAGINATION_SIZE`
+**Environment variable**: `INFRAHUB_PAGINATION_SIZE`
## retry_delay @@ -124,7 +124,7 @@ The following settings can be defined in the Config class **Description**: Number of seconds to wait until attempting a retry.
**Type**: `integer`
**Default value**: 5
-**Environment variable**: `INFRAHUB_SDK_RETRY_DELAY`
+**Environment variable**: `INFRAHUB_RETRY_DELAY`
## retry_on_failure @@ -132,7 +132,7 @@ The following settings can be defined in the Config class **Description**: Retry operation in case of failure
**Type**: `boolean`
**Default value**: False
-**Environment variable**: `INFRAHUB_SDK_RETRY_ON_FAILURE`
+**Environment variable**: `INFRAHUB_RETRY_ON_FAILURE`
## timeout @@ -140,7 +140,7 @@ The following settings can be defined in the Config class **Description**: Default connection timeout in seconds
**Type**: `integer`
**Default value**: 10
-**Environment variable**: `INFRAHUB_SDK_TIMEOUT`
+**Environment variable**: `INFRAHUB_TIMEOUT`
## transport @@ -149,21 +149,21 @@ The following settings can be defined in the Config class **Type**: `string`
**Default value**: httpx
**Choices**: httpx, json
-**Environment variable**: `INFRAHUB_SDK_TRANSPORT`
+**Environment variable**: `INFRAHUB_TRANSPORT`
## proxy **Property**: proxy
**Description**: Proxy address
**Type**: `string`
-**Environment variable**: `INFRAHUB_SDK_PROXY`
+**Environment variable**: `INFRAHUB_PROXY`
## proxy_mounts **Property**: proxy_mounts
**Description**: Proxy mounts configuration
**Type**: `object`
-**Environment variable**: `INFRAHUB_SDK_PROXY_MOUNTS`
+**Environment variable**: `INFRAHUB_PROXY_MOUNTS`
## update_group_context @@ -171,7 +171,25 @@ The following settings can be defined in the Config class **Description**: Update GraphQL query groups
**Type**: `boolean`
**Default value**: False
-**Environment variable**: `INFRAHUB_SDK_UPDATE_GROUP_CONTEXT`
+**Environment variable**: `INFRAHUB_UPDATE_GROUP_CONTEXT`
+ +## tls_insecure + +**Property**: tls_insecure
+**Description**: + Indicates if TLS certificates are verified. + Enabling this option will disable: CA verification, expiry date verification, hostname verification). + Can be useful to test with self-signed certificates.
+**Type**: `boolean`
+**Default value**: False
+**Environment variable**: `INFRAHUB_TLS_INSECURE`
+ +## tls_ca_file + +**Property**: tls_ca_file
+**Description**: File path to CA cert or bundle in PEM format
+**Type**: `string`
+**Environment variable**: `INFRAHUB_TLS_CA_FILE`
## recorder diff --git a/docs/docs/readme.mdx b/docs/docs/readme.mdx index d303ad29ec..31c89b2b46 100644 --- a/docs/docs/readme.mdx +++ b/docs/docs/readme.mdx @@ -4,41 +4,19 @@ title: Introduction # Welcome to Infrahub -Infrahub is taking a new approach to Infrastructure Management by providing a new generation of datastore to organize and control all the data that defines how an infrastructure should run. +Infrahub from [OpsMill](https://opsmill.com) is taking a new approach to Infrastructure Management by providing a new generation of datastore to organize and control all the data that defines how an infrastructure should run. Infrahub offers a central hub to manage the data, templates and playbooks that power your infrastructure by combining the version control and branch management capabilities of Git with the flexible data model and UI of a graph database. -At its heart, Infrahub is built on 3 fundamental pillars: +## Learn about Infrahub -- **Powerful Schema**: that's easily extensible -- **Unified Version Control**: for data and files -- **Data Synchronization**: with traceability and ownership +- **[Overview](./overview/)** explains Infrahub's architecture and concepts. +- **[Tutorials](./tutorials/getting-started/)** walk you through learning Infrahub's basic features. +- **[Guides](./guides/)** comprise a comprehensive set of "how-to" topics, covering the key features of Infrahub. +- **[Topics](./topics/)** provide a more in-depth technical explanation of various features, implementation, and deployment details. +- **[Reference](./reference/)** documents technical implementation details such as available options for features and commands. +- **[FAQ](./faq)** covers project status and how to get involved. -## Getting started +## Deploy Infrahub - Choose your Infrahub deployment method: - [Deploy an instance of Infrahub in the Cloud via GitHub Codespaces](https://github.com/opsmill/infrahub?tab=readme-ov-file#quick-start) - - [Deploy the demo environment on your laptop](/tutorials/getting-started/#prepare-the-demo-environment) -- Explore the Python SDK to easily interact with Infrahub -- Explore the capabilities of the schema -- Check the architecture document to understand how the application is built - -## Project status - -The project is currently in a Tech Preview phase, which means that not all features we are targeting for the first major release have been implemented yet and the project is still evolving at a very rapid pace with the (un)stability that you would expect in an early project. - -Having said that there are several features already available and you should be able already to: - -- Manage branches and query any branches -- Integrate a Git repository within Infrahub -- Integrate and render Jinja2 templates -- Expose new data Transformation endpoints -- Validate data within the CI/CD pipeline -- Extend the current schema -- Query and modify data via the GraphQL interface -- Access the previous state of the data and the extensions -- Branch diff - -Missing features we are actively working on. - -- Object Profile and Inheritance -- Pull requests -- Branches support for the schema and schema migration + - [Deploy the demo environment on your infrastructure](./guides/installation) diff --git a/docs/docs/reference/configuration.mdx b/docs/docs/reference/configuration.mdx index 5da2c79689..32d0ceff64 100644 --- a/docs/docs/reference/configuration.mdx +++ b/docs/docs/reference/configuration.mdx @@ -3,21 +3,112 @@ title: Configuration file --- import CodeBlock from "@theme/CodeBlock"; -import infrahubConfigPy from '!!raw-loader!../../../backend/infrahub/config.py'; # Configuration file -:::warning Under Construction +The Infrahub containers have a number of environmental variables available at runtime to affect their behavior. -This page is still under construction and is not available yet.
-Please reach out in Slack if you have some questions about the **Configuration file** +## Usage + +Here are a few common methods of setting environmental variables: + +- Exporting in a shell, e.g.: `export INFRAHUB_ADDRESS="http://localhost:8000"` +- Using a [`.env` file](https://docs.docker.com/compose/environment-variables/set-environment-variables/#substitute-with-an-env-file) +- Using [direnv](https://direnv.net/) + +:::note + +`infrahubctl` has it's own environmental variables. See the [infrahubctl documentation](../infrahubctl#environment-variables) for more information. ::: -Until a better documentation is available, the best reference to understand what options are available in the configuration file is the code itself. -The configuration file format is defined in Pydantic models in `infrahub/config.py` +## Infrahub environmental variables + -
- Explore the Source Code for the configuration File - {infrahubConfigPy} -
+| Name | Description | Example | Alias | | +|---|---|---|---|---| +| AWS_ACCESS_KEY_ID | | | | | +| AWS_SECRET_ACCESS_KEY | | | | | +| DB_TYPE | | | | | +| INFRAHUB_ADDRESS | "HTTP endpoint of the API Server, used by the git agent for internal communication" | http://infrahub-server:8000 | | | +| INFRAHUB_ALLOW_ANONYMOUS_ACCESS | Indicates if the system allows anonymous read access | TRUE | | | +| INFRAHUB_ANALYTICS_ADDRESS | | | | | +| INFRAHUB_ANALYTICS_API_KEY | | | | | +| INFRAHUB_ANALYTICS_ENABLE | | | | | +| INFRAHUB_API_CORS_ALLOW_CREDENTIALS | "If True, cookies will be allowed to be included in cross-site HTTP requests" | | | | +| INFRAHUB_API_CORS_ALLOW_HEADERS | The list of non-standard HTTP headers allowed in requests from the browser | | | | +| INFRAHUB_API_CORS_ALLOW_METHODS | A list of HTTP verbs that are allowed for the actual request | | | | +| INFRAHUB_API_CORS_ALLOW_ORIGINS | A list of origins that are authorized to make cross-site HTTP requests | | | | +| INFRAHUB_BROKER_ADDRESS | | message-queue | | | +| INFRAHUB_BROKER_DRIVER | | | | | +| INFRAHUB_BROKER_ENABLE | | | | | +| INFRAHUB_BROKER_MAXIMUM_CONCURRENT_MESSAGES | The maximum number of concurrent messages fetched by each worker | | | | +| INFRAHUB_BROKER_MAXIMUM_MESSAGE_RETRIES | The maximum number of retries that are attempted for failed messages | | | | +| INFRAHUB_BROKER_NAMESPACE | | | | | +| INFRAHUB_BROKER_PASSWORD | | infrahub | | | +| INFRAHUB_BROKER_PORT | Specified if running on a non default port. | | | | +| INFRAHUB_BROKER_TLS_CA_FILE | File path to CA cert or bundle in PEM format | | | | +| INFRAHUB_BROKER_TLS_ENABLED | Indicates if TLS is enabled for the connection | | | | +| INFRAHUB_BROKER_TLS_INSECURE | Indicates if TLS certificates are verified | | | | +| INFRAHUB_BROKER_USERNAME | | | | | +| INFRAHUB_BROKER_VIRTUALHOST | The virtual host to connect to | | | | +| INFRAHUB_CACHE_ADDRESS | | cache | | | +| INFRAHUB_CACHE_DATABASE | Id of the database to use | | | | +| INFRAHUB_CACHE_DRIVER | | | | | +| INFRAHUB_CACHE_ENABLE | | | | | +| INFRAHUB_CACHE_PASSWORD | | | | | +| INFRAHUB_CACHE_PORT | Specified if running on a non default port (6379) | 6379 | | | +| INFRAHUB_CACHE_TLS_CA_FILE | File path to CA cert or bundle in PEM format | | | | +| INFRAHUB_CACHE_TLS_ENABLED | Indicates if TLS is enabled for the connection | | | | +| INFRAHUB_CACHE_TLS_INSECURE | Indicates if TLS certificates are verified | | | | +| INFRAHUB_CACHE_USERNAME | | | | | +| INFRAHUB_CONFIG | Location of the configuration file for Infrahub | infrahub.toml | | | +| INFRAHUB_DB_ADDRESS | | database | | | +| INFRAHUB_DB_DATABASE | Name of the database | | | | +| INFRAHUB_DB_MAX_DEPTH_SEARCH_HIERARCHY | Maximum number of level to search in a hierarchy. | | | | +| INFRAHUB_DB_PASSWORD | | | | | +| INFRAHUB_DB_PORT | | | | | +| INFRAHUB_DB_PROTOCOL | | | | | +| INFRAHUB_DB_QUERY_SIZE_LIMIT | The max number of records to fetch in a single query before performing internal pagination. | | | | +| INFRAHUB_DB_RETRY_LIMIT | Maximum number of times a transient issue in a transaction should be retried. | | | | +| INFRAHUB_DB_TLS_CA_FILE | File path to CA cert or bundle in PEM format | | | | +| INFRAHUB_DB_TLS_ENABLED | Indicates if TLS is enabled for the connection | | | | +| INFRAHUB_DB_TLS_INSECURE | Indicates if TLS certificates are verified | | | | +| INFRAHUB_DB_TYPE | | neo4j | | | +| INFRAHUB_DB_USERNAME | | | | | +| INFRAHUB_DOCS_INDEX_PATH | Full path of saved json containing pre-indexed documentation | | | | +| INFRAHUB_EXPERIMENTAL_GRAPHQL_ENUMS | | | | | +| INFRAHUB_EXPERIMENTAL_PULL_REQUEST | | | | | +| INFRAHUB_INITIAL_ADMIN_PASSWORD | The initial password for the admin user | | | | +| INFRAHUB_INITIAL_ADMIN_TOKEN | The initial password for the admin user | | | | +| INFRAHUB_INITIAL_AGENT_PASSWORD | The initial password for the agent user | | | | +| INFRAHUB_INITIAL_AGENT_TOKEN | The initial password for the agent user | | | | +| INFRAHUB_INITIAL_DEFAULT_BRANCH | "Defines the name of the default branch within Infrahub, can only be set once during initialization of the system." | | | | +| INFRAHUB_INTERNAL_ADDRESS | | http://infrahub-server:8000 | | | +| INFRAHUB_LOG_LEVEL | "Set the level of the log to print in the console: info, debug, warning" | INFO | | | +| INFRAHUB_LOGGING_REMOTE_API_SERVER_DSN | | | | | +| INFRAHUB_LOGGING_REMOTE_ENABLE | | | | | +| INFRAHUB_LOGGING_REMOTE_FRONTEND_DSN | | | | | +| INFRAHUB_LOGGING_REMOTE_GIT_AGENT_DSN | | | | | +| INFRAHUB_MISC_MAXIMUM_VALIDATOR_EXECUTION_TIME | The maximum allowed time (in seconds) for a validator to run. | | | | +| INFRAHUB_MISC_PRINT_QUERY_DETAILS | | | | | +| INFRAHUB_MISC_START_BACKGROUND_RUNNER | | | | | +| INFRAHUB_PRODUCTION | "Enable or disable the production mode, in production mode the logs are generated in JSON format" | FALSE | | | +| INFRAHUB_SECURITY_ACCESS_TOKEN_LIFETIME | Lifetime of access token in seconds | | | | +| INFRAHUB_SECURITY_REFRESH_TOKEN_LIFETIME | Lifetime of refresh token in seconds | | | | +| INFRAHUB_STORAGE_BUCKET_NAME | | infrahub-data | AWS_S3_BUCKET_NAME | | +| INFRAHUB_STORAGE_CUSTOM_DOMAIN | | | AWS_S3_CUSTOM_DOMAIN | | +| INFRAHUB_STORAGE_DEFAULT_ACL | | | AWS_DEFAULT_ACL | | +| INFRAHUB_STORAGE_ENDPOINT_URL | | | AWS_S3_ENDPOINT_URL | | +| INFRAHUB_STORAGE_LOCAL_PATH | | /opt/infrahub/storage | | | +| INFRAHUB_STORAGE_QUERYTSTRING_AUTH | | | AWS_QUERYSTRING_AUTH | | +| INFRAHUB_STORAGE_USE_SSL | | | AWS_S3_USE_SSL | | +| INFRAHUB_STORAGE_DRIVER | | local | | | +| INFRAHUB_TRACE_ENABLE | | FALSE | | | +| INFRAHUB_TRACE_EXPORTER_ENDPOINT | OTLP endpoint for exporting traces | | | | +| INFRAHUB_TRACE_EXPORTER_PROTOCOL | Protocol to be used for exporting traces | | | | +| INFRAHUB_TRACE_EXPORTER_TYPE | Type of exporter to be used for tracing | | | | +| INFRAHUB_TRACE_INSECURE | "Use insecure connection (HTTP) if True, otherwise use secure connection (HTTPS)" | | | | +| REPOSITORIES_DIRECTORY | | | | | +| SYNC_INTERVAL | Time (in seconds) between git repositories synchronizations | | | | + diff --git a/docs/docs/reference/dotinfrahub.mdx b/docs/docs/reference/dotinfrahub.mdx index 4e03ae3622..c3fe763276 100644 --- a/docs/docs/reference/dotinfrahub.mdx +++ b/docs/docs/reference/dotinfrahub.mdx @@ -14,6 +14,12 @@ See [this topic](/topics/infrahub-yml) for more details on the available reposit ::: +:::note + +To help with the development process of a repository configuration file, you can leverage the schemas we publish for validation within your [editor](/development/editor) + +::: + ## Check Definitions diff --git a/docs/docs/reference/message-bus-events.mdx b/docs/docs/reference/message-bus-events.mdx index 0f01aadc39..242273e4ff 100644 --- a/docs/docs/reference/message-bus-events.mdx +++ b/docs/docs/reference/message-bus-events.mdx @@ -974,6 +974,24 @@ For more detailed explanations on how to use these events within Infrahub, see t | **event_data** | The data tied to the event | object | None | + +### Send Telemetry + + + +#### Event send.telemetry.push + + +**Description**: Push usage telemetry. + +**Priority**: 3 + + +| Key | Description | Type | Default Value | +|-----|-------------|------|---------------| +| **meta** | Meta properties for the message | N/A | None | + + ### Transform Jinja @@ -2134,6 +2152,25 @@ For more detailed explanations on how to use these events within Infrahub, see t | **event_data** | The data tied to the event | object | None | + +### Send Telemetry + + + +#### Event send.telemetry.push + + +**Description**: Push usage telemetry. + +**Priority**: 3 + + + +| Key | Description | Type | Default Value | +|-----|-------------|------|---------------| +| **meta** | Meta properties for the message | N/A | None | + + ### Transform Jinja diff --git a/docs/docs/reference/schema-validation.mdx b/docs/docs/reference/schema-validation.mdx new file mode 100644 index 0000000000..5d76198acb --- /dev/null +++ b/docs/docs/reference/schema-validation.mdx @@ -0,0 +1,65 @@ +--- +title: Schema validation +--- + +Infrahub requires the user to define multiple YAML files. One or more files defining the [schema in Infrahub](/topics/schema) and the [external repository configuration file](/topics/repository). + +To help with the process of creating and maintaining these files, we publish JSON schemas that allow you to validate the schema of these files. + +## Language server + +To be able to validate a YAML against a schema, you need to install a language server. Which language server you can use is specific to your environment and the editor that you use. For Visual Studio Code we recommend that you install the +[Red Hat YAML Language server](https://marketplace.visualstudio.com/items?itemName=redhat.vscode-yaml). + +A language server is a software that helps an editor provide advanced language specific features like: code completion, refactoring, navigation, syntax highlighting, schema validation etc. + +## Schema validation for Infrahub schema files + +The schema for Infrahub schema files is published at https://schema.infrahub.app/infrahub/schema/latest.json + +To use this schema for validation, you have to add a modeline near the top, or the bottom of the schema file. + +A modeline is a file specific configuration parameter that configures the editor with a specific behavior. In our case it configures the editor's language server to use the schema at the URL for schema validation. + +This modeline can be used for Infrahub schema files. + +```yaml +# yaml-language-server: $schema=https://schema.infrahub.app/infrahub/schema/latest.json +``` + +An example in an Infrahub schema file. + +```yaml +# yaml-language-server: $schema=https://schema.infrahub.app/infrahub/schema/latest.json +nodes: + - name: Test + namespace: Infra +``` + +## Schema validation for Infrahub external repository configuration files + +The schema for an Infrahub external repository configuration file is published at https://schema.infrahub.app/python-sdk/repository-config/latest.json + +To use this schema for validation, you have to add a modeline near the top, or the bottom of the repository configuration file. + +A modeline is a file specific configuration parameter that configures the editor with a specific behavior. In our case it configures the editor's language server to use the schema at the URL for schema validation. + +This modeline can be used for an Infrahub external repository configuration file. + +```yaml +# yaml-language-server: $schema=https://schema.infrahub.app/python-sdk/repository-config/latest.json +``` + +An example in an Infrahub schema file. + +```yaml +# yaml-language-server: $schema=https://schema.infrahub.app/python-sdk/repository-config/latest.json +schemas: + - ./schemas/locations.yml +``` + +:::note + +The schema of the Infrahub external repository configuration file has been published on [JSON Schema store](https://www.schemastore.org/json/). It allows an editor, like Visual Studio Code to download the correct schema validation file. Visual Studio Code will automatically validate a file named `.infrahub.y(a)ml` with this schema, if the Red Hat YAML Language server is installed. + +::: diff --git a/docs/docs/reference/schema/generic.mdx b/docs/docs/reference/schema/generic.mdx index 44a36940b4..0cb38dbc0c 100644 --- a/docs/docs/reference/schema/generic.mdx +++ b/docs/docs/reference/schema/generic.mdx @@ -15,11 +15,12 @@ Below is the list of all available options to define a Generic in the schema | Name | Type | Description | Mandatory | | ---- | ---- | ---- | --------- | | [**branch**](#branch) | Attribute | Type of branch support for the model. | False | -| [**default_filter**](#default_filter) | Attribute | Default filter used to search for a node in addition to its ID. | False | +| [**default_filter**](#default_filter) | Attribute | Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead) | False | | [**description**](#description) | Attribute | Short description of the model, will be visible in the frontend. | False | | [**display_labels**](#display_labels) | Attribute | List of attributes to use to generate the display label | False | | [**documentation**](#documentation) | Attribute | Link to a documentation associated with this object, can be internal or external. | False | | [**hierarchical**](#hierarchical) | Attribute | Defines if the Generic support the hierarchical mode. | False | +| [**human_friendly_id**](#human_friendly_id) | Attribute | Human friendly and unique identifier for the object. | False | | [**icon**](#icon) | Attribute | Defines the icon to use in the menu. Must be a valid value from the MDI library https://icon-sets.iconify.design/mdi/ | False | | [**include_in_menu**](#include_in_menu) | Attribute | Defines if objects of this kind should be included in the menu. | False | | [**label**](#label) | Attribute | Human friendly representation of the name/kind | False | @@ -53,7 +54,7 @@ Below is the list of all available options to define a Generic in the schema | ---- | --------------- | | **Name** | default_filter | | **Kind** | `Text` | -| **Description** | Default filter used to search for a node in addition to its ID. | +| **Description** | Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead) | | **Optional** | True | | **Default Value** | | | **Constraints** | Regex: `^[a-z0-9\_]+$` | @@ -102,6 +103,17 @@ Below is the list of all available options to define a Generic in the schema | **Default Value** | False | | **Constraints** | | +### human_friendly_id + +| Key | Value | +| ---- | --------------- | +| **Name** | human_friendly_id | +| **Kind** | `List` | +| **Description** | Human friendly and unique identifier for the object. | +| **Optional** | True | +| **Default Value** | | +| **Constraints** | | + ### icon | Key | Value | diff --git a/docs/docs/reference/schema/node.mdx b/docs/docs/reference/schema/node.mdx index 619234e2c3..d8b566a249 100644 --- a/docs/docs/reference/schema/node.mdx +++ b/docs/docs/reference/schema/node.mdx @@ -16,11 +16,12 @@ Below is the list of all available options to define a Node in the schema | ---- | ---- | ----------- | --------- | | [**branch**](#branch) | Attribute | Type of branch support for the model. | False | | [**children**](#children) | Attribute | Expected Kind for the children nodes in a Hierarchy, default to the main generic defined if not defined. | False | -| [**default_filter**](#default_filter) | Attribute | Default filter used to search for a node in addition to its ID. | False | +| [**default_filter**](#default_filter) | Attribute | Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead) | False | | [**description**](#description) | Attribute | Short description of the model, will be visible in the frontend. | False | | [**display_labels**](#display_labels) | Attribute | List of attributes to use to generate the display label | False | | [**documentation**](#documentation) | Attribute | Link to a documentation associated with this object, can be internal or external. | False | | [**hierarchy**](#hierarchy) | Attribute | Internal value to track the name of the Hierarchy, must match the name of a Generic supporting hierarchical mode | False | +| [**human_friendly_id**](#human_friendly_id) | Attribute | Human friendly and unique identifier for the object. | False | | [**icon**](#icon) | Attribute | Defines the icon to use in the menu. Must be a valid value from the MDI library https://icon-sets.iconify.design/mdi/ | False | | [**include_in_menu**](#include_in_menu) | Attribute | Defines if objects of this kind should be included in the menu. | False | | [**inherit_from**](#inherit_from) | Attribute | List of Generic Kind that this node is inheriting from | False | @@ -66,7 +67,7 @@ Below is the list of all available options to define a Node in the schema | ---- | --------------- | | **Name** | default_filter | | **Kind** | `Text` | -| **Description** | Default filter used to search for a node in addition to its ID. | +| **Description** | Default filter used to search for a node in addition to its ID. (deprecated: please use human_friendly_id instead) | | **Optional** | True | | **Default Value** | | | **Constraints** | Regex: `^[a-z0-9\_]+$` | @@ -115,6 +116,17 @@ Below is the list of all available options to define a Node in the schema | **Default Value** | | | **Constraints** | | +### human_friendly_id + +| Key | Value | +| ---- | --------------- | +| **Name** | human_friendly_id | +| **Kind** | `List` | +| **Description** | Human friendly and unique identifier for the object. | +| **Optional** | True | +| **Default Value** | | +| **Constraints** | | + ### icon | Key | Value | diff --git a/docs/docs/reference/schema/validator-migration.mdx b/docs/docs/reference/schema/validator-migration.mdx index 592b191b55..7c40ce4f41 100644 --- a/docs/docs/reference/schema/validator-migration.mdx +++ b/docs/docs/reference/schema/validator-migration.mdx @@ -32,6 +32,7 @@ In this context, an element represent either a Node, a Generic, an Attribute or | **label** | allowed | | **branch** | not_supported | | **default_filter** | allowed | +| **human_friendly_id** | allowed | | **display_labels** | allowed | | **include_in_menu** | allowed | | **menu_placement** | allowed | @@ -100,6 +101,7 @@ In this context, an element represent either a Node, a Generic, an Attribute or | **label** | allowed | | **branch** | not_supported | | **default_filter** | allowed | +| **human_friendly_id** | allowed | | **display_labels** | allowed | | **include_in_menu** | allowed | | **menu_placement** | allowed | diff --git a/docs/docs/release-notes/release-0_10.mdx b/docs/docs/release-notes/release-0_10.mdx index c5ef640e9d..f334b6aa49 100644 --- a/docs/docs/release-notes/release-0_10.mdx +++ b/docs/docs/release-notes/release-0_10.mdx @@ -10,7 +10,7 @@ title: Release 0.10 Release Date - Jan 16, 2024 + January 16, 2024 Release Codename diff --git a/docs/docs/release-notes/release-0_11.mdx b/docs/docs/release-notes/release-0_11.mdx index dfeafae897..0d459d56fb 100644 --- a/docs/docs/release-notes/release-0_11.mdx +++ b/docs/docs/release-notes/release-0_11.mdx @@ -10,7 +10,7 @@ title: Release 0.11 Release Date - XX, 2024 + February 13, 2024 Release Codename diff --git a/docs/docs/release-notes/release-0_12.mdx b/docs/docs/release-notes/release-0_12.mdx index fee6937dbd..ea0b463ee6 100644 --- a/docs/docs/release-notes/release-0_12.mdx +++ b/docs/docs/release-notes/release-0_12.mdx @@ -9,7 +9,7 @@ title: Release 0.12 Release Date - March XX, 2024 + March 16, 2024 Release Codename @@ -24,11 +24,11 @@ title: Release 0.12 # Release 0.12.0 - Beta #1 -## Main Changes +## Main changes -### Unified Storage +### Unified storage -#### Schema Update & Migrations +#### Schema update & migrations It's now possible to update the schema without losing data. Infrahub will automatically apply the validations and the migrations to ensure the data currently in the database is compliant with the new schema. @@ -38,7 +38,7 @@ The validations and the migrations will also be applied : - During a branch rebase - During a branch merge -#### Non Isolated Branches +#### Non isolated branches The default behavior for a branch has been updated to keep in sync with the main branch by default. With this new behavior, all changes applied to the main branch will automatically be visible in the branches without the need for rebase. @@ -46,14 +46,14 @@ With this new behavior, all changes applied to the main branch will automaticall A new isolated branch mode has been introduced. It allows a branch to be isolated from the main branch. Isolated branches are not kept in sync with the changes in the main branch. With these changes, the `rebase` flag in the API and in the transformations has been deprecated. -The flag `data_only` on a branch has been renamed to `sync_with_git` to provide a better description of its intent. +The flag `data_only` on a branch has been renamed to `sync_with_git` to provide a better description of its intent. The meaning of this flag has been switched so `is_data_only=true` is the same as `sync_with_git=false`. -#### Additional Constraints for the Schema +#### Additional constraints for the schema A few additional constraints have been added to the schema to enforce your business logic. -##### multiple uniqueness constraints +##### Multiple uniqueness constraints On a Node or a Generic, it's now possible to define one or multiple uniqueness constraints composed of multiple attributes or relationships of cardinality one. @@ -87,23 +87,23 @@ On a relationship of cardinality many, it's now possible to define a minimum or min_count: 2 ``` -#### New Version of the Data & Time Picker +#### New Version of the data & time picker The widget to select the active date and time has been updated to improve its usability. In addition to this change, all edits have been disabled while viewing past data to avoid any confusions and guarantee the immutability of the database. -### CI Pipeline +### CI pipeline The CI Pipeline as part of a Proposed Change has been significantly improved to provide more visibility to the user. -#### New version of the Check View +#### New version of the check view The page to display the progression and the results of the checks has been redesigned to provide more visibility. ![Proposed Change ](../media/release_notes/infrahub_0_12_0/proposed_change_checks.png) ![Proposed Change ](../media/release_notes/infrahub_0_12_0/proposed_change_failed_checks.png) -#### Background Tasks +#### Background tasks Information about background pipeline tasks are now available in the Tasks tab of the proposed change view. @@ -111,14 +111,14 @@ Information about background pipeline tasks are now available in the Tasks tab o ### Schema -#### Schema Visualizer +#### Schema visualizer The Schema page in the frontend has been redesigned to make it easier to navigate the current schema. All information are now accessible, in the future the page will be updated to modify the schema directly from the frontend as well. ![schema visualizer](../media/release_notes/infrahub_0_12_0/schema_visualizer.png) -#### Schema Documentation +#### Schema documentation The internal schema has been refactored in order to generate better documentation and to be able to provide better validation of new schema. A new definition of the internal schema has been published in JSONSchema format and it's accessible at `https://schema.infrahub.app/infrahub/schema/latest.json` @@ -145,14 +145,14 @@ The previous version of the Query has been migrated to `DiffSummaryOld` and it w ### Other -#### Enhanced Search Bar +#### Enhanced search bar The search bar has been enhanced to return more information. In addition to the objects, it's now possible to search the documentation and to navigate directly to other pages in the frontend. The search results view has also been redesigned to make it faster and more accessible. ![search bar](../media/release_notes/infrahub_0_12_0/search_bar_02.png) -#### Performance Improvement +#### Performance improvement The processing of the schema internally has been significantly improved and as a result: @@ -160,12 +160,12 @@ The processing of the schema internally has been significantly improved and as a - Loading a new schema is 3x faster - Loading the frontend for the first time is significantly faster too -#### Sync Engine +#### Sync engine The Synchronization Engine has been improved to be able to run in standalone mode and it has been integrated with Dagster, to provide more visibility into the process and leverage its orchestration capabilities. The project has been packaged as a dedicated Python package and it's now available on PyPI `infrahub-sync`. -#### Documentation Update +#### Documentation update There have been multiple improvements to the documentation, including: diff --git a/docs/docs/release-notes/release-0_13.mdx b/docs/docs/release-notes/release-0_13.mdx index f29de2895d..09559e2c7f 100644 --- a/docs/docs/release-notes/release-0_13.mdx +++ b/docs/docs/release-notes/release-0_13.mdx @@ -9,26 +9,26 @@ title: Release 0.13 Release Date - May XX, 2024 + May 7, 2024 Release Codename - - + Beta #2 Tag - - + [infrahub-v0.13.0](https://github.com/opsmill/infrahub/releases/tag/infrahub-v0.13.0) # Release 0.13.0 -## Main Changes +## Main changes -### Unified Storage +### Unified storage -#### IP Address Management +#### IP address management Infrahub now includes builtin support for IP Prefixes and IP Addresses, both for IPv4 and IPv6. @@ -57,7 +57,7 @@ The attribute values of a node that were inherited from a profile can be overrid More information about Profiles is available in the [Documentation](/topics/profiles). -#### Leverage Database Indexes to improve performance +#### Leverage database indexes to improve performance Infrahub is now leveraging database indexes to improve the overall performance of the database. Indexes will be automatically applied during startup. @@ -81,7 +81,7 @@ infrahub db index --help ``` -### CI Pipeline +### CI pipeline #### Generators @@ -105,7 +105,7 @@ The form to create a proposed change has been redesigned to expand the descripti ### Schema -#### Relationship of type Parent can't be optional +#### Relationship of type parent can't be optional The constraints around the relationships of kind `Parent` have been tightened and these relationships can't be optional anymore. All existing relationships will be automatically migrated when upgrading to this release and your schema will need to be updated. @@ -171,7 +171,7 @@ A new namespace `dev` has been introduced and some commands have been renamed in A new `demo.migrate` command has been introduced to apply the database & schema migrations. -#### Update GraphiQL Application +#### Update GraphiQL application The Graph sandbox (GraphiQL) has been integrated into Infrahub directly to provide a better experience and remove the dependencies to an external CDN. @@ -181,7 +181,7 @@ and its possible to directly select the active branch with the standard dropdown ![Search in Schema](../media/release_notes/infrahub_0_13_0/graphiql.png) -#### Help Panel in the list view +#### Help panel in the list view A new help popup is now available in the top right corner of a list view for all objects. The help popup will include a link to the schema for this object and if defined in the schema, a link to the external documentation. diff --git a/docs/docs/release-notes/release-0_14.mdx b/docs/docs/release-notes/release-0_14.mdx new file mode 100644 index 0000000000..f40b6f4523 --- /dev/null +++ b/docs/docs/release-notes/release-0_14.mdx @@ -0,0 +1,121 @@ +--- +title: Release 0.14 +--- + + + + + + + + + + + + + + + + + + + +
Release Number0.14.0
Release DateMay 27, 2024
Release CodenameBeta #3
Tag[infrahub-v0.14.0](https://github.com/opsmill/infrahub/releases/tag/infrahub-v0.14.0)
+ +# Release 0.14.0 + +We are thrilled to announce the latest release of Infrahub (0.14), marking the start of our open beta. +This release focuses on preparing for the open beta by cleaning up and improving documentation and introducing key features like the Resource Manager. + +## Main changes + +### Unified storage + +#### Resource Manager + +The resource manager simplifies resource management and allocation. +This initial implementation supports IP Prefixes and IP Addresses, with future support for additional resources like VLAN, IDs, and interfaces. + +Key features of the Resource Manager include: + +- **Inline Allocation**: Allocate resources from a pool directly when creating an object. +- **Branch Agnostic**: Resource allocation works across branches. A resource allocated in one branch won’t be allocated in another. +- **Idempotent**: If the same consumer requests a resource multiple times, the Resource Manager will always return the same value. This reduces the complexity of managing resource allocation on the client side in an idempotent way. + +![Resource Pool](../media/release_notes/infrahub_0_14_0/resource_manager_overview.png) +![Resource Pool](../media/release_notes/infrahub_0_14_0/resource_manager_form.png) + +### Schema + +#### Human Friendly Identifier (hfid) + +In addition to the automatically generated internal ID (UUID) for each object, Infrahub now allows defining fields that form a human-friendly identifier (`hfid`). + +The hfid can uniquely reference objects across systems, even before an object is created in Infrahub. + +While mostly invisible in the frontend, `hfid` is crucial for building robust data synchronization between systems and creating truly idempotent scripts. + +Applied to the network industry: + +- the `hfid` of a device could be its name: `atl1-edge01` +- the `hfid` of an interface will be the combination of the name of the device and the name of the interface: `["atl1-edge01", "Ethernet1"] + +The fields that will compose the `human_friendly_id` must be defined in the schema + +##### hfid support in GraphQL + +`hfid` can be used as an alternative to the ID in most GraphQL operations, including: + +- Update Mutation +- Upsert Mutation +- Delete Mutation +- Related Node in all Mutations + +### Other + +#### Documentation update + +We have significantly improved and added new content to the documentation, including a new FAQ section. + +## Breaking Changes + +### Remove support for non-isolated branch + +Support for branches in non-isolated mode has been removed. +Although useful, it posed challenges for operations dependent on other nodes in the graph, such as schema management, constraints validation, and IPAM. + +All branches now operate in isolated mode by default, similar to branches in Git. A branch need to be rebased to stay in sync with main. + +## Migration Guide + +To migrate your instance of Infrahub to the latest version, please run the following commands and restart all instances of Infrahub. + + +```shell +infrahub db migrate +infrahub db update-core-schema +``` + + +> if you are running in docker these commands need to run from the container where Infrahub is installed + +### Migration of the demo instance + +If you are using the demo environment, you can migrate to the latest version with the following commands + +```shell +invoke demo.stop +invoke demo.build +invoke demo.migrate +invoke demo.start +``` + +If you don't want to keep your data, you can start a clean instance with the following command + +```shell +invoke demo.destroy demo.build demo.start demo.load-infra-schema demo.load-infra-data +``` + +> All data will be lost, please make sure to backup everything you need before running this command. + +The repository https://github.com/opsmill/infrahub-demo-edge has also been updated, it's recommended to pull the latest changes into your fork. diff --git a/docs/docs/sync/guides/installation.mdx b/docs/docs/sync/guides/installation.mdx deleted file mode 100644 index 2221fe70ed..0000000000 --- a/docs/docs/sync/guides/installation.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Installing infrahub-sync ---- -# Installing infrahub-sync - -The Infrahub Sync is available on [PyPI](https://pypi.org/project/infrahub-sync/) and can be installed using the pip package installer. It is recommended to install the Sync into a virtual environment. - -```bash -python3 -m venv .venv -source .venv/bin/activate -pip install infrahub-sync -``` diff --git a/docs/docs/sync/readme.mdx b/docs/docs/sync/readme.mdx deleted file mode 100644 index d396ecd18d..0000000000 --- a/docs/docs/sync/readme.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Sync Engine ---- -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - - -# Infrahub Sync - -Infrahub-Sync is a versatile Python package that synchronizes data between a source and a destination system.It builds on the robust capabilities of `diffsync` to offer flexible and efficient data synchronization across different platforms, including Netbox, Nautobot, and Infrahub. This package features a Typer-based CLI for ease of use, supporting operations such as listing available sync projects, generating diffs, and executing sync processes. - -## Guides - -- [Installing infrahub-sync](/sync/guides/installation) -- [Creating a new Sync Instance](/sync/guides/creation) -- [Run a Sync Instance](/sync/guides/run) - -## Reference - -- [Sync Instance configuration](/sync/reference/config) diff --git a/docs/docs/topics/architecture.mdx b/docs/docs/topics/architecture.mdx index a81351ae70..0a160b299c 100644 --- a/docs/docs/topics/architecture.mdx +++ b/docs/docs/topics/architecture.mdx @@ -2,12 +2,24 @@ title: Architecture --- -# Architecture diagram +# Infrahub architecture -![](../media/high_level_architecture.excalidraw.svg) +Infrahub is deployed as a container-based architecture, composed of multiple components. A minimum deployment consists of the following architecture: + +![Infrahub Architecture](../media/high_level_architecture.excalidraw.svg) ## Infrahub components +The main components are: + +- A **Frontend** written in React and rendered in the user's browser. +- An **API server** written in Python with FastAPI. +- A **Git agent** written in Python to manage the interaction with external Git repositories. +- A **Graph database** based on `neo4j`. +- A **Message bus** based on `RabbitMQ`. +- A **Cache** based on `redis`. +- An **Object Store** based on local storage or `Amazon S3`. + ### API server Language: Python @@ -55,11 +67,51 @@ Memgraph is a lightweight, very fast, in-memory database that works great for te ### Message bus The message bus is based on RabbitMQ. It supports both a fanout channel to distribute messages to all members at the same time and a RPC framework to distribute work synchronously. +Infrahub also supports NATS JetStream for the message bus. ### Cache The cache is based on Redis. It's mainly used as a central point to support the distributed lock systems between all the different component of the system. +Infrahub also supports NATS JetStream for the cache. ### Git server (GitHub/GitLab) Any Git server. The most popular being: GitHub, GitLab, or Bitbucket. + + +## TLS-secured connections + + +Infrahub supports TLS connections toward the dependencies above. +The following configuration variables are available to configure TLS: + +```bash +INFRAHUB_BROKER_TLS_CA_FILE=/opt/ssl/ca.pem # File path to a CA certificate or bundle in PEM format +INFRAHUB_BROKER_TLS_ENABLED=true # Boolean to enable TLS connections (allowed values: 1, True, true, 0, False, false) +INFRAHUB_BROKER_TLS_INSECURE=true # Boolean to ignore certificate verification, useful for self-signed certificates (CA is not verified, expiry is not verified, hostname is not verified) + +INFRAHUB_CACHE_TLS_CA_FILE +INFRAHUB_CACHE_TLS_ENABLED +INFRAHUB_CACHE_TLS_INSECURE +INFRAHUB_DB_TLS_CA_FILE +INFRAHUB_DB_TLS_ENABLED +INFRAHUB_DB_TLS_INSECURE +``` + +### Graph database + +You can configure TLS for Neo4j using the following Docker environment variables: + +```bash +NEO4J_dbms_ssl_policy_bolt_enabled=true +NEO4J_dbms_ssl_policy_bolt_base__directory=/opt/ssl +NEO4J_dbms_ssl_policy_bolt_private__key=cert.key +NEO4J_dbms_ssl_policy_bolt_public__certificate=cert.pem +NEO4J_dbms_connector_bolt_tls__level=REQUIRED +``` + +## Infrahub High Availability Deployment + +Infrahub may be deployed with no single-point of failure, and horizontally scaled architectures can be deployed. An example of a HA deployment is below: + +![Infrahub Architecture](../media/high_level_architecture_ha.excalidraw.svg) diff --git a/docs/docs/topics/artifact.mdx b/docs/docs/topics/artifact.mdx index 0676a6f7d8..08afd41a3e 100644 --- a/docs/docs/topics/artifact.mdx +++ b/docs/docs/topics/artifact.mdx @@ -34,7 +34,7 @@ An **artifact definition** centralizes all the information required to generate - Format of the output - Information to extract from each target that must be passed to the transformation. -From an **artifact definition** artifact nodes are created, for each target which is part of the group. The result of the transformation is stored in the [object storage](./object-storage.mdx). The generation of the artifacts is performed by the git agent(s). +From an **artifact definition** artifact nodes are created, for each target which is part of the group. The result of the transformation is stored in the [object storage](./object-storage.mdx). The generation of the artifacts is performed by the Git agent(s). ![](../media/topics/artifact/architecture.excalidraw.svg) diff --git a/docs/docs/topics/check.mdx b/docs/docs/topics/check.mdx index 10217a140b..2394ed9296 100644 --- a/docs/docs/topics/check.mdx +++ b/docs/docs/topics/check.mdx @@ -2,10 +2,27 @@ title: Check --- -# Checks +Checks are user defined logic, stored in an [external repository linked to Infrahub](/topics/repository), that are run as part of a [proposed change](/topics/proposed-change). It allows a user to perform any kind of data validation logic during a proposed change. If a check does not complete successfully, then the proposed change cannot be merged. -:::warning WIP +Some examples: -Coming Soon +- name validation against a naming convention for all infrastructure components in the database +- validate that we always have a redundant WAN circuit in operational state for every site +- validate that all internet facing interfaces have an inbound access-list associated -::: +## High level design + +A check is composed of 2 main components: + +- A GraphQL Query that will define the input data +- A check logic in the Python language that will validate the data + +![High level design](../media/topics/checks.excalidraw.svg) + +## Targeted checks + +Targeted checks are exactly the same as a check, the main difference is that they target a specific group of nodes in Infrahub. The check will then only be executed against the nodes in that group. + +This can be useful if a check should only be executed against a subset of a specific kind of nodes. + +An example of such scenario could be that you want to validate that all devices for which we generate an OpenConfig artifact, have the NETCONF service enabled. diff --git a/docs/docs/topics/event-handling.mdx b/docs/docs/topics/event-handling.mdx index 9a0e7eede6..4d0f35ebe6 100644 --- a/docs/docs/topics/event-handling.mdx +++ b/docs/docs/topics/event-handling.mdx @@ -9,4 +9,33 @@ title: Bus Event handling This page is still under construction and is not available yet.
Please reach out in Slack if you have some questions about the **Bus events** -::: \ No newline at end of file +::: + +## Architecture + +Infrahub requires the following features from the message bus: + +1. Retry messages with a delay +2. Broadcast messages to multiple consumers +3. Asynchronous RPC +4. Set priorities to messages + +Depending on the message bus system, we implement them using the following: + +### RabbitMQ + +1. We create a `delayed` exchange and multiple queues per TTL variation. When there is an error on message processing, the worker will publish the failed message in the delayed exchange with the delay TTL set. + Note: for non-acked (NAK, expired, dropped, or lost) messages, we make use of a dead-letter exchange (DLX). + Note bis: events and callback messages do not require acknowledgment. +2. We create one `events` queue per worker binding on the required broadcast messages using their routing keys. +3. Requests are sent to the exchange and processed by an unique queue where each worker consume messages. + We also create one `callback` queue per worker and use the `reply-to` header to send reply messages to this queue. +4. Priorities are handled using the `priority` field of message properties. + +### NATS JetStream + +1. We NAK the message with a delay. +2. We create an `events` stream with retention policy set to `INTEREST` and create an ephemeral consumer for each worker. +3. Requests are sent to the `rpcs` stream with retention policy set to `WORK_QUEUE` and create a consumer group on which each worker will subscribe. + We also create one `callback` stream per worker and publish to this stream for the replies. +4. **We do not handle priorities.** diff --git a/docs/docs/topics/generator.mdx b/docs/docs/topics/generator.mdx index 73f6768b31..2463df17a6 100644 --- a/docs/docs/topics/generator.mdx +++ b/docs/docs/topics/generator.mdx @@ -28,4 +28,8 @@ The targets point to a group that will consist of objects that are impacted by t The [GraphQL query](graphql) defines the data that will be collected when running the generator. Any object identified in this step is added as a member to a GraphQL query group. The membership in these groups are then used to determine which generators need to be executed as part of a proposed change during the pipeline run. -The Generator itself is a Python class that is based on the `InfrahubGenerator` class from the SDK. Just like [transforms](transformation) and [checks](check), the Generators are user defined. \ No newline at end of file +The Generator itself is a Python class that is based on the `InfrahubGenerator` class from the SDK. Just like [transforms](transformation) and [checks](check), the Generators are user defined. + +## Known limitations + +- [3289](https://github.com/opsmill/infrahub/issues/3289) deleting a generator target object should delete the created objects of that target diff --git a/docs/docs/topics/graphql.mdx b/docs/docs/topics/graphql.mdx index 334d584716..f09bdb8fe8 100644 --- a/docs/docs/topics/graphql.mdx +++ b/docs/docs/topics/graphql.mdx @@ -189,11 +189,11 @@ In addition to the queries and the mutations automatically generated based on th - **Mutation**: `BranchMerge`, Merge a branch into main - **Mutation**: `BranchValidate`, Validate if a branch has some conflicts -## GraphQLQuery +## Stored GraphQL queries in the database The `GraphQLQuery` model has been designed to store a GraphQL query in order to simplify its execution and to associate it with other internal objects like `Transformation`. -A `GraphQLQuery` object can be created directly from the API or it can be imported from a Git repository. +A `GraphQLQuery` object can be created via the web interface, the API or it can be imported from a Git repository. Every time a `GraphQLQuery` is created or updated, the content of the query will be analyzed to: @@ -208,6 +208,10 @@ Every time a `GraphQLQuery` is created or updated, the content of the query will - Height, total number of fields requested in the query - List of Infrahub models referenced in the query -### Import from a git repository +### Import from a Git repository -The git agent will automatically try to import all files with the extension `.gql` into a `GraphQLQuery` with the name of the file as the name of the query. +The Git agent will automatically try to import all files with the extension `.gql` into a `GraphQLQuery` with the name of the file as the name of the query. + +### Executing stored GraphQL queries + +Stored GraphQL queries can be executed by using the `/api/query/{query_id}` REST API endpoint. The `{query_id}` can be the name or the id of the `GraphQLQuery` node in the database. More information can be found in the [Swagger documentation](http://localhost:8000/api/docs). diff --git a/docs/docs/topics/hardware-requirements.mdx b/docs/docs/topics/hardware-requirements.mdx index fe7fee1684..2b3de40d9d 100644 --- a/docs/docs/topics/hardware-requirements.mdx +++ b/docs/docs/topics/hardware-requirements.mdx @@ -10,3 +10,37 @@ The system on which you want to run Infrahub, has to meet the following hardware | Recommended | 8 | 16GB | SSD and/or >= 5000 IOPS | If you only want to give Infrahub a try, or follow the [getting started tutorial](/tutorials/getting-started/), then you can use [GitHub Codespaces](/guides/installation#github-codespaces) as an alternative. + +## Performance benchmark utility + +To evaluate the performance of your system, we provide a small utility that will run some performance benchmark of your system's CPU, Memory and disk IOPS. + +:::note + +Even with the right amount of CPU core and memory, there are some other factors that could impact the performance of Infrahub like the speed of your CPU. + +::: + +The tool can run on any system using docker with the following command `docker run --pull always --rm registry.opsmill.io/opsmill/bench` + +```bash title="❯ docker run --pull always --rm registry.opsmill.io/opsmill/bench" + +latest: Pulling from opsmill/bench +09f376ebb190: Already exists +6008598ecd4d: Already exists +b70c7f4d3f19: Pull complete +84e80b988953: Pull complete +Digest: sha256:6f0031a0f61823cca7d319033087f80524eadffa87b1981b2e82d841ada12895 +Status: Downloaded newer image for registry.opsmill.io/opsmill/bench:latest +Running Disk IOPS benchmark... hold on +Running CPU/Memory benchmark... hold on + +Benchmark results: + +Memory: 15611 MB - Required: 8000 MB : OK +CPU Perf: 2337 - Required: 1500 : OK +Disk Read IOPS: 47742 - Required: 5000 : OK +Disk Write IOPS: 15885 - Required: 5000 : OK + +Benchmark completed... +``` diff --git a/docs/docs/topics/infrahub-yml.mdx b/docs/docs/topics/infrahub-yml.mdx index 7b5aeae371..26778c87b0 100644 --- a/docs/docs/topics/infrahub-yml.mdx +++ b/docs/docs/topics/infrahub-yml.mdx @@ -22,6 +22,12 @@ An external repository can be used to link the following Infrahub objects to an ::: +:::note + +To help with the development process of a repository configuration file, you can leverage [schema validation](/reference/schema-validation) within your editor. + +::: + ## GraphQL query {#graphql-query} This is the easiest type of object to link to Infrahub through an external repository because they do not need to be specified in the `.infrahub.yml` file. When Infrahub creates a Repository or pulls changes from the associated external repository, it will scan all the files in the repository and save any that have a `.gql` extension as GraphQLQuery objects in Infrahub. diff --git a/docs/docs/topics/local-demo-environment.mdx b/docs/docs/topics/local-demo-environment.mdx index 7857684fec..8b25efefdb 100644 --- a/docs/docs/topics/local-demo-environment.mdx +++ b/docs/docs/topics/local-demo-environment.mdx @@ -29,7 +29,6 @@ It's designed to be controlled by `invoke` using a list of predefined commands. | **cache** | redis:7.2 | Cache based on Redis, mainly used for distributed lock | | **infrahub-server** | Dockerfile | Instance of the API server, running GraphQL | | **infrahub-git** | Dockerfile | Instance of the Git agent, managing the Git Repository | -| **frontend** | Dockerfile | Instance of the Frontend | @@ -52,12 +51,6 @@ On a Laptop, both Docker & Docker Compose can be installed by installing [Docker ### First utilization -Before the first utilization you need to build the images for Infrahub with the command: - -```bash -invoke demo.build -``` - Initialize the database and start the application ```bash @@ -114,6 +107,6 @@ export INVOKE_PTY=0 to disable it completely It's recommended to check if all containers are still running using `invoke demo.status`. The 5 containers should be running and be present. - If one is not running, you can try to restart it with `invoke demo.start`. -- If the container is still not coming up, you can watch the logs with `docker logs ` (the container name will include the name of the project and a number, i.e., `infrahub-dev-infrahub-git-1` ). +- If the container is still not coming up, you can watch the logs with `docker logs ` (the container name will include the name of the project and a number, i.e., `infrahub-infrahub-git-1` ). If some containers are still not coming up, it's recommended to start from a fresh install with `invoke demo.destroy`. diff --git a/docs/docs/topics/object-storage.mdx b/docs/docs/topics/object-storage.mdx index 53ed5eaefa..0676f0ab43 100644 --- a/docs/docs/topics/object-storage.mdx +++ b/docs/docs/topics/object-storage.mdx @@ -1,17 +1,53 @@ --- -title: Object storage +title: Object-storage --- -# Object storage +# Object-storage -Infrahub provides an interface to store and retrieve files in an object storage. The object storage interface is independent of the branches. +Infrahub provides an interface to store and retrieve files or objects in an object-storage. The object-storage is used internally within Infrahub to store rendered artifacts, but it can be used to store any text based file or content. -Currently, Infrahub only supports a local backend. The goal over time is to support multiple backends, such as AWS S3, to allow users to select where they would like to store their files. +You can interface with the object-storage through the REST API and Python SDK. +See the [object-storage guide](/guides/object-storage) and [object-storage Python SDK](/python-sdk/guides/object-storage) guide for more information. -Currently, the main interface to interact with the object storage is the REST API. 3 methods are supported: +## Supported backends -- GET /api/storage/object/\ -- POST /api/storage/upload/content -- POST /api/storage/upload/file +At this moment Infrahub supports using local storage, or AWS S3 storage backends. Support for other storage backends will be added in the future. -Please check the API documentation for more details. +### Local storage + +Infrahub can use local storage as a storage backend. It can be any directory on a filesystem that is attached to the system on which Infrahub runs. The only requirement is that all the Infrahub API servers and Git Agents need access to the filesystem. + +To setup Infrahub to use local storage backend you can use the following configuration: + +```toml +[storage] +driver = "local" + +[storage.local] +path = "/opt/infrahub/storage/" +``` + +More details can be found in the [configuration documentation](/reference/configuration). + +### AWS S3 storage + +Infrahub can use AWS S3 or any other S3 API compatible storage as a storage system. + +To setup Infrahub to use AWS S3 as a storage backend you can use the following configuration: + +```toml +[storage] +driver = "s3" + +[storage.s3] +access_key_id = "my_access_key" +secret_access_key = "secret_access_key" +bucket_name = "my-infrahub-bucket" +endpoint_url = "https://s3.eu-central-1.amazonaws.com" +``` + +More details can be found in the [configuration documentation](/reference/configuration). + +## Object model + +Objects or files stored within the object-storage, are identified by an identifier (UUID). An identifier is assigned to the object at time of creation within the object-storage. Interactions with the object then happen leveraging that identifier. diff --git a/docs/docs/topics/profiles.mdx b/docs/docs/topics/profiles.mdx index 766ac6a70e..bd84756195 100644 --- a/docs/docs/topics/profiles.mdx +++ b/docs/docs/topics/profiles.mdx @@ -20,7 +20,7 @@ A common scenario is that you want to create multiple interface configurations t In that case we could create an interface profile with the name "user-interface" that defines the mode of the interface and the untagged VLAN to be used. This profile can then be applied to all the interfaces in Infrahub that will be used to connect users too. This assures that all these interfaces will have the same value for the mode and untagged VLAN. -### BGP Session profiles +### BGP session profiles Internal BGP sessions within a network typically contain multiple common configuration options. Profiles can be used to gather these common attributes. The profile can be applied to all the internal BGP sessions to assure they use the same configuration settings. diff --git a/docs/docs/topics/repository.mdx b/docs/docs/topics/repository.mdx index 08c6a49c5a..de8c5c7ef1 100644 --- a/docs/docs/topics/repository.mdx +++ b/docs/docs/topics/repository.mdx @@ -29,7 +29,9 @@ Infrahub stores all of the data that it needs for every remote repository in a d Please note that each Git agent must have access to the same directory on the file system so that they can share work among each other. + ## Read-only Repository vs. CoreRepository {#read-only-vs-core} + Feature | CoreRepository | Read-only Repository ------------------------|-------------------------------|--------------------- @@ -37,7 +39,9 @@ Branches | Tracks all remote branches | Data from one remote c Updates **from** remote | Automatic via background task | Manually, by updating `ref` or `commit` Updates **to** remote | When merging Proposed Change | No + ### Read-only Repository {#read-only-repository} + Read-only Repositories will only pull data from an external repository into Infrahub and will never push any data to the external repository. A Read-only Repository will pull changes from a single `ref` (branch, tag, or commit) into the Infrahub branch(es) on which it exists. Read-only repositories are not automatically updated. To update a Read-only Repository, you must manually update the `commit` and/or `ref` property to a new value, then the Git agent will pull the appropriate commit and create the appropriate objects in Infrahub. diff --git a/docs/docs/topics/schema.mdx b/docs/docs/topics/schema.mdx index 921ba159c0..43daf4baa6 100644 --- a/docs/docs/topics/schema.mdx +++ b/docs/docs/topics/schema.mdx @@ -14,7 +14,13 @@ Out of the box, Infrahub doesn't have a schema for most things and it's up to us Unlike traditional databases that can only have one schema at a time, in Infrahub it is possible to have a different schema per branch. This is possible because the schema itself is stored in the database like any other object. -There is several way to [load a new schema](/guides/schema). +There are several ways to [load a new schema](/guides/schema). + +:::note + +To help with the development process of a schema definition file, you can leverage the schemas we publish for validation within your [editor](/reference/schema-validation) + +::: ## Schema definition @@ -191,6 +197,120 @@ nodes: peer: Example1Car ``` +### Object Uniqueness + +The schema provides 2 mechanisms to enforce the uniqueness of an object, within all the objects of the same kind: + +- At the attribute level, with the property `unique` +- At the Node or Generic level with the property `uniqueness_constraints` + +Both type of uniqueness constraints will be automatically validated during the following events: + +- Branch merge +- Proposed Change +- Branch rebase +- Schema update + +#### Unique attribute + +Each attribute with the property `unique: true` will be evaluated individually and will automatically enforce a uniqueness constraint for all the nodes of the same kind. +If a unique attribute is defined on a Generic, all nodes inheriting from this Generic will respect the uniqueness constraint defined at the Generic level. + +```yaml {7} showLineNumbers +nodes: + - name: Person + namespace: Example + attributes: + - name: name + kind: Text + unique: true +``` + +#### Uniqueness Constraints + +More complex uniqueness constraints, composed of multiple attributes and/or relationships can be defined at the Node or Generic level with the property `uniqueness_constraints`. +It's possible to define multiple uniqueness constraints and each of them will be evaluated individually. + +In the example below, the node schema `ExampleCar`, `["owner", "model__value"]` guarantee that a car will unique based on the `owner` and the `model` of the car. + +`uniqueness_constraints` can be composed of N number of attribute or relationship of cardinality one: + +- For an attribute, the valid format is `__value`. *Currently only value is supported but in the future the plan is to allow additional metadata to be used as well.* +- For a relationship, only the name of the relationship should be provided ``. *Only relationship of cardinality one are supported and the relationship must be mandatory.* + +```yaml {10} showLineNumbers +nodes: + - name: Person + namespace: Example + attributes: + - name: name + kind: Text + unique: true + - name: Car + namespace: Example + uniqueness_constraints: ["owner", "model__value"] + attributes: + - name: model + kind: Text + relationships: + - name: owner + peer: ExamplePerson + optional: false + cardinality: one +``` + +### Human friendly identifier (hfid) + +In addition to the internal id automatically generated for each object (UUID), Infrahub provide a way to define a set of fields that will constitue a human friendly identifier (hfid). + +:::success Use Case + +The `hfid` is meant to be used to reference objects uniquely across systems, or even before an object has been created in Infrahub. +Having a human friendly way to identify an object is very important to build robust data synchronization between systems and to provide true idempotent script. + +In the network industry: + +- the `hfid` of a device will be could be its `name` : `atl1-edge01` +- the `hfid` of an interface will be the combination of the name of the device and the name of the interface: (`atl1-edge01`, `Ethernet1`) + +::: + +In the example below, each `ExamplePerson`, will have a `hfid` composed of his/her `lastname` and `firstname`. + +`human_friendly_id` can be composed of N number of attribute or relationship of cardinality one: + +- For an attribute, the valid format is `__value`. *Currently only value is supported but in the future the plan is to allow additional metadata to be used as well.* +- For a relationship, the name of the relationship and the name of a unique attribute must be provided `____value`. *Only relationship of cardinality one are supported and the relationship must be mandatory.* + +```yaml {4} showLineNumbers +nodes: + - name: Person + namespace: Example + human_friendly_id: ["lastname__value", "firstname__value"] + attributes: + - name: firstname + kind: Text + - name: lastname + kind: Text +``` + +:::info + +If a `human_friendly_id` is defined on a node but no `uniqueness_constraints` are present, a uniqueness constraints matching the `human_friendly_id` will be automatically created. + +If at least one attribute is marked as unique, and `human_friendly_id` hasn't been defined, `human_friendly_id` will be automatically created. + +::: + +#### `hfid` support in GraphQL + +`hfid` can be used as a alternative to `id` in most places in GraphQL, including : + +- Update Mutation +- Upsert Mutation +- Delete Mutation +- Related Node in all Mutations + ### Branch support By default, all models defined in the schema will be **branch-aware** which means that any changes to an object based on a **branch-aware** model will be local to the branch and will not affect the other branches. @@ -232,11 +352,11 @@ Attributes and relationships can be configured as **branch-aware**, **branch-agn nodes: - name: Fruit namespace: Example - branch: True # (Default) + branch: "agnostic" attributes: - kind: Text name: name - branch: "agnostic" + branch: "aware" ``` By default, if a specific value is not defined: diff --git a/docs/docs/topics/transformation.mdx b/docs/docs/topics/transformation.mdx index 7689cb2c1a..d3992f6655 100644 --- a/docs/docs/topics/transformation.mdx +++ b/docs/docs/topics/transformation.mdx @@ -85,8 +85,8 @@ A TransformPython can be rendered with 2 different methods: ## Unit testing for transformation -:::warning WIP +Infrahub provide a framework to create unit tests for your transformations with very minimal code/configuration. -Coming Soon +The tests can be executed locally for development purpose and they will also be executed as part of the CI Pipeline when the platform identify a change that could potentially impact your transformation. -::: +For more information, please check out the [Resource Testing Framework](/topics/resources-testing-framework) page. diff --git a/docs/docs/topics/version-control.mdx b/docs/docs/topics/version-control.mdx index 93de3bfcf2..0905959160 100644 --- a/docs/docs/topics/version-control.mdx +++ b/docs/docs/topics/version-control.mdx @@ -1,8 +1,8 @@ --- -title: Immutability and Version Control +title: Immutability and version control --- -# Immutability and Version Control +# Immutability and version control Infrahub integrate an immutable database with native support for version control that was designed with Infrastructure Management in mind. @@ -24,40 +24,24 @@ Infrahub guarantee the immutability of the default branch by default (`main`) It's possible to query a previous version of the database by providing a specific timestamp either via the UI, via GraphQL or via the REST API -## Version Control +## Version control -The implementation of Version Control in Infrahub is inspired by Git but also different in several ways +The implementation of version control in Infrahub is inspired by Git but also different in several ways A branch provide a safe environment to prepare and validate a change before integrating it into the default branch by opening a [Proposed Change](/topics/proposed-change). Branches are meant to be short lived, from a few seconds to a few weeks, and are hierarchical by nature which means that a branch can only be merged into the branch it was created from. > Currently only a single level of hierarchy is supported, meaning that all branches must be created from the default branch and be merged into the default branch. - -### Sync and Isolated mode - -Unlike Git, by default, a branch in Infrahub will automatically stay in sync with the default branch, unless the branch is currently in isolated mode. -A branch in isolated mode will have a similar behavior as branches in Git and a rebase will be required to integrate the latest changes from the default branch. -:::info Branch Isolation & Git Rebase - -In Git, Branches are isolated by default and a rebase is required for a branch to stay in sync with the main branch. -This behavior works well when we need to prepare a big change and we want to have full control about the changes that gets in but in most cases -it present a risk of having the working branch out-of-sync with the main branches. - -::: - -### Create a Branch +### Create a branch Branches in Infrahub are designed to be lightweight, while the recommendation is to keep the lifespan of a branch short, it's possible to have 10s of branches open at the same time. -When creating a branch it's possible to provide a description as well as these options: - -- **Data Only**: When a branch is flagged as **Data Only** it won't be extended to the Read-Write Repositories. By opposition, if a branch isn't **Data Only** it will be automatically created in all the Read-Write repositories. -- **Isolated Mode**: When operating in isolated mode, the branch won't automatically keep in sync with the main branch. +When creating a branch it's possible to provide a description and define if the branch should be **Data Only** or not. When a branch is flagged as **Data Only** it won't be extended to the Read-Write Repositories. By opposition, if a branch isn't **Data Only** it will be automatically created in all the Read-Write repositories. Branch names are fairly permissive, but must conform to git ref format. For example, slashes (/) are allowed, tildes (~) are not. -A branch can be created via the UI, via GraphQL, via `infrahubctl` or simply by pushing a new branch to a managed Git repository. +A branch can be created via the UI, via GraphQL, via `infrahubctl` or by pushing a new branch to a managed Git repository. :::info @@ -104,7 +88,7 @@ Creating a branch won't create a copy of the database, only the changes applied -### Changes between Branches +### Changes between branches To view all the changes in a branch @@ -124,7 +108,7 @@ Check the [Branch Support section in the Schema documentation](/topics/schema#br ::: -### Merge a Branch +### Merge a branch During a merge operation, only the latest modified values in the branch will be applied to the destination branch and the history of the branch won't be carried over to the main branch. This behavior is required to guarantee the immutability of the default branch. @@ -140,17 +124,17 @@ Using a Proposed Change to merge a branch is recommended to guarantee that all c ::: -### Rebase a Branch +### Rebase a branch -If a branch operates in isolated mode or if it has some conflicts with the default branch, it's possible to rebase it with the latest version of the default branch. -Similar to the merge operation, during a rebase only the latest modified values in the branch will be conversed and the history of the branch won't be carried over. +If a branch is out of sync with the default branch or if it has some conflicts, it's possible to rebase it with the latest version of the default branch. +Similar to the merge operation, during a rebase only the latest modified values in the branch will be conserved and the history of the branch won't be carried over. The diagram below present how various changes to 2 objects in the Branch A will be updated during a rebase. ![](../media/branch_rebase_no_conflict.excalidraw.svg) -#### Conflicts between Branches +#### Conflicts between branches If the same attribute or the same relationship has been modified both in a branch and in main, the conflict will need to be resolved manually before the branch can be merged. -Conflicts in a branch can be resolved as part of a Proposed Change +Conflicts in a branch can be resolved as part of a Proposed Change. diff --git a/docs/docs/tutorials/getting-started/git-integration.mdx b/docs/docs/tutorials/getting-started/git-integration.mdx index ef36a80936..5665e419e4 100644 --- a/docs/docs/tutorials/getting-started/git-integration.mdx +++ b/docs/docs/tutorials/getting-started/git-integration.mdx @@ -4,17 +4,15 @@ title: Integration with Git # Connect a Git repository to Infrahub -One of the three pillars Infrahub is built on is the idea of having **Unified Version Control for Data and Files** at the same time. The data is stored in the Graph Database and the files in Git. +One of the three pillars Infrahub is built on is the idea of having unified storage for data and files. The data is stored in the graph database and the files are stored in Git. -When integrating a Git repository with Infrahub, the Git agent will ensure that both systems stay in sync at any time. +When integrating a Git repository with Infrahub, the Git agent will ensure that both systems stay in sync at any time. Changes to branches or files in a Git repository will be synced to Infrahub automatically. ## Fork & Clone the repository for the demo Create a fork of the repository: -| Branch `stable` | Branch `develop` | -| --- | --- | -| [infrahub-demo-edge](https://github.com/opsmill/infrahub-demo-edge) | [infrahub-demo-edge-develop](https://github.com/opsmill/infrahub-demo-edge-develop) | +[infrahub-demo-edge](https://github.com/opsmill/infrahub-demo-edge) :::info @@ -28,8 +26,7 @@ Once you have created a fork in GitHub, you'll need a Personal Access Token to a :::note -If you already cloned the repository in the past, ensure only the main branch is present in GitHub. -If other branches are present, we recommend deleting them before continuing. +If you already cloned the repository in the past, ensure only the main branch is present in GitHub. If other branches are present, we recommend deleting them before continuing. ::: @@ -59,7 +56,7 @@ After adding the `infrahub-demo-edge` repository you will be able to see several :::note Troubleshooting -If you don't seeing additional objects under the transformations or `GraphQL Queries`, it's possible that the `Git agent` might not be running anymore. +If you don't see additional objects under the transformations or `GraphQL Queries`, it's possible that the `Git agent` might not be running anymore. In this case, you should run `invoke demo.start` first to ensure that everything is working. diff --git a/docs/docs/tutorials/getting-started/introduction-to-infrahub.mdx b/docs/docs/tutorials/getting-started/introduction-to-infrahub.mdx index d7bd58c34c..86e59711f3 100644 --- a/docs/docs/tutorials/getting-started/introduction-to-infrahub.mdx +++ b/docs/docs/tutorials/getting-started/introduction-to-infrahub.mdx @@ -10,7 +10,7 @@ Before starting this tutorial, let's take a moment to explore how Infrahub is or ![Infrahub architecture](../../media/high_level_architecture.excalidraw.svg) -During this tutorial we'll mainly use the Frontend, the `infrahubctl` CLI and GraphQL via the API Server. +During this tutorial we'll mainly use the Frontend, the `infrahubctl` CLI and the GraphQL API via the API Server. | Name | Description | Demo Environment | | --------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- | @@ -19,6 +19,6 @@ During this tutorial we'll mainly use the Frontend, the `infrahubctl` CLI and Gr | **API server** | GraphQL and REST API server, primary component to interact with the data. | [http://localhost:8000/graphql](http://localhost:8000/graphql) | | **Git agent** | Infrahub agent that manages all content hosted in Git. | --- | | **Git server** | External Git server like GitHub or GitLab that can host some Git repositories. | --- | -| **GraphDB** | Main database where all information in the graph are stored. Neo4j 5.x | --- | +| **GraphDB** | Main database based on neo4j where all information in the graph are stored. | --- | | **Cache** | Cache based on Redis. Mainly used to support the reservation of shared resources across all components. | --- | | **Message bus** | Message bus based on RabbitMQ to allow all components to interact. | --- | diff --git a/docs/docs/tutorials/getting-started/readme.mdx b/docs/docs/tutorials/getting-started/readme.mdx index 8b26d362b6..b524fc729e 100644 --- a/docs/docs/tutorials/getting-started/readme.mdx +++ b/docs/docs/tutorials/getting-started/readme.mdx @@ -11,7 +11,7 @@ This tutorial doesn't require any prior knowledge, but knowledge of Git, GraphQL ::: -This tutorial will get you started with Infrahub and it will help you get familiar with some of the main components and concepts behind Infrahub. To do that we'll use a sample dataset that represents a small network with 6 devices. This tutorial will teach you: +This tutorial will get you started with using Infrahub and it will help you get familiar with some of the main components and concepts behind Infrahub. To do this we'll use a sample dataset that represents a small network with 6 devices. This tutorial will teach you: - How to manage branches and query any branches. - How to integrate a Git repository within Infrahub. diff --git a/docs/sidebars.ts b/docs/sidebars.ts index 496ae131ce..eede59d73b 100644 --- a/docs/sidebars.ts +++ b/docs/sidebars.ts @@ -1,18 +1,28 @@ import type {SidebarsConfig} from '@docusaurus/plugin-content-docs'; /** - * Creating a sidebar enables you to: - - create an ordered group of docs - - render a sidebar for each doc of that group - - provide next/previous navigation + * Creating a sidebar enables you to: + - create an ordered group of docs + - render a sidebar for each doc of that group + - provide next/previous navigation - The sidebars can be generated from the filesystem, or explicitly defined here. + The sidebars can be generated from the filesystem, or explicitly defined here. - Create as many sidebars as you want. + Create as many sidebars as you want. */ const sidebars: SidebarsConfig = { docsSidebar: [ 'readme', + { + type: 'category', + label: 'Infrahub Overview', + link: {type: 'doc', id: 'overview/readme'}, + items: [ + 'overview/interfaces', + 'overview/schema', + 'overview/data', + ], + }, { 'Tutorials': [ { @@ -52,6 +62,8 @@ const sidebars: SidebarsConfig = { 'guides/artifact', 'guides/database-backup', 'guides/profiles', + 'guides/object-storage', + 'guides/check', ], }, { @@ -66,7 +78,7 @@ const sidebars: SidebarsConfig = { 'topics/architecture', 'topics/artifact', 'topics/check', - 'topics/hardware-requirements', + 'topics/hardware-requirements', 'topics/ipam', 'topics/local-demo-environment', 'topics/generator', @@ -80,7 +92,7 @@ const sidebars: SidebarsConfig = { 'topics/auth', 'topics/database-backup', 'topics/resources-testing-framework', - 'topics/profiles', + 'topics/profiles', ], }, { @@ -125,7 +137,8 @@ const sidebars: SidebarsConfig = { 'reference/message-bus-events', 'reference/api-server', 'reference/dotinfrahub', - 'reference/infrahub-tests' + 'reference/infrahub-tests', + 'reference/schema-validation' ], }, { @@ -146,7 +159,9 @@ const sidebars: SidebarsConfig = { 'python-sdk/guides/create_update_delete', 'python-sdk/guides/branches', 'python-sdk/guides/store', - 'python-sdk/guides/tracking' + 'python-sdk/guides/tracking', + 'python-sdk/guides/batch', + 'python-sdk/guides/object-storage' ], }, { @@ -167,36 +182,70 @@ const sidebars: SidebarsConfig = { }, { type: 'category', - label: 'Infrahub Sync', + label: 'infrahubctl', + link: {type: 'doc', id: 'infrahubctl'}, + items: [{type: 'autogenerated', dirName: 'infrahubctl' }], + }, + { + type: 'category', + label: 'Integrations', link: { type: 'doc', - id: 'sync/readme' + id: 'integrations/readme' }, items: [ { type: 'category', - label: 'Guides', + label: 'Infrahub Ansible Collection', + link: { + type: 'doc', + id: 'integrations/infrahub-ansible/readme' + }, items: [ - 'sync/guides/installation', - 'sync/guides/creation', - 'sync/guides/run', + { + }, ], }, { type: 'category', - label: 'Reference', + label: 'Infrahub Sync', + link: { + type: 'doc', + id: 'integrations/sync/readme' + }, items: [ - 'sync/reference/config', - 'sync/reference/cli', + { + type: 'category', + label: 'Guides', + items: [ + 'integrations/sync/guides/installation', + 'integrations/sync/guides/creation', + 'integrations/sync/guides/run', + ], + }, + { + type: 'category', + label: 'Reference', + items: [ + 'integrations/sync/reference/config', + 'integrations/sync/reference/cli', + ], + }, ], }, - ], - }, - { - type: 'category', - label: 'infrahubctl', - link: {type: 'doc', id: 'infrahubctl'}, - items: [{type: 'autogenerated', dirName: 'infrahubctl' }], + { + type: 'category', + label: 'Nornir plugin for Infrahub', + link: { + type: 'doc', + id: 'integrations/nornir-infrahub/readme' + }, + items: [ + { + }, + ], + }, + ] }, { type: 'category', @@ -219,6 +268,7 @@ const sidebars: SidebarsConfig = { }, { 'Release Notes': [ + 'release-notes/release-0_14', 'release-notes/release-0_13', 'release-notes/release-0_12', 'release-notes/release-0_11', @@ -228,6 +278,7 @@ const sidebars: SidebarsConfig = { 'release-notes/release-0_7', 'release-notes/release-0_6'], }, + 'faq/faq', ], }; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index b96da846a8..6338d9fab6 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -47,6 +47,7 @@ "react-datepicker": "^4.11.0", "react-diff-view": "^3.2.0", "react-dom": "^18.2.0", + "react-error-boundary": "^4.0.13", "react-hook-form": "^7.51.2", "react-loading": "^2.0.3", "react-markdown": "^9.0.1", @@ -15778,6 +15779,17 @@ "react": "^18.2.0" } }, + "node_modules/react-error-boundary": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-4.0.13.tgz", + "integrity": "sha512-b6PwbdSv8XeOSYvjt8LpgpKrZ0yGdtZokYwkwV2wlcZbxgopHX/hgPl5VgpnoVOWd868n1hktM8Qm4b+02MiLQ==", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "peerDependencies": { + "react": ">=16.13.1" + } + }, "node_modules/react-fast-compare": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz", @@ -30052,6 +30064,14 @@ "scheduler": "^0.23.0" } }, + "react-error-boundary": { + "version": "4.0.13", + "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-4.0.13.tgz", + "integrity": "sha512-b6PwbdSv8XeOSYvjt8LpgpKrZ0yGdtZokYwkwV2wlcZbxgopHX/hgPl5VgpnoVOWd868n1hktM8Qm4b+02MiLQ==", + "requires": { + "@babel/runtime": "^7.12.5" + } + }, "react-fast-compare": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz", diff --git a/frontend/package.json b/frontend/package.json index 338fad4558..e040b0aaa2 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -69,6 +69,7 @@ "react-datepicker": "^4.11.0", "react-diff-view": "^3.2.0", "react-dom": "^18.2.0", + "react-error-boundary": "^4.0.13", "react-hook-form": "^7.51.2", "react-loading": "^2.0.3", "react-markdown": "^9.0.1", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 280a99b570..7b349c1820 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -16,15 +16,23 @@ export default defineConfig({ /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: !!process.env.CI, /* Retry on CI only */ - retries: process.env.CI ? 2 : 0, + retries: process.env.CI ? 1 : 0, /* 30s timeout for both assertions and tests (2min in CI) */ - timeout: process.env.CI ? 2 * 60 * 1000 : 30 * 1000, + timeout: process.env.CI + ? process.env.INFRAHUB_MISC_RESPONSE_DELAY + ? 6 * 60 * 1000 + : 2 * 60 * 1000 + : 30 * 1000, expect: { - timeout: process.env.CI ? 2 * 60 * 1000 : 30 * 1000, + timeout: process.env.CI + ? process.env.INFRAHUB_MISC_RESPONSE_DELAY + ? 6 * 60 * 1000 + : 2 * 60 * 1000 + : 30 * 1000, toHaveScreenshot: { maxDiffPixels: 5000 }, }, /* Opt out of parallel tests on CI. */ - workers: process.env.CI ? 3 : undefined, + workers: process.env.CI ? 4 : undefined, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: [ ["list"], diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0c864ef8c7..00931b4f06 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -37,6 +37,11 @@ const ObjectItemDetailsPaginated = loadable( () => import("./screens/object-item-details/object-item-details-paginated") ); const Homepage = loadable(() => import("./screens/homepage")); +const ResourceManager = loadable(() => import("./screens/resource-manager/resource-manager-page")); +const ResourcePool = loadable(() => import("./screens/resource-manager/resource-pool-page")); +const ResourceAllocationPage = loadable( + () => import("./screens/resource-manager/resource-allocation-page") +); const SignIn = loadable(() => import("./screens/sign-in/sign-in")); const IpamPage = loadable(() => import("./screens/ipam/ipam-page")); const IpamRouter = loadable(() => import("./screens/ipam/ipam-router")); @@ -68,6 +73,13 @@ const App = () => { } /> } /> } /> + } /> + }> + } + /> + } /> }> } /> diff --git a/frontend/src/components/branch-selector.tsx b/frontend/src/components/branch-selector.tsx index 7132ef5903..5cfebfdc4d 100644 --- a/frontend/src/components/branch-selector.tsx +++ b/frontend/src/components/branch-selector.tsx @@ -11,6 +11,7 @@ import { usePermission } from "../hooks/usePermission"; import { DynamicFieldData } from "../screens/edit-form-hook/dynamic-control-types"; import { Form } from "../screens/edit-form-hook/form"; import { branchesState, currentBranchAtom } from "../state/atoms/branches.atom"; +import { branchesToSelectOptions } from "../utils/branches"; import { classNames } from "../utils/common"; import { BUTTON_TYPES } from "./buttons/button"; import { ButtonWithTooltip } from "./buttons/button-with-tooltip"; @@ -18,18 +19,10 @@ import { SelectButton } from "./buttons/select-button"; import { DateDisplay } from "./display/date-display"; import { POPOVER_SIZE, PopOver } from "./display/popover"; import { SelectOption } from "./inputs/select"; -import { branchesToSelectOptions } from "../utils/branches"; const getBranchIcon = (branch: Branch | null, active?: Boolean) => branch && ( <> - {branch.is_isolated && ( - - )} - {branch.has_schema_changes && ( { } const mutationString = updateObjectWithId({ - kind: PROPOSED_CHANGES_CHANGE_THREAD_OBJECT, + kind: displayContext + ? PROPOSED_CHANGES_CHANGE_THREAD_OBJECT // for conversations view + : PROPOSED_CHANGES_OBJECT_THREAD_OBJECT, // for object views data: stringifyWithoutQuotes({ id: thread.id, resolved: { @@ -135,7 +138,9 @@ export const Thread = (props: tThread) => { context: { branch: branch?.name, date }, }); - refetch(); + if (refetch) { + refetch(); + } if (confirmModal) { setConfirmModal(false); diff --git a/frontend/src/components/display/password-display.tsx b/frontend/src/components/display/password-display.tsx index 7a083ca57f..3e0bc83274 100644 --- a/frontend/src/components/display/password-display.tsx +++ b/frontend/src/components/display/password-display.tsx @@ -1,6 +1,6 @@ import { Icon } from "@iconify-icon/react"; import { useState } from "react"; -import { MAX_VALUE_LENGTH_DISPLAY } from "../../config/constants"; +import { MAX_PASSWORD_DOTS_DISPLAY, MAX_VALUE_LENGTH_DISPLAY } from "../../config/constants"; import { BUTTON_TYPES, Button } from "../buttons/button"; type tPasswordDisplayProps = { @@ -32,7 +32,9 @@ export const PasswordDisplay = (props: tPasswordDisplayProps) => { ); } - const passwordCircles = Array.from(Array(value.length)).map((value: null, index: number) => ( + const passwordCircles = Array.from( + Array(value.length < MAX_PASSWORD_DOTS_DISPLAY ? value.length : MAX_PASSWORD_DOTS_DISPLAY) + ).map((value: null, index: number) => ( )); diff --git a/frontend/src/components/display/question-mark.tsx b/frontend/src/components/display/question-mark.tsx new file mode 100644 index 0000000000..5ddd1dedb2 --- /dev/null +++ b/frontend/src/components/display/question-mark.tsx @@ -0,0 +1,18 @@ +import { Icon } from "@iconify-icon/react"; +import { Tooltip } from "../ui/tooltip"; + +type tQuestionMark = { + message?: string; +}; + +export const QuestionMark = ({ message }: tQuestionMark) => { + if (!message) return null; + + return ( + + + + + + ); +}; diff --git a/frontend/src/components/editor/code-editor.tsx b/frontend/src/components/editor/code-editor.tsx index b239508c61..b495e66fa5 100644 --- a/frontend/src/components/editor/code-editor.tsx +++ b/frontend/src/components/editor/code-editor.tsx @@ -44,8 +44,8 @@ export const CodeEditor = (props: any) => { onChange(code)} + value={value ? (typeof value === "string" ? value : JSON.stringify(value)) : ""} + onValueChange={onChange} highlight={(code) => Prism.highlight(code, Prism.languages.json, "json")} padding={10} style={{ diff --git a/frontend/src/components/file.tsx b/frontend/src/components/file.tsx index 3163591f78..1bc0cd3c28 100644 --- a/frontend/src/components/file.tsx +++ b/frontend/src/components/file.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import { toast } from "react-toastify"; +import NoDataFound from "../screens/errors/no-data-found"; import LoadingScreen from "../screens/loading-screen/loading-screen"; -import NoDataFound from "../screens/no-data-found/no-data-found"; import { fetchStream } from "../utils/fetch"; import { CodeEditor } from "./editor/code-editor"; import { ALERT_TYPES, Alert } from "./utils/alert"; diff --git a/frontend/src/components/filters/filters.tsx b/frontend/src/components/filters/filters.tsx index 91e5a2dd5e..5c5f0501a0 100644 --- a/frontend/src/components/filters/filters.tsx +++ b/frontend/src/components/filters/filters.tsx @@ -18,12 +18,6 @@ type tFilters = { const computeFilter = (data: [key: string, value: any]) => { const [key, value] = data; - if (value.value) - return { - name: `${key}__value`, - value: value.value, - }; - if (value.id) { return { name: `${key}__ids`, @@ -31,10 +25,17 @@ const computeFilter = (data: [key: string, value: any]) => { }; } - if (value.list?.length) { + if (Array.isArray(value)) { return { name: `${key}__ids`, - value: value.list, + value: value, + }; + } + + if (value) { + return { + name: `${key}__value`, + value, }; } }; diff --git a/frontend/src/components/form/checkbox.tsx b/frontend/src/components/form/checkbox.tsx index 2f05f05c83..ee02339c67 100644 --- a/frontend/src/components/form/checkbox.tsx +++ b/frontend/src/components/form/checkbox.tsx @@ -1,10 +1,12 @@ import { LockClosedIcon } from "@heroicons/react/24/outline"; import { useState } from "react"; import { FormFieldError } from "../../screens/edit-form-hook/form"; +import { QuestionMark } from "../display/question-mark"; import { Checkbox } from "../inputs/checkbox"; interface Props { label: string; + description?: string; value: boolean; onChange: (value: boolean) => void; error?: FormFieldError; @@ -13,7 +15,7 @@ interface Props { } export default function OpsCheckbox(props: Props) { - const { label, onChange, value, error, isProtected, isOptional } = props; + const { label, description, onChange, value, error, isProtected, isOptional } = props; const [enabled, setEnabled] = useState(value); return ( @@ -23,6 +25,7 @@ export default function OpsCheckbox(props: Props) { {label} {isOptional ? "" : "*"}
{isProtected ? : null}
+
void; className?: string; @@ -16,7 +18,17 @@ type OpsColorPickerProps = { }; export const OpsColorPicker = (props: OpsColorPickerProps) => { - const { className, onChange, value, label, error, isProtected, isOptional, disabled } = props; + const { + className, + onChange, + value, + label, + description, + error, + isProtected, + isOptional, + disabled, + } = props; return ( <> @@ -25,6 +37,7 @@ export const OpsColorPicker = (props: OpsColorPickerProps) => { {label} {!isOptional && "*"} {isProtected && } +
void; className?: string; @@ -15,7 +17,17 @@ type OpsDatePickerProps = { }; export const OpsDatePicker = (props: OpsDatePickerProps) => { - const { className, onChange, value, label, error, isOptional, disabled, isProtected } = props; + const { + className, + description, + onChange, + value, + label, + error, + isOptional, + disabled, + isProtected, + } = props; return ( <> @@ -24,6 +36,7 @@ export const OpsDatePicker = (props: OpsDatePickerProps) => { {label} {isOptional ? "" : "*"}
{isProtected ? : null}
+ void; className?: string; + description?: string; error?: FormFieldError; type: string; isProtected?: boolean; @@ -19,8 +21,18 @@ type OpsInputProps = { const InputUniqueTips = () => must be unique; export const OpsInput = (props: OpsInputProps) => { - const { className, onChange, value, label, error, isProtected, isOptional, isUnique, disabled } = - props; + const { + className, + onChange, + value, + label, + description, + error, + isProtected, + isOptional, + isUnique, + disabled, + } = props; return ( <> @@ -30,6 +42,7 @@ export const OpsInput = (props: OpsInputProps) => { {isProtected && } {isUnique && } + void; - error?: FormFieldError; - isProtected?: boolean; -}; - -export default function OpsMultiSelect(props: OpsMultiSelectProps) { - const { label, isProtected, ...propsToPass } = props; - - return ( - <> - - ({ + id: option.id, + name: option.display_label, + description: option.description?.value, + }))} + data-testid="namespace-select" + preventEmpty + /> + + ); +}; diff --git a/frontend/src/screens/ipam/ipam-page.tsx b/frontend/src/screens/ipam/ipam-page.tsx index 32df19bedc..3933efa8ff 100644 --- a/frontend/src/screens/ipam/ipam-page.tsx +++ b/frontend/src/screens/ipam/ipam-page.tsx @@ -3,11 +3,14 @@ import { Outlet } from "react-router-dom"; import { Card } from "../../components/ui/card"; import Content from "../layout/content"; import IpamTree from "./ipam-tree/ipam-tree"; +import IpNamespaceSelector from "./ip-namespace-selector"; export default function IpamPage() { return ( <> - + + + diff --git a/frontend/src/screens/ipam/ipam-router.tsx b/frontend/src/screens/ipam/ipam-router.tsx index dea4ed6b5c..c829086b1d 100644 --- a/frontend/src/screens/ipam/ipam-router.tsx +++ b/frontend/src/screens/ipam/ipam-router.tsx @@ -1,5 +1,5 @@ import { Icon } from "@iconify-icon/react"; -import { useAtomValue } from "jotai"; +import { useAtomValue, useSetAtom } from "jotai"; import { useRef, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { StringParam, useQueryParam } from "use-query-params"; @@ -11,6 +11,7 @@ import { DEFAULT_BRANCH_NAME } from "../../config/constants"; import { usePermission } from "../../hooks/usePermission"; import { currentBranchAtom } from "../../state/atoms/branches.atom"; import { genericsState, schemaState } from "../../state/atoms/schema.atom"; +import { constructPath } from "../../utils/fetch"; import ObjectItemCreate from "../object-item-create/object-item-create-paginated"; import { IPAM_QSP, @@ -20,8 +21,9 @@ import { IP_PREFIX_GENERIC, } from "./constants"; import IpamIPAddresses from "./ip-addresses/ipam-ip-address"; +import { reloadIpamTreeAtom } from "./ipam-tree/ipam-tree.state"; import IpamIPPrefixes from "./prefixes/ipam-prefixes"; -import { constructPath } from "../../utils/fetch"; +import { defaultIpNamespaceAtom } from "./common/namespace.state"; const tabToKind = { [IPAM_TABS.IP_DETAILS]: IP_ADDRESS_GENERIC, @@ -29,13 +31,16 @@ const tabToKind = { }; export default function IpamRouter() { - const [qspTab] = useQueryParam(IPAM_QSP, StringParam); + const [qspTab] = useQueryParam(IPAM_QSP.TAB, StringParam); const navigate = useNavigate(); const { prefix } = useParams(); const permission = usePermission(); const branch = useAtomValue(currentBranchAtom); const schemaList = useAtomValue(schemaState); const genericList = useAtomValue(genericsState); + const [namespace] = useQueryParam(IPAM_QSP.NAMESPACE, StringParam); + const defaultIpNamespace = useAtomValue(defaultIpNamespaceAtom); + const reloadIpamTree = useSetAtom(reloadIpamTreeAtom); const refetchRef = useRef(null); const objectname = qspTab ? tabToKind[qspTab] : IP_PREFIX_GENERIC; @@ -51,11 +56,11 @@ export default function IpamRouter() { name: IPAM_TABS.SUMMARY, onClick: () => { if (prefix) { - navigate(constructPath(`${IPAM_ROUTE.PREFIXES}/${prefix}`)); + navigate(constructPath(`${IPAM_ROUTE.PREFIXES}/${prefix}`, [], [IPAM_QSP.NAMESPACE])); return; } - navigate(constructPath(IPAM_ROUTE.PREFIXES)); + navigate(constructPath(IPAM_ROUTE.PREFIXES, [], [IPAM_QSP.NAMESPACE])); return; }, }, @@ -64,9 +69,11 @@ export default function IpamRouter() { name: IPAM_TABS.PREFIX_DETAILS, onClick: () => { navigate( - constructPath(prefix ? `${IPAM_ROUTE.PREFIXES}/${prefix}` : IPAM_ROUTE.PREFIXES, [ - { name: IPAM_QSP, value: IPAM_TABS.PREFIX_DETAILS }, - ]) + constructPath( + prefix ? `${IPAM_ROUTE.PREFIXES}/${prefix}` : IPAM_ROUTE.PREFIXES, + [{ name: IPAM_QSP.TAB, value: IPAM_TABS.PREFIX_DETAILS }], + [IPAM_QSP.NAMESPACE] + ) ); return; }, @@ -77,15 +84,21 @@ export default function IpamRouter() { onClick: () => { if (prefix) { navigate( - constructPath(`${IPAM_ROUTE.PREFIXES}/${prefix}`, [ - { name: IPAM_QSP, value: IPAM_TABS.IP_DETAILS }, - ]) + constructPath( + `${IPAM_ROUTE.PREFIXES}/${prefix}`, + [{ name: IPAM_QSP.TAB, value: IPAM_TABS.IP_DETAILS }], + [IPAM_QSP.NAMESPACE] + ) ); return; } navigate( - constructPath(IPAM_ROUTE.ADDRESSES, [{ name: IPAM_QSP, value: IPAM_TABS.IP_DETAILS }]) + constructPath( + IPAM_ROUTE.ADDRESSES, + [{ name: IPAM_QSP.TAB, value: IPAM_TABS.IP_DETAILS }], + [IPAM_QSP.NAMESPACE] + ) ); return; }, @@ -119,7 +132,7 @@ export default function IpamRouter() { return ( - +
{renderContent()}
@@ -151,7 +164,14 @@ export default function IpamRouter() { open={showCreateDrawer} setOpen={setShowCreateDrawer}> setShowCreateDrawer(false)} + onCreate={() => { + setShowCreateDrawer(false); + + const currentIpNamespace = namespace ?? defaultIpNamespace; + if (currentIpNamespace) { + reloadIpamTree(currentIpNamespace, prefix); + } + }} onCancel={() => setShowCreateDrawer(false)} objectname={objectname!} refetch={refetchRef?.current?.refetch} diff --git a/frontend/src/screens/ipam/ipam-tree/ipam-tree.state.ts b/frontend/src/screens/ipam/ipam-tree/ipam-tree.state.ts new file mode 100644 index 0000000000..736fbcf3c1 --- /dev/null +++ b/frontend/src/screens/ipam/ipam-tree/ipam-tree.state.ts @@ -0,0 +1,126 @@ +import { atom } from "jotai"; +import * as R from "ramda"; +import { TreeProps } from "../../../components/ui/tree"; +import graphqlClient from "../../../graphql/graphqlClientApollo"; +import { + GET_PREFIX_ANCESTORS, + GET_PREFIXES_ONLY, + GET_TOP_LEVEL_PREFIXES, +} from "../../../graphql/queries/ipam/prefixes"; +import { currentBranchAtom } from "../../../state/atoms/branches.atom"; +import { datetimeAtom } from "../../../state/atoms/time.atom"; +import { IP_PREFIX_GENERIC, IPAM_TREE_ROOT_ID } from "../constants"; +import { + AncestorsData, + EMPTY_IPAM_TREE, + formatIPPrefixResponseForTreeView, + PrefixData, + updateTreeData, +} from "./utils"; + +export const ipamTreeAtom = atom(EMPTY_IPAM_TREE); + +export const reloadIpamTreeAtom = atom( + null, + async (get, set, namespaceId: string, currentPrefixId?: string) => { + const currentIpamTree = get(ipamTreeAtom); + const currentBranch = get(currentBranchAtom); + const timeMachineDate = get(datetimeAtom); + + const { data: getTopLevelPrefixData } = await graphqlClient.query({ + query: GET_TOP_LEVEL_PREFIXES, + variables: { namespaces: [namespaceId] }, + context: { + branch: currentBranch?.name, + date: timeMachineDate, + }, + }); + + if (!getTopLevelPrefixData) return currentIpamTree; + + const topLevelTreeItems = formatIPPrefixResponseForTreeView(getTopLevelPrefixData); + const treeWithTopLevelPrefixesOnly = updateTreeData( + EMPTY_IPAM_TREE, + IPAM_TREE_ROOT_ID, + topLevelTreeItems + ); + + if (!currentPrefixId) { + set(ipamTreeAtom, treeWithTopLevelPrefixesOnly); + return treeWithTopLevelPrefixesOnly; + } + + const { data: getFetchPrefixAncestorsData } = await graphqlClient.query({ + query: GET_PREFIX_ANCESTORS, + context: { + branch: currentBranch?.name, + date: timeMachineDate, + }, + variables: { + ids: [currentPrefixId], + namespaces: [namespaceId], + }, + }); + + const prefixAncestorsData = getFetchPrefixAncestorsData[IP_PREFIX_GENERIC].edges[0]; + if (!prefixAncestorsData) { + console.error(`Prefix ${currentPrefixId} not found.`); + set(ipamTreeAtom, treeWithTopLevelPrefixesOnly); + return treeWithTopLevelPrefixesOnly; + } + + const ancestors = prefixAncestorsData.node.ancestors.edges.map(({ node }) => ({ + id: node.id, + name: node.display_label, + parentId: node.parent.node?.id ?? IPAM_TREE_ROOT_ID, + })); + + const parentToChildMap: Record = {}; + + ancestors.forEach(({ id, parentId }) => { + parentToChildMap[parentId] = id; + }); + + const orderedAncestorIds: string[] = []; + + const traverseHierarchy = (map: Record, parentId: string) => { + const childId = map[parentId]; + if (!childId) return; + + orderedAncestorIds.push(childId); + traverseHierarchy(map, childId); + }; + + traverseHierarchy(parentToChildMap, IPAM_TREE_ROOT_ID); + + const { data: getFetchPrefixesData } = await graphqlClient.query< + PrefixData, + { parentIds: string[] } + >({ + query: GET_PREFIXES_ONLY, + context: { + branch: currentBranch?.name, + date: timeMachineDate, + }, + variables: { + parentIds: [...orderedAncestorIds, currentPrefixId], + }, + }); + + const newtreeItems = formatIPPrefixResponseForTreeView(getFetchPrefixesData); + + const groupedByParent = R.groupBy( + (node) => node.parent?.toString() ?? IPAM_TREE_ROOT_ID, + newtreeItems + ); + + const newTree = [...orderedAncestorIds, currentPrefixId].reduce((acc, currentAncestorId) => { + const children = groupedByParent[currentAncestorId]; + if (!children) return acc; + return updateTreeData(acc, currentAncestorId, children); + }, treeWithTopLevelPrefixesOnly); + + set(ipamTreeAtom, newTree); + return newTree; + } +); diff --git a/frontend/src/screens/ipam/ipam-tree/ipam-tree.tsx b/frontend/src/screens/ipam/ipam-tree/ipam-tree.tsx index 6c4c57a57a..9c8d5da15f 100644 --- a/frontend/src/screens/ipam/ipam-tree/ipam-tree.tsx +++ b/frontend/src/screens/ipam/ipam-tree/ipam-tree.tsx @@ -1,124 +1,49 @@ -import { TreeItemProps, Tree } from "../../../components/ui/tree"; -import { useLazyQuery } from "../../../hooks/useQuery"; -import React, { useEffect, useState } from "react"; +import { Icon } from "@iconify-icon/react"; +import { useAtom, useAtomValue, useSetAtom } from "jotai"; +import { useEffect, useState } from "react"; import { ITreeViewOnLoadDataProps, NodeId } from "react-accessible-treeview"; import { Link, useNavigate, useParams } from "react-router-dom"; -import { Icon } from "@iconify-icon/react"; -import * as R from "ramda"; +import { Tree, TreeItemProps } from "../../../components/ui/tree"; +import { useLazyQuery } from "../../../hooks/useQuery"; -import { - GET_PREFIX_ANCESTORS, - GET_PREFIXES_ONLY, - GET_TOP_LEVEL_PREFIXES, -} from "../../../graphql/queries/ipam/prefixes"; -import { useAtomValue } from "jotai/index"; +import { StringParam, useQueryParam } from "use-query-params"; +import { GET_PREFIXES_ONLY } from "../../../graphql/queries/ipam/prefixes"; +import { defaultIpNamespaceAtom } from "../common/namespace.state"; import { genericsState, schemaState } from "../../../state/atoms/schema.atom"; import { constructPathForIpam } from "../common/utils"; +import { IPAM_QSP, IPAM_ROUTE } from "../constants"; import { IpamTreeSkeleton } from "./ipam-tree-skeleton"; -import { IP_PREFIX_GENERIC, IPAM_ROUTE, IPAM_TREE_ROOT_ID } from "../constants"; +import { ipamTreeAtom, reloadIpamTreeAtom } from "./ipam-tree.state"; import { - AncestorsData, - EMPTY_IPAM_TREE, - formatIPPrefixResponseForTreeView, PrefixData, + formatIPPrefixResponseForTreeView, + getTreeItemAncestors, updateTreeData, } from "./utils"; export default function IpamTree() { const { prefix } = useParams(); - const [selected, setSelected] = useState([]); + const [namespace] = useQueryParam(IPAM_QSP.NAMESPACE, StringParam); + const defaultIpNamespace = useAtomValue(defaultIpNamespaceAtom); + const [expandedIds, setExpandedIds] = useState([]); const [isLoading, setLoading] = useState(true); - const [treeData, setTreeData] = useState(EMPTY_IPAM_TREE); - const [fetchTopLevelIpPrefixes] = useLazyQuery(GET_TOP_LEVEL_PREFIXES); - const [fetchPrefixAncestors] = useLazyQuery(GET_PREFIX_ANCESTORS); + const [treeData, setTreeData] = useAtom(ipamTreeAtom); + const reloadIpamTree = useSetAtom(reloadIpamTreeAtom); const [fetchPrefixes] = useLazyQuery(GET_PREFIXES_ONLY); const navigate = useNavigate(); useEffect(() => { - fetchTopLevelIpPrefixes() - .then(({ data }) => { - if (!data) return; - - const topLevelTreeItems = formatIPPrefixResponseForTreeView(data); - - // assign all prefixes and IP addresses without parent to the root node - return updateTreeData(EMPTY_IPAM_TREE, IPAM_TREE_ROOT_ID, topLevelTreeItems); - }) - .then((tree) => { - if (!tree) return; - - if (!prefix) { - setTreeData(tree); - setLoading(false); - return; - } - - fetchPrefixAncestors({ variables: { ids: [prefix] } }) - .then(({ data }) => { - if (!data) return; - - const prefixAncestorsData = data[IP_PREFIX_GENERIC].edges[0]; - - if (!prefixAncestorsData) { - setTreeData(tree); - setLoading(false); - return; - } - - const ancestors = prefixAncestorsData.node.ancestors.edges.map(({ node }) => ({ - id: node.id, - name: node.display_label, - parentId: node.parent.node?.id ?? IPAM_TREE_ROOT_ID, - })); - - const parentToChildMap: Record = {}; - - ancestors.forEach(({ id, parentId }) => { - parentToChildMap[parentId] = id; - }); - - const orderedAncestorIds: string[] = []; - - const traverseHierarchy = (map: Record, parentId: string) => { - const childId = map[parentId]; - if (!childId) return; - - orderedAncestorIds.push(childId); - traverseHierarchy(map, childId); - }; - - traverseHierarchy(parentToChildMap, IPAM_TREE_ROOT_ID); - - return orderedAncestorIds; - }) - .then((orderedAncestorIds) => { - if (!orderedAncestorIds) return; - - fetchPrefixes({ variables: { parentIds: orderedAncestorIds } }).then(({ data }) => { - if (!data) return; - - const treeItems = formatIPPrefixResponseForTreeView(data); - const groupedByParent = R.groupBy( - (node) => node.parent?.toString() ?? IPAM_TREE_ROOT_ID, - treeItems - ); - - const newTree = orderedAncestorIds.reduce((acc, currentAncestorId) => { - const children = groupedByParent[currentAncestorId]; - if (!children) return acc; - return updateTreeData(acc, currentAncestorId, children); - }, tree); - - const currentPrefix = newTree.find(({ id }) => id === prefix); - setTreeData(newTree); - setSelected( - currentPrefix ? [...orderedAncestorIds, currentPrefix.id] : orderedAncestorIds - ); - setLoading(false); - }); - }); - }); - }, []); + const currentIpNamespace = namespace ?? defaultIpNamespace; + if (!currentIpNamespace) return; + + reloadIpamTree(currentIpNamespace, prefix).then((newTree) => { + if (prefix) { + const ancestorIds = getTreeItemAncestors(newTree, prefix).map(({ id }) => id); + setExpandedIds(ancestorIds); + } + setLoading(false); + }); + }, [namespace, defaultIpNamespace]); const onLoadData = async ({ element }: ITreeViewOnLoadDataProps) => { if (element.children.length > 0) return; // To avoid refetching data @@ -135,7 +60,7 @@ export default function IpamTree() { return (