diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-14 20:03:01 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-14 20:03:01 +0000 |
commit | a453ac31f3428614cceb99027f8efbdb9258a40b (patch) | |
tree | f61f87408f32a8511cbd91799f9cececb53e0374 /collections-debian-merged/ansible_collections/community/kubevirt | |
parent | Initial commit. (diff) | |
download | ansible-upstream.tar.xz ansible-upstream.zip |
Adding upstream version 2.10.7+merged+base+2.10.8+dfsg.upstream/2.10.7+merged+base+2.10.8+dfsgupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'collections-debian-merged/ansible_collections/community/kubevirt')
45 files changed, 5362 insertions, 0 deletions
diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/.github/workflows/ansible-test.yml b/collections-debian-merged/ansible_collections/community/kubevirt/.github/workflows/ansible-test.yml new file mode 100644 index 00000000..11ccbc74 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/.github/workflows/ansible-test.yml @@ -0,0 +1,177 @@ +# README FIRST +# 1. replace "NAMESPACE" and "COLLECTION_NAME" with the correct name in the env section (e.g. with 'community' and 'mycollection') +# 2. If you don't have unit tests remove that section +# 3. If your collection depends on other collections ensure they are installed, see "Install collection dependencies" +# If you need help please ask in #ansible-devel on Freenode IRC + +name: CI +on: + # Run CI against all pushes (direct commits, also merged PRs), Pull Requests + push: + pull_request: + # Uncomment the following two lines to run CI once per day (at 06:00 UTC) + schedule: + - cron: '0 6 * * *' +env: + NAMESPACE: community + COLLECTION_NAME: kubevirt + +jobs: + +### +# Sanity tests (REQUIRED) +# +# https://docs.ansible.com/ansible/latest/dev_guide/testing_sanity.html + + sanity: + name: Sanity (Ⓐ${{ matrix.ansible }}) + strategy: + matrix: + ansible: + # It's important that Sanity is tested against all stable-X.Y branches + # Testing against `devel` may fail as new tests are added. + - stable-2.9 + - stable-2.10 + - devel + runs-on: ubuntu-latest + steps: + + # ansible-test requires the collection to be in a directory in the form + # .../ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}}/ + + - name: Check out code + uses: actions/checkout@v2 + with: + path: ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + - name: Set up Python + uses: actions/setup-python@v2 + with: + # it is just required to run that once as "ansible-test sanity" in the docker image + # will run on all python versions it supports. + python-version: 3.8 + + # Install the head of the given branch (devel, stable-2.10) + - name: Install ansible-base (${{ matrix.ansible }}) + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check + + - name: Install collection dependencies + run: ansible-galaxy collection install community.kubernetes -p . + + # run ansible-test sanity inside of Docker. + # The docker container has all the pinned dependencies that are required + # and all python versions ansible supports. + - name: Run sanity tests + run: ansible-test sanity --docker -v --color + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + +### +# Unit tests (OPTIONAL) +# +# https://docs.ansible.com/ansible/latest/dev_guide/testing_units.html + + units: + runs-on: ubuntu-latest + name: Units (Ⓐ${{ matrix.ansible }}) + strategy: + # As soon as the first unit test fails, cancel the others to free up the CI queue + fail-fast: true + matrix: + ansible: + - stable-2.9 + - stable-2.10 + - devel + steps: + - name: Check out code + uses: actions/checkout@v2 + with: + path: ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + - name: Set up Python 3.8 + uses: actions/setup-python@v2 + with: + python-version: 3.8 + + - name: Install ansible-base (${{ matrix.ansible }}) + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check + + - name: Install collection dependencies + run: ansible-galaxy collection install community.kubernetes -p . + + # Run the unit tests + - name: Run unit test + run: ansible-test units -v --color --docker --coverage + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + # ansible-test support producing code coverage date + - name: Generate coverage report + run: ansible-test coverage xml -v --requirements --group-by command --group-by version + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + # See the reports at https://codecov.io/gh/ansible_collections/GITHUBORG/REPONAME + - uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false + +### +# Integration tests (RECOMMENDED) +# +# https://docs.ansible.com/ansible/latest/dev_guide/testing_integration.html + + +# If the application you are testing is available as a docker container and you want to test +# multiple versions see the following for an example: +# https://github.com/ansible-collections/community.zabbix/tree/master/.github/workflows + + integration: + runs-on: ubuntu-latest + name: I (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }}}) + strategy: + fail-fast: false + matrix: + ansible: + - stable-2.9 + - stable-2.10 + - devel + python: + - 2.7 + - 3.5 + - 3.6 + - 3.7 + - 3.8 + - 3.9 + exclude: + - ansible: stable-2.9 + python: 3.9 + + steps: + - name: Check out code + uses: actions/checkout@v2 + with: + path: ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + - name: Set up Python ${{ matrix.ansible }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + + - name: Install ansible-base (${{ matrix.ansible }}) + run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check + + - name: Install collection dependencies + run: ansible-galaxy collection install community.kubernetes -p . + + # Run the integration tests + - name: Run integration test + run: ansible-test integration -v --color --retry-on-error --continue-on-error --diff --python ${{ matrix.python }} --docker --coverage + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + # ansible-test support producing code coverage date + - name: Generate coverage report + run: ansible-test coverage xml -v --requirements --group-by command --group-by version + working-directory: ./ansible_collections/${{env.NAMESPACE}}/${{env.COLLECTION_NAME}} + + # See the reports at https://codecov.io/gh/ansible_collections/GITHUBORG/REPONAME + - uses: codecov/codecov-action@v1 + with: + fail_ci_if_error: false diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/.yamllint b/collections-debian-merged/ansible_collections/community/kubevirt/.yamllint new file mode 100644 index 00000000..88276760 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/.yamllint @@ -0,0 +1,33 @@ +--- +# Based on ansible-lint config +extends: default + +rules: + braces: + max-spaces-inside: 1 + level: error + brackets: + max-spaces-inside: 1 + level: error + colons: + max-spaces-after: -1 + level: error + commas: + max-spaces-after: -1 + level: error + comments: disable + comments-indentation: disable + document-start: disable + empty-lines: + max: 3 + level: error + hyphens: + level: error + indentation: disable + key-duplicates: enable + line-length: disable + new-line-at-end-of-file: disable + new-lines: + type: unix + trailing-spaces: disable + truthy: disable diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/CHANGELOG.rst b/collections-debian-merged/ansible_collections/community/kubevirt/CHANGELOG.rst new file mode 100644 index 00000000..86ea49d3 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/CHANGELOG.rst @@ -0,0 +1,27 @@ +================================ +community.kubevirt Release Notes +================================ + +.. contents:: Topics + + +v1.0.0 +====== + +Release Summary +--------------- + +This is the first stable release version of community.kubevirt. + +v0.1.0 +====== + +Release Summary +--------------- + +This is the first pre-release version of community.kubevirt after migrating from community.general. + +Bugfixes +-------- + +- kubevirt - Add aliases 'interface_name' for network_name (https://github.com/ansible/ansible/issues/55641). diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/FILES.json b/collections-debian-merged/ansible_collections/community/kubevirt/FILES.json new file mode 100644 index 00000000..a29c4e76 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/FILES.json @@ -0,0 +1,467 @@ +{ + "files": [ + { + "name": ".", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "LICENSE", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "format": 1 + }, + { + "name": "CHANGELOG.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "36d10bd8312dc5b5dfc371e1ad9014623fdb1bac645c953ee684dc2c9f70a463", + "format": 1 + }, + { + "name": "README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e7b85c8051e20ffdd86fb1bbaede8dd53601bf94bcf87837d9bce2bf0fc44a65", + "format": 1 + }, + { + "name": ".github", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github/workflows", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": ".github/workflows/ansible-test.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "fdafd0a0d4207262ae1a7debd62f7084722f553fcc57c1217de0cce49cc7013c", + "format": 1 + }, + { + "name": "changelogs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/changelog.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "03fdb056ed3615626cbb45193ab77bfcf0b8647e5c166c99e00ffff8f221faee", + "format": 1 + }, + { + "name": "changelogs/config.yaml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8ff4a5d975641a17a1c0f669529523c1c58c132429510e138044daf67c3a4d1f", + "format": 1 + }, + { + "name": "changelogs/fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "changelogs/fragments/.keep", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": ".yamllint", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5845e18e9f23155f423207df9abac970aed687c638620bc2c9ee06706191054b", + "format": 1 + }, + { + "name": "plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_pvc.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "224a8170e02b8bb3745da955504aeff58eb60115ec315e6be716ddb75025a3e6", + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_rs.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3a879a0618412848aadadba879b0db13fda6577546a4fd3a1eb2292848fdd139", + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_template.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e76b523ce19e0b65ea786a5b7f604ad5399ca8ee4bdb012aa2d0e658d4788ee6", + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_preset.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e0f02363b7501375c94d259f9ecf1e9d5f57132c572f42134cd1f647ef63c3d5", + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_vm.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b8b02f3e0f8c0dae8956bb07d49ff40082483c5fef5dc479c70cb76efbe60aa7", + "format": 1 + }, + { + "name": "plugins/modules/kubevirt_cdi_upload.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "deb9c4fd2d622a3d951afac97aaa79a46f0c6982954d49f8ddc1a789bae6267e", + "format": 1 + }, + { + "name": "plugins/README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c82ee692702ec1dd604cdbc38ff252114e5204e1b0627045a66c9451e7a918ac", + "format": 1 + }, + { + "name": "plugins/inventory", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/inventory/kubevirt.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "17ff63d4ef1bbc52b767d5a0043242ded06d0406a08656e9e693a5d2d6ac2d7e", + "format": 1 + }, + { + "name": "plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/module_utils/kubevirt.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f7386985f81b57e17a180f655b8d9f5761667859efbad2018d92a66701e8e4ef", + "format": 1 + }, + { + "name": "plugins/doc_fragments", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/doc_fragments/kubevirt_vm_options.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3ff22d0e5bcbbcd3491bb61e6dea8918da8738d967fe63311232e5b046400b45", + "format": 1 + }, + { + "name": "plugins/doc_fragments/kubevirt_common_options.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8a3e40ea6074efed7afd88caade050e040904b8f4cf0ac78f8b0ff9d9464fb75", + "format": 1 + }, + { + "name": "meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "meta/runtime.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "570307de2315dfc6701630cceeaefee6d79d388fa15b0237c134e0a3cbcc7291", + "format": 1 + }, + { + "name": "molecule", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "molecule/default", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "molecule/default/verify.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b94db48bc50299d3ab3b5a190f3dcfe070764256ba96138fcf6292ca0e911ed8", + "format": 1 + }, + { + "name": "molecule/default/INSTALL.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ddf3326f7dfb1fc88d2e5a9087e874ece93e08cb4a32cb30d235285d6ec9c68c", + "format": 1 + }, + { + "name": "molecule/default/converge.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "38fa79db29f354ddee65697503880cf72ce2e8b5ed8e626a429d2348bdf015df", + "format": 1 + }, + { + "name": "molecule/default/molecule.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3c405a2ba7fb9719b7e9824855087259ac0c9c5427d82d89d780aa992f3e5e5b", + "format": 1 + }, + { + "name": "tests", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.11.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2c13583818de0ca2cbdd4c4642f9ed820a1aad186ef56ef26814ffe19ce0865b", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.10.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2c13583818de0ca2cbdd4c4642f9ed820a1aad186ef56ef26814ffe19ce0865b", + "format": 1 + }, + { + "name": "tests/sanity/ignore-2.9.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dd22689be6ca6b0a5add1e017495f53b5b2e01929e447e5ad09cb73d23530b78", + "format": 1 + }, + { + "name": "tests/integration", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/aliases", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e5a8866bb35edfbfde89676bc1698a7dd27c89530da249de619169892e7482d1", + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/test.out", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "46bfa629dd84a66c7944bc00062d023c5130a385c9f0ec7e1670d13cdf2b1185", + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/server.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "cd8cb90a23c8a4241123857ef2e4a8f42f15b8f56639235fac3d126d7389881d", + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/runme.sh", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4c6db4449470aaa6565e5c511bb9c3377d078e3d1568d9c00b402e7bc6af25a8", + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/inventory_diff.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "feb395f3424b665f027a47573877907d2543c174c17a37fc6c6e83dd3b99f3ae", + "format": 1 + }, + { + "name": "tests/integration/targets/inventory_kubevirt/constraints.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e8b88db827901e5ef567c9fc5cc4e86bfd9a7b2a0aff3f2f63d95dd4f84392b8", + "format": 1 + }, + { + "name": "tests/unit", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/requirements.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "73ab0e43c8c56d5481ee3bf7f6c442b6a2ff5c37f6a0d0e09e50ab078b500398", + "format": 1 + }, + { + "name": "tests/unit/compat", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/compat/unittest.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5401a046e5ce71fa19b6d905abd0f9bdf816c0c635f7bdda6730b3ef06e67096", + "format": 1 + }, + { + "name": "tests/unit/compat/mock.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0af958450cf6de3fbafe94b1111eae8ba5a8dbe1d785ffbb9df81f26e4946d99", + "format": 1 + }, + { + "name": "tests/unit/compat/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "tests/unit/plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/kubevirt_fixtures.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bc1f97ebb0d3dcbe9e2e499260ebf7ef59c19e94e1c252a1d72ef3159b88aebc", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/utils.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "d6d056acfdce90af12551b4b86f2267e994b05b35ebdc9d84b358efa44951196", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_kubevirt_vm.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "26c0097faaa807baaf03793f8e46d4b8981a4d9da764384a65bf83072ae0045b", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/test_kubevirt_rs.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9f55610a7ad4ac4ab3eddbd5c82aad432bf0a234840edeba11f8f0288611b5ac", + "format": 1 + }, + { + "name": "tests/unit/plugins/modules/__init__.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "format": 1 + }, + { + "name": "tests/unit/plugins/module_utils", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "tests/unit/plugins/module_utils/test_kubevirt.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8decee4cdfd65ebd2239b8598fdbf4a9097ba2603491d798bbb80ab097a2fc60", + "format": 1 + } + ], + "format": 1 +}
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/LICENSE b/collections-debian-merged/ansible_collections/community/kubevirt/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/MANIFEST.json b/collections-debian-merged/ansible_collections/community/kubevirt/MANIFEST.json new file mode 100644 index 00000000..a47bfd83 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/MANIFEST.json @@ -0,0 +1,39 @@ +{ + "collection_info": { + "namespace": "community", + "name": "kubevirt", + "version": "1.0.0", + "authors": [ + "kubevirt (github.com/kubevirt)", + "tima (github.com/tima)" + ], + "readme": "README.md", + "tags": [ + "api", + "k8s", + "kubernetes", + "kubevirt", + "virtualization", + "cloud", + "infrastructure" + ], + "description": null, + "license": [], + "license_file": "LICENSE", + "dependencies": { + "community.kubernetes": ">=1.0.0" + }, + "repository": "https://github.com/ansible-collections/community.kubevirt", + "documentation": null, + "homepage": "https://github.com/ansible-collections/community.kubevirt", + "issues": "https://github.com/ansible-collections/community.kubevirt/issues" + }, + "file_manifest_file": { + "name": "FILES.json", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f6492c3dc19b84095067d04bf11ae9fac70a7971162cc15ef8c4cbbced357edb", + "format": 1 + }, + "format": 1 +}
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/README.md b/collections-debian-merged/ansible_collections/community/kubevirt/README.md new file mode 100644 index 00000000..348d3ce1 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/README.md @@ -0,0 +1,47 @@ +# KubeVirt Collection for Ansible +<!-- Add CI and code coverage badges here. Samples included below. --> +[![CI](https://github.com/ansible-collections/community.kubevirt/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/community.kubevirt/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.kubevirt)](https://codecov.io/gh/ansible-collections/community.kubevirt) + +<!-- Describe the collection and why a user would want to use it. What does the collection do? --> + +This repo hosts the `community.kubevirt` Ansible Collection. + +The collection includes a variety of Ansible content to automate the management of KubeVirt container native virtualization environments. + +## Included Content + + - **Inventory Source**: + - kubevirt + - **Modules**: + - kubevirt_cdi_upload + - kubevirt_preset + - kubevirt_pvc + - kubevirt_rs + - kubevirt_template + - kubevirt_vm + +<!-- ## Contributing to this collection --> + +<!--Describe how the community can contribute to your collection. At a minimum, include how and where users can create issues to report problems or request features for this collection. List contribution requirements, including preferred workflows and necessary testing, so you can benefit from community PRs. If you are following general Ansible contributor guidelines, you can link to - [Ansible Community Guide](https://docs.ansible.com/ansible/latest/community/index.html). --> + +## Release notes + +See the [changelog](https://github.com/ansible-collections/community.kubevirt/tree/main/CHANGELOG.rst). + +## More Information + +For more information about Ansible's Kubernetes integration, join the `#ansible-kubernetes` channel on Freenode IRC, and browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page. + +- [Ansible Collection overview](https://github.com/ansible-collections/overview) +- [Ansible User guide](https://docs.ansible.com/ansible/latest/user_guide/index.html) +- [Ansible Developer guide](https://docs.ansible.com/ansible/latest/dev_guide/index.html) +- [Ansible Collections Checklist](https://github.com/ansible-collections/overview/blob/master/collection_requirements.rst) +- [Ansible Community code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html) +- [The Bullhorn (the Ansible Contributor newsletter)](https://us19.campaign-archive.com/home/?u=56d874e027110e35dea0e03c1&id=d6635f5420) +- [Changes impacting Contributors](https://github.com/ansible-collections/overview/issues/45) + +## Licensing + +GNU General Public License v3.0 or later. + +See [LICENSE](https://www.gnu.org/licenses/gpl-3.0.txt) to see the full text. diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/changelog.yaml b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/changelog.yaml new file mode 100644 index 00000000..653aa63e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/changelog.yaml @@ -0,0 +1,18 @@ +ancestor: null +releases: + 0.1.0: + changes: + bugfixes: + - kubevirt - Add aliases 'interface_name' for network_name (https://github.com/ansible/ansible/issues/55641). + release_summary: This is the first pre-release version of community.kubevirt + after migrating from community.general. + fragments: + - 0.1.0.yml + - 55903_kubevirt.yml + release_date: '2020-11-25' + 1.0.0: + changes: + release_summary: This is the first stable release version of community.kubevirt. + fragments: + - 1.0.0.yaml + release_date: '2020-12-22' diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/config.yaml b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/config.yaml new file mode 100644 index 00000000..f357e294 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/config.yaml @@ -0,0 +1,29 @@ +changelog_filename_template: ../CHANGELOG.rst +changelog_filename_version_depth: 0 +changes_file: changelog.yaml +changes_format: combined +keep_fragments: false +mention_ancestor: true +new_plugins_after_name: removed_features +notesdir: fragments +prelude_section_name: release_summary +prelude_section_title: Release Summary +sections: +- - major_changes + - Major Changes +- - minor_changes + - Minor Changes +- - breaking_changes + - Breaking Changes / Porting Guide +- - deprecated_features + - Deprecated Features +- - removed_features + - Removed Features (previously deprecated) +- - security_fixes + - Security Fixes +- - bugfixes + - Bugfixes +- - known_issues + - Known Issues +title: community.kubevirt +trivial_section_name: trivial diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/fragments/.keep b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/fragments/.keep new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/changelogs/fragments/.keep diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/meta/runtime.yml b/collections-debian-merged/ansible_collections/community/kubevirt/meta/runtime.yml new file mode 100644 index 00000000..62e53c07 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/meta/runtime.yml @@ -0,0 +1,10 @@ +--- +requires_ansible: '>=2.9.10' +action_groups: + k8s: + - kubevirt_cdi_upload + - kubevirt_preset + - kubevirt_pvc + - kubevirt_rs + - kubevirt_template + - kubevirt_vm diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/INSTALL.rst b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/INSTALL.rst new file mode 100644 index 00000000..4fcb1b30 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/INSTALL.rst @@ -0,0 +1,22 @@ +******************************** +Docker driver installation guide +******************************** + +Requirements +============ + +* Docker Engine + +Install +======= + +Please refer to the `Virtual environment`_ documentation for installation best +practices. If not using a virtual environment, please consider passing the +widely recommended `'--user' flag`_ when invoking ``pip``. + +.. _Virtual environment: https://virtualenv.pypa.io/en/latest/ +.. _'--user' flag: https://packaging.python.org/tutorials/installing-packages/#installing-to-the-user-site + +.. code-block:: bash + + $ python3 -m pip install 'molecule[docker]' diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/converge.yml b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/converge.yml new file mode 100644 index 00000000..a80c0811 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/converge.yml @@ -0,0 +1,10 @@ +--- +- name: Converge + hosts: all + tasks: + - name: apt cache (on Debian) is up to date + apt: + update_cache: true + cache_valid_time: 3600 + when: ansible_os_family == 'Debian' + diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/molecule.yml b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/molecule.yml new file mode 100644 index 00000000..aafdc9d3 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/molecule.yml @@ -0,0 +1,13 @@ +--- +dependency: + name: galaxy +driver: + name: docker +platforms: + - name: instance + image: docker.io/pycontribs/centos:7 + pre_build_image: true +provisioner: + name: ansible +verifier: + name: ansible diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/verify.yml b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/verify.yml new file mode 100644 index 00000000..a82dd6fd --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/molecule/default/verify.yml @@ -0,0 +1,9 @@ +--- +# This is an example playbook to execute Ansible tests. + +- name: Verify + hosts: all + tasks: + - name: Example assertion + assert: + that: true diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/README.md b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/README.md new file mode 100644 index 00000000..6541cf7c --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/README.md @@ -0,0 +1,31 @@ +# Collections Plugins Directory + +This directory can be used to ship various plugins inside an Ansible collection. Each plugin is placed in a folder that +is named after the type of plugin it is in. It can also include the `module_utils` and `modules` directory that +would contain module utils and modules respectively. + +Here is an example directory of the majority of plugins currently supported by Ansible: + +``` +└── plugins + ├── action + ├── become + ├── cache + ├── callback + ├── cliconf + ├── connection + ├── filter + ├── httpapi + ├── inventory + ├── lookup + ├── module_utils + ├── modules + ├── netconf + ├── shell + ├── strategy + ├── terminal + ├── test + └── vars +``` + +A full list of plugin types can be found at [Working With Plugins](https://docs.ansible.com/ansible/2.9/plugins/plugins.html).
\ No newline at end of file diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_common_options.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_common_options.py new file mode 100644 index 00000000..ed25b724 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_common_options.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2018, KubeVirt Team <@kubevirt> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +class ModuleDocFragment(object): + DOCUMENTATION = r''' +options: + resource_definition: + description: + - "A partial YAML definition of the object being created/updated. Here you can define Kubernetes + resource parameters not covered by this module's parameters." + - "NOTE: I(resource_definition) has lower priority than module parameters. If you try to define e.g. + I(metadata.namespace) here, that value will be ignored and I(namespace) used instead." + aliases: + - definition + - inline + type: dict + wait: + description: + - "I(True) if the module should wait for the resource to get into desired state." + type: bool + default: yes + force: + description: + - If set to C(no), and I(state) is C(present), an existing object will be replaced. + type: bool + default: no + wait_timeout: + description: + - The amount of time in seconds the module should wait for the resource to get into desired state. + type: int + default: 120 + wait_sleep: + description: + - Number of seconds to sleep between checks. + default: 5 + memory: + description: + - The amount of memory to be requested by virtual machine. + - For example 1024Mi. + type: str + memory_limit: + description: + - The maximum memory to be used by virtual machine. + - For example 1024Mi. + type: str + machine_type: + description: + - QEMU machine type is the actual chipset of the virtual machine. + type: str + merge_type: + description: + - Whether to override the default patch merge approach with a specific type. + - If more than one merge type is given, the merge types will be tried in order. + - "Defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters + on resource kinds that combine Custom Resources and built-in resources, as + Custom Resource Definitions typically aren't updatable by the usual strategic merge." + - "See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment)" + type: list + choices: [ json, merge, strategic-merge ] + cpu_shares: + description: + - "Specify CPU shares." + type: int + cpu_limit: + description: + - "Is converted to its millicore value and multiplied by 100. The resulting value is the total amount of CPU time that a container can use + every 100ms. A virtual machine cannot use more than its share of CPU time during this interval." + type: int + cpu_cores: + description: + - "Number of CPU cores." + type: int + cpu_model: + description: + - "CPU model." + - "You can check list of available models here: U(https://github.com/libvirt/libvirt/blob/master/src/cpu_map/index.xml)." + - "I(Note:) User can define default CPU model via as I(default-cpu-model) in I(kubevirt-config) I(ConfigMap), if not set I(host-model) is used." + - "I(Note:) Be sure that node CPU model where you run a VM, has the same or higher CPU family." + - "I(Note:) If CPU model wasn't defined, the VM will have CPU model closest to one that used on the node where the VM is running." + type: str + bootloader: + description: + - "Specify the bootloader of the virtual machine." + - "All virtual machines use BIOS by default for booting." + type: str + smbios_uuid: + description: + - "In order to provide a consistent view on the virtualized hardware for the guest OS, the SMBIOS UUID can be set." + type: str + cpu_features: + description: + - "List of dictionary to fine-tune features provided by the selected CPU model." + - "I(Note): Policy attribute can either be omitted or contain one of the following policies: force, require, optional, disable, forbid." + - "I(Note): In case a policy is omitted for a feature, it will default to require." + - "More information about policies: U(https://libvirt.org/formatdomain.html#elementsCPU)" + type: list + headless: + description: + - "Specify if the virtual machine should have attached a minimal Video and Graphics device configuration." + - "By default a minimal Video and Graphics device configuration will be applied to the VirtualMachineInstance. The video device is vga + compatible and comes with a memory size of 16 MB." + hugepage_size: + description: + - "Specify huge page size." + type: str + tablets: + description: + - "Specify tablets to be used as input devices" + type: list + hostname: + description: + - "Specifies the hostname of the virtual machine. The hostname will be set either by dhcp, cloud-init if configured or virtual machine + name will be used." + subdomain: + description: + - "If specified, the fully qualified virtual machine hostname will be hostname.subdomain.namespace.svc.cluster_domain. If not specified, + the virtual machine will not have a domain name at all. The DNS entry will resolve to the virtual machine, no matter if the virtual machine + itself can pick up a hostname." +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +notes: + - "In order to use this module you have to install Openshift Python SDK. + To ensure it's installed with correct version you can create the following task: + I(pip: name=openshift>=0.8.2)" +''' diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_vm_options.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_vm_options.py new file mode 100644 index 00000000..89d17a99 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/doc_fragments/kubevirt_vm_options.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2018, KubeVirt Team <@kubevirt> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +class ModuleDocFragment(object): + + # Standard oVirt documentation fragment + DOCUMENTATION = r''' +options: + disks: + description: + - List of dictionaries which specify disks of the virtual machine. + - "A disk can be made accessible via four different types: I(disk), I(lun), I(cdrom), I(floppy)." + - "All possible configuration options are available in U(https://kubevirt.io/api-reference/master/definitions.html#_v1_disk)" + - Each disk must have specified a I(volume) that declares which volume type of the disk + All possible configuration options of volume are available in U(https://kubevirt.io/api-reference/master/definitions.html#_v1_volume). + type: list + labels: + description: + - Labels are key/value pairs that are attached to virtual machines. Labels are intended to be used to + specify identifying attributes of virtual machines that are meaningful and relevant to users, but do not directly + imply semantics to the core system. Labels can be used to organize and to select subsets of virtual machines. + Labels can be attached to virtual machines at creation time and subsequently added and modified at any time. + - More on labels that are used for internal implementation U(https://kubevirt.io/user-guide/#/misc/annotations_and_labels) + type: dict + interfaces: + description: + - An interface defines a virtual network interface of a virtual machine (also called a frontend). + - All possible configuration options interfaces are available in U(https://kubevirt.io/api-reference/master/definitions.html#_v1_interface) + - Each interface must have specified a I(network) that declares which logical or physical device it is connected to (also called as backend). + All possible configuration options of network are available in U(https://kubevirt.io/api-reference/master/definitions.html#_v1_network). + type: list + cloud_init_nocloud: + description: + - "Represents a cloud-init NoCloud user-data source. The NoCloud data will be added + as a disk to the virtual machine. A proper cloud-init installation is required inside the guest. + More information U(https://kubevirt.io/api-reference/master/definitions.html#_v1_cloudinitnocloudsource)" + type: dict + affinity: + description: + - "Describes node affinity scheduling rules for the vm." + type: dict + suboptions: + soft: + description: + - "The scheduler will prefer to schedule vms to nodes that satisfy the affinity expressions specified by this field, but it may choose a + node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for + each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute + a sum by iterating through the elements of this field and adding C(weight) to the sum if the node has vms which matches the corresponding + C(term); the nodes with the highest sum are the most preferred." + type: dict + hard: + description: + - "If the affinity requirements specified by this field are not met at scheduling time, the vm will not be scheduled onto the node. If + the affinity requirements specified by this field cease to be met at some point during vm execution (e.g. due to a vm label update), the + system may or may not try to eventually evict the vm from its node. When there are multiple elements, the lists of nodes corresponding to + each C(term) are intersected, i.e. all terms must be satisfied." + type: dict + node_affinity: + description: + - "Describes vm affinity scheduling rules e.g. co-locate this vm in the same node, zone, etc. as some other vms" + type: dict + suboptions: + soft: + description: + - "The scheduler will prefer to schedule vms to nodes that satisfy the affinity expressions specified by this field, but it may choose + a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. + for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), + compute a sum by iterating through the elements of this field and adding C(weight) to the sum if the node matches the corresponding + match_expressions; the nodes with the highest sum are the most preferred." + type: dict + hard: + description: + - "If the affinity requirements specified by this field are not met at scheduling time, the vm will not be scheduled onto the node. If + the affinity requirements specified by this field cease to be met at some point during vm execution (e.g. due to an update), the system + may or may not try to eventually evict the vm from its node." + type: dict + anti_affinity: + description: + - "Describes vm anti-affinity scheduling rules e.g. avoid putting this vm in the same node, zone, etc. as some other vms." + type: dict + suboptions: + soft: + description: + - "The scheduler will prefer to schedule vms to nodes that satisfy the anti-affinity expressions specified by this field, but it may + choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, + i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, + etc.), compute a sum by iterating through the elements of this field and adding C(weight) to the sum if the node has vms which matches + the corresponding C(term); the nodes with the highest sum are the most preferred." + type: dict + hard: + description: + - "If the anti-affinity requirements specified by this field are not met at scheduling time, the vm will not be scheduled onto the node. + If the anti-affinity requirements specified by this field cease to be met at some point during vm execution (e.g. due to a vm label + update), the system may or may not try to eventually evict the vm from its node. When there are multiple elements, the lists of nodes + corresponding to each C(term) are intersected, i.e. all terms must be satisfied." + type: dict +''' diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/inventory/kubevirt.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/inventory/kubevirt.py new file mode 100644 index 00000000..b2d06468 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/inventory/kubevirt.py @@ -0,0 +1,256 @@ +# Copyright (c) 2018 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) + +__metaclass__ = type + +DOCUMENTATION = ''' + name: kubevirt + plugin_type: inventory + author: + - KubeVirt Team (@kubevirt) + + short_description: KubeVirt inventory source + extends_documentation_fragment: + - inventory_cache + - constructed + description: + - Fetch running VirtualMachines for one or more namespaces. + - Groups by namespace, namespace_vms and labels. + - Uses kubevirt.(yml|yaml) YAML configuration file to set parameter values. + + options: + plugin: + description: token that ensures this is a source file for the 'kubevirt' plugin. + required: True + choices: ['kubevirt', 'community.general.kubevirt', 'community.kubevirt.kubevirt'] + type: str + host_format: + description: + - Specify the format of the host in the inventory group. + default: "{namespace}-{name}-{uid}" + connections: + type: list + description: + - Optional list of cluster connection settings. If no connections are provided, the default + I(~/.kube/config) and active context will be used, and objects will be returned for all namespaces + the active user is authorized to access. + suboptions: + name: + description: + - Optional name to assign to the cluster. If not provided, a name is constructed from the server + and port. + type: str + kubeconfig: + description: + - Path to an existing Kubernetes config file. If not provided, and no other connection + options are provided, the OpenShift client will attempt to load the default + configuration file from I(~/.kube/config.json). Can also be specified via K8S_AUTH_KUBECONFIG + environment variable. + type: str + context: + description: + - The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment + variable. + type: str + host: + description: + - Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable. + type: str + api_key: + description: + - Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment + variable. + type: str + username: + description: + - Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME + environment variable. + type: str + password: + description: + - Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD + environment variable. + type: str + cert_file: + description: + - Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE + environment variable. + type: str + key_file: + description: + - Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_HOST + environment variable. + type: str + ssl_ca_cert: + description: + - Path to a CA certificate used to authenticate with the API. Can also be specified via + K8S_AUTH_SSL_CA_CERT environment variable. + type: str + verify_ssl: + description: + - "Whether or not to verify the API server's SSL certificates. Can also be specified via + K8S_AUTH_VERIFY_SSL environment variable." + type: bool + namespaces: + description: + - List of namespaces. If not specified, will fetch all virtual machines for all namespaces user is authorized + to access. + type: list + network_name: + description: + - In case of multiple network attached to virtual machine, define which interface should be returned as primary IP + address. + type: str + aliases: [ interface_name ] + api_version: + description: + - "Specify the KubeVirt API version." + type: str + annotation_variable: + description: + - "Specify the name of the annotation which provides data, which should be used as inventory host variables." + - "Note, that the value in ansible annotations should be json." + type: str + default: 'ansible' + requirements: + - "openshift >= 0.6" + - "PyYAML >= 3.11" +''' + +EXAMPLES = ''' +# File must be named kubevirt.yaml or kubevirt.yml + +# Authenticate with token, and return all virtual machines for all namespaces +plugin: community.kubevirt.kubevirt +connections: + - host: https://kubevirt.io + token: xxxxxxxxxxxxxxxx + ssl_verify: false + +# Use default config (~/.kube/config) file and active context, and return vms with interfaces +# connected to network myovsnetwork and from namespace vms +plugin: community.kubevirt.kubevirt +connections: + - namespaces: + - vms + network_name: myovsnetwork +''' + +import json + +from ansible_collections.community.kubernetes.plugins.inventory.k8s import K8sInventoryException, InventoryModule as K8sInventoryModule, format_dynamic_api_exc + +try: + from openshift.dynamic.exceptions import DynamicApiError +except ImportError: + pass + + +API_VERSION = 'kubevirt.io/v1alpha3' + + +class InventoryModule(K8sInventoryModule): + NAME = 'community.kubevirt.kubevirt' + + def setup(self, config_data, cache, cache_key): + self.config_data = config_data + super(InventoryModule, self).setup(config_data, cache, cache_key) + + def fetch_objects(self, connections): + client = self.get_api_client() + vm_format = self.config_data.get('host_format', '{namespace}-{name}-{uid}') + + if connections: + for connection in connections: + client = self.get_api_client(**connection) + name = connection.get('name', self.get_default_host_name(client.configuration.host)) + if connection.get('namespaces'): + namespaces = connection['namespaces'] + else: + namespaces = self.get_available_namespaces(client) + interface_name = connection.get('network_name') + api_version = connection.get('api_version', API_VERSION) + annotation_variable = connection.get('annotation_variable', 'ansible') + for namespace in namespaces: + self.get_vms_for_namespace(client, name, namespace, vm_format, interface_name, api_version, annotation_variable) + else: + name = self.get_default_host_name(client.configuration.host) + namespaces = self.get_available_namespaces(client) + for namespace in namespaces: + self.get_vms_for_namespace(client, name, namespace, vm_format, None, api_version, annotation_variable) + + def get_vms_for_namespace(self, client, name, namespace, name_format, interface_name=None, api_version=None, annotation_variable=None): + v1_vm = client.resources.get(api_version=api_version, kind='VirtualMachineInstance') + try: + obj = v1_vm.get(namespace=namespace) + except DynamicApiError as exc: + self.display.debug(exc) + raise K8sInventoryException('Error fetching Virtual Machines list: %s' % format_dynamic_api_exc(exc)) + + namespace_group = 'namespace_{0}'.format(namespace) + namespace_vms_group = '{0}_vms'.format(namespace_group) + + name = self._sanitize_group_name(name) + namespace_group = self._sanitize_group_name(namespace_group) + namespace_vms_group = self._sanitize_group_name(namespace_vms_group) + self.inventory.add_group(name) + self.inventory.add_group(namespace_group) + self.inventory.add_child(name, namespace_group) + self.inventory.add_group(namespace_vms_group) + self.inventory.add_child(namespace_group, namespace_vms_group) + for vm in obj.items: + if not (vm.status and vm.status.interfaces): + continue + + # Find interface by its name: + if interface_name is None: + interface = vm.status.interfaces[0] + else: + interface = next( + (i for i in vm.status.interfaces if i.name == interface_name), + None + ) + + # If interface is not found or IP address is not reported skip this VM: + if interface is None or interface.ipAddress is None: + continue + + vm_name = name_format.format(namespace=vm.metadata.namespace, name=vm.metadata.name, uid=vm.metadata.uid) + vm_ip = interface.ipAddress + vm_annotations = {} if not vm.metadata.annotations else dict(vm.metadata.annotations) + + self.inventory.add_host(vm_name) + + if vm.metadata.labels: + # create a group for each label_value + for key, value in vm.metadata.labels: + group_name = 'label_{0}_{1}'.format(key, value) + group_name = self._sanitize_group_name(group_name) + self.inventory.add_group(group_name) + self.inventory.add_child(group_name, vm_name) + vm_labels = dict(vm.metadata.labels) + else: + vm_labels = {} + + self.inventory.add_child(namespace_vms_group, vm_name) + + # add hostvars + self.inventory.set_variable(vm_name, 'ansible_host', vm_ip) + self.inventory.set_variable(vm_name, 'labels', vm_labels) + self.inventory.set_variable(vm_name, 'annotations', vm_annotations) + self.inventory.set_variable(vm_name, 'object_type', 'vm') + self.inventory.set_variable(vm_name, 'resource_version', vm.metadata.resourceVersion) + self.inventory.set_variable(vm_name, 'uid', vm.metadata.uid) + + # Add all variables which are listed in 'ansible' annotation: + annotations_data = json.loads(vm_annotations.get(annotation_variable, "{}")) + for k, v in annotations_data.items(): + self.inventory.set_variable(vm_name, k, v) + + def verify_file(self, path): + if super(InventoryModule, self).verify_file(path): + if path.endswith(('kubevirt.yml', 'kubevirt.yaml')): + return True + return False diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/module_utils/kubevirt.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/module_utils/kubevirt.py new file mode 100644 index 00000000..e59e477a --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/module_utils/kubevirt.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# + +# Copyright (c) 2018, KubeVirt Team <@kubevirt> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +from collections import defaultdict +from distutils.version import Version + +from ansible.module_utils.common import dict_transformations +from ansible.module_utils.common._collections_compat import Sequence +from ansible_collections.community.kubernetes.plugins.module_utils.common import list_dict_str +from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule + +import copy +import re + +MAX_SUPPORTED_API_VERSION = 'v1alpha3' +API_GROUP = 'kubevirt.io' + + +# Put all args that (can) modify 'spec:' here: +VM_SPEC_DEF_ARG_SPEC = { + 'resource_definition': { + 'type': 'dict', + 'aliases': ['definition', 'inline'] + }, + 'memory': {'type': 'str'}, + 'memory_limit': {'type': 'str'}, + 'cpu_cores': {'type': 'int'}, + 'disks': {'type': 'list'}, + 'labels': {'type': 'dict'}, + 'interfaces': {'type': 'list'}, + 'machine_type': {'type': 'str'}, + 'cloud_init_nocloud': {'type': 'dict'}, + 'bootloader': {'type': 'str'}, + 'smbios_uuid': {'type': 'str'}, + 'cpu_model': {'type': 'str'}, + 'headless': {'type': 'str'}, + 'hugepage_size': {'type': 'str'}, + 'tablets': {'type': 'list'}, + 'cpu_limit': {'type': 'int'}, + 'cpu_shares': {'type': 'int'}, + 'cpu_features': {'type': 'list'}, + 'affinity': {'type': 'dict'}, + 'anti_affinity': {'type': 'dict'}, + 'node_affinity': {'type': 'dict'}, +} +# And other common args go here: +VM_COMMON_ARG_SPEC = { + 'name': {'required': True}, + 'namespace': {'required': True}, + 'hostname': {'type': 'str'}, + 'subdomain': {'type': 'str'}, + 'state': { + 'default': 'present', + 'choices': ['present', 'absent'], + }, + 'force': { + 'type': 'bool', + 'default': False, + }, + 'merge_type': {'type': 'list', 'choices': ['json', 'merge', 'strategic-merge']}, + 'wait': {'type': 'bool', 'default': True}, + 'wait_timeout': {'type': 'int', 'default': 120}, + 'wait_sleep': {'type': 'int', 'default': 5}, +} +VM_COMMON_ARG_SPEC.update(VM_SPEC_DEF_ARG_SPEC) + + +def virtdict(): + """ + This function create dictionary, with defaults to dictionary. + """ + return defaultdict(virtdict) + + +class KubeAPIVersion(Version): + component_re = re.compile(r'(\d+ | [a-z]+)', re.VERBOSE) + + def __init__(self, vstring=None): + if vstring: + self.parse(vstring) + + def parse(self, vstring): + self.vstring = vstring + components = [x for x in self.component_re.split(vstring) if x] + for i, obj in enumerate(components): + try: + components[i] = int(obj) + except ValueError: + pass + + errmsg = "version '{0}' does not conform to kubernetes api versioning guidelines".format(vstring) + c = components + + if len(c) not in (2, 4) or c[0] != 'v' or not isinstance(c[1], int): + raise ValueError(errmsg) + if len(c) == 4 and (c[2] not in ('alpha', 'beta') or not isinstance(c[3], int)): + raise ValueError(errmsg) + + self.version = components + + def __str__(self): + return self.vstring + + def __repr__(self): + return "KubeAPIVersion ('{0}')".format(str(self)) + + def _cmp(self, other): + if isinstance(other, str): + other = KubeAPIVersion(other) + + myver = self.version + otherver = other.version + + for ver in myver, otherver: + if len(ver) == 2: + ver.extend(['zeta', 9999]) + + if myver == otherver: + return 0 + if myver < otherver: + return -1 + if myver > otherver: + return 1 + + # python2 compatibility + def __cmp__(self, other): + return self._cmp(other) + + +class KubeVirtRawModule(KubernetesRawModule): + def __init__(self, *args, **kwargs): + super(KubeVirtRawModule, self).__init__(*args, **kwargs) + + @staticmethod + def merge_dicts(base_dict, merging_dicts): + """This function merges a base dictionary with one or more other dictionaries. + The base dictionary takes precedence when there is a key collision. + merging_dicts can be a dict or a list or tuple of dicts. In the latter case, the + dictionaries at the front of the list have higher precedence over the ones at the end. + """ + if not merging_dicts: + merging_dicts = ({},) + + if not isinstance(merging_dicts, Sequence): + merging_dicts = (merging_dicts,) + + new_dict = {} + for d in reversed(merging_dicts): + new_dict = dict_transformations.dict_merge(new_dict, d) + + new_dict = dict_transformations.dict_merge(new_dict, base_dict) + + return new_dict + + def get_resource(self, resource): + try: + existing = resource.get(name=self.name, namespace=self.namespace) + except Exception: + existing = None + + return existing + + def _define_datavolumes(self, datavolumes, spec): + """ + Takes datavoulmes parameter of Ansible and create kubevirt API datavolumesTemplateSpec + structure from it + """ + if not datavolumes: + return + + spec['dataVolumeTemplates'] = [] + for dv in datavolumes: + # Add datavolume to datavolumetemplates spec: + dvt = virtdict() + dvt['metadata']['name'] = dv.get('name') + dvt['spec']['pvc'] = { + 'accessModes': dv.get('pvc').get('accessModes'), + 'resources': { + 'requests': { + 'storage': dv.get('pvc').get('storage'), + } + } + } + dvt['spec']['source'] = dv.get('source') + spec['dataVolumeTemplates'].append(dvt) + + # Add datavolume to disks spec: + if not spec['template']['spec']['domain']['devices']['disks']: + spec['template']['spec']['domain']['devices']['disks'] = [] + + spec['template']['spec']['domain']['devices']['disks'].append( + { + 'name': dv.get('name'), + 'disk': dv.get('disk', {'bus': 'virtio'}), + } + ) + + # Add datavolume to volumes spec: + if not spec['template']['spec']['volumes']: + spec['template']['spec']['volumes'] = [] + + spec['template']['spec']['volumes'].append( + { + 'dataVolume': { + 'name': dv.get('name') + }, + 'name': dv.get('name'), + } + ) + + def _define_cloud_init(self, cloud_init_nocloud, template_spec): + """ + Takes the user's cloud_init_nocloud parameter and fill it in kubevirt + API strucuture. The name for disk is hardcoded to ansiblecloudinitdisk. + """ + if cloud_init_nocloud: + if not template_spec['volumes']: + template_spec['volumes'] = [] + if not template_spec['domain']['devices']['disks']: + template_spec['domain']['devices']['disks'] = [] + + template_spec['volumes'].append({'name': 'ansiblecloudinitdisk', 'cloudInitNoCloud': cloud_init_nocloud}) + template_spec['domain']['devices']['disks'].append({ + 'name': 'ansiblecloudinitdisk', + 'disk': {'bus': 'virtio'}, + }) + + def _define_interfaces(self, interfaces, template_spec, defaults): + """ + Takes interfaces parameter of Ansible and create kubevirt API interfaces + and networks strucutre out from it. + """ + if not interfaces and defaults and 'interfaces' in defaults: + interfaces = copy.deepcopy(defaults['interfaces']) + for d in interfaces: + d['network'] = defaults['networks'][0] + + if interfaces: + # Extract interfaces k8s specification from interfaces list passed to Ansible: + spec_interfaces = [] + for i in interfaces: + spec_interfaces.append( + self.merge_dicts(dict((k, v) for k, v in i.items() if k != 'network'), defaults['interfaces']) + ) + if 'interfaces' not in template_spec['domain']['devices']: + template_spec['domain']['devices']['interfaces'] = [] + template_spec['domain']['devices']['interfaces'].extend(spec_interfaces) + + # Extract networks k8s specification from interfaces list passed to Ansible: + spec_networks = [] + for i in interfaces: + net = i['network'] + net['name'] = i['name'] + spec_networks.append(self.merge_dicts(net, defaults['networks'])) + if 'networks' not in template_spec: + template_spec['networks'] = [] + template_spec['networks'].extend(spec_networks) + + def _define_disks(self, disks, template_spec, defaults): + """ + Takes disks parameter of Ansible and create kubevirt API disks and + volumes strucutre out from it. + """ + if not disks and defaults and 'disks' in defaults: + disks = copy.deepcopy(defaults['disks']) + for d in disks: + d['volume'] = defaults['volumes'][0] + + if disks: + # Extract k8s specification from disks list passed to Ansible: + spec_disks = [] + for d in disks: + spec_disks.append( + self.merge_dicts(dict((k, v) for k, v in d.items() if k != 'volume'), defaults['disks']) + ) + if 'disks' not in template_spec['domain']['devices']: + template_spec['domain']['devices']['disks'] = [] + template_spec['domain']['devices']['disks'].extend(spec_disks) + + # Extract volumes k8s specification from disks list passed to Ansible: + spec_volumes = [] + for d in disks: + volume = d['volume'] + volume['name'] = d['name'] + spec_volumes.append(self.merge_dicts(volume, defaults['volumes'])) + if 'volumes' not in template_spec: + template_spec['volumes'] = [] + template_spec['volumes'].extend(spec_volumes) + + def find_supported_resource(self, kind): + results = self.client.resources.search(kind=kind, group=API_GROUP) + if not results: + self.fail('Failed to find resource {0} in {1}'.format(kind, API_GROUP)) + sr = sorted(results, key=lambda r: KubeAPIVersion(r.api_version), reverse=True) + for r in sr: + if KubeAPIVersion(r.api_version) <= KubeAPIVersion(MAX_SUPPORTED_API_VERSION): + return r + self.fail("API versions {0} are too recent. Max supported is {1}/{2}.".format( + str([r.api_version for r in sr]), API_GROUP, MAX_SUPPORTED_API_VERSION)) + + def _construct_vm_definition(self, kind, definition, template, params, defaults=None): + self.client = self.get_api_client() + + disks = params.get('disks', []) + memory = params.get('memory') + memory_limit = params.get('memory_limit') + cpu_cores = params.get('cpu_cores') + cpu_model = params.get('cpu_model') + cpu_features = params.get('cpu_features') + labels = params.get('labels') + datavolumes = params.get('datavolumes') + interfaces = params.get('interfaces') + bootloader = params.get('bootloader') + cloud_init_nocloud = params.get('cloud_init_nocloud') + machine_type = params.get('machine_type') + headless = params.get('headless') + smbios_uuid = params.get('smbios_uuid') + hugepage_size = params.get('hugepage_size') + tablets = params.get('tablets') + cpu_shares = params.get('cpu_shares') + cpu_limit = params.get('cpu_limit') + node_affinity = params.get('node_affinity') + vm_affinity = params.get('affinity') + vm_anti_affinity = params.get('anti_affinity') + hostname = params.get('hostname') + subdomain = params.get('subdomain') + template_spec = template['spec'] + + # Merge additional flat parameters: + if memory: + template_spec['domain']['resources']['requests']['memory'] = memory + + if cpu_shares: + template_spec['domain']['resources']['requests']['cpu'] = cpu_shares + + if cpu_limit: + template_spec['domain']['resources']['limits']['cpu'] = cpu_limit + + if tablets: + for tablet in tablets: + tablet['type'] = 'tablet' + template_spec['domain']['devices']['inputs'] = tablets + + if memory_limit: + template_spec['domain']['resources']['limits']['memory'] = memory_limit + + if hugepage_size is not None: + template_spec['domain']['memory']['hugepages']['pageSize'] = hugepage_size + + if cpu_features is not None: + template_spec['domain']['cpu']['features'] = cpu_features + + if cpu_cores is not None: + template_spec['domain']['cpu']['cores'] = cpu_cores + + if cpu_model: + template_spec['domain']['cpu']['model'] = cpu_model + + if labels: + template['metadata']['labels'] = self.merge_dicts(labels, template['metadata']['labels']) + + if machine_type: + template_spec['domain']['machine']['type'] = machine_type + + if bootloader: + template_spec['domain']['firmware']['bootloader'] = {bootloader: {}} + + if smbios_uuid: + template_spec['domain']['firmware']['uuid'] = smbios_uuid + + if headless is not None: + template_spec['domain']['devices']['autoattachGraphicsDevice'] = not headless + + if vm_affinity or vm_anti_affinity: + vms_affinity = vm_affinity or vm_anti_affinity + affinity_name = 'podAffinity' if vm_affinity else 'podAntiAffinity' + for affinity in vms_affinity.get('soft', []): + if not template_spec['affinity'][affinity_name]['preferredDuringSchedulingIgnoredDuringExecution']: + template_spec['affinity'][affinity_name]['preferredDuringSchedulingIgnoredDuringExecution'] = [] + template_spec['affinity'][affinity_name]['preferredDuringSchedulingIgnoredDuringExecution'].append({ + 'weight': affinity.get('weight'), + 'podAffinityTerm': { + 'labelSelector': { + 'matchExpressions': affinity.get('term').get('match_expressions'), + }, + 'topologyKey': affinity.get('topology_key'), + }, + }) + for affinity in vms_affinity.get('hard', []): + if not template_spec['affinity'][affinity_name]['requiredDuringSchedulingIgnoredDuringExecution']: + template_spec['affinity'][affinity_name]['requiredDuringSchedulingIgnoredDuringExecution'] = [] + template_spec['affinity'][affinity_name]['requiredDuringSchedulingIgnoredDuringExecution'].append({ + 'labelSelector': { + 'matchExpressions': affinity.get('term').get('match_expressions'), + }, + 'topologyKey': affinity.get('topology_key'), + }) + + if node_affinity: + for affinity in node_affinity.get('soft', []): + if not template_spec['affinity']['nodeAffinity']['preferredDuringSchedulingIgnoredDuringExecution']: + template_spec['affinity']['nodeAffinity']['preferredDuringSchedulingIgnoredDuringExecution'] = [] + template_spec['affinity']['nodeAffinity']['preferredDuringSchedulingIgnoredDuringExecution'].append({ + 'weight': affinity.get('weight'), + 'preference': { + 'matchExpressions': affinity.get('term').get('match_expressions'), + } + }) + for affinity in node_affinity.get('hard', []): + if not template_spec['affinity']['nodeAffinity']['requiredDuringSchedulingIgnoredDuringExecution']['nodeSelectorTerms']: + template_spec['affinity']['nodeAffinity']['requiredDuringSchedulingIgnoredDuringExecution']['nodeSelectorTerms'] = [] + template_spec['affinity']['nodeAffinity']['requiredDuringSchedulingIgnoredDuringExecution']['nodeSelectorTerms'].append({ + 'matchExpressions': affinity.get('term').get('match_expressions'), + }) + + if hostname: + template_spec['hostname'] = hostname + + if subdomain: + template_spec['subdomain'] = subdomain + + # Define disks + self._define_disks(disks, template_spec, defaults) + + # Define cloud init disk if defined: + # Note, that this must be called after _define_disks, so the cloud_init + # is not first in order and it's not used as boot disk: + self._define_cloud_init(cloud_init_nocloud, template_spec) + + # Define interfaces: + self._define_interfaces(interfaces, template_spec, defaults) + + # Define datavolumes: + self._define_datavolumes(datavolumes, definition['spec']) + + return self.merge_dicts(definition, self.resource_definitions[0]) + + def construct_vm_definition(self, kind, definition, template, defaults=None): + definition = self._construct_vm_definition(kind, definition, template, self.params, defaults) + resource = self.find_supported_resource(kind) + definition = self.set_defaults(resource, definition) + return resource, definition + + def construct_vm_template_definition(self, kind, definition, template, params): + definition = self._construct_vm_definition(kind, definition, template, params) + resource = self.find_resource(kind, definition['apiVersion'], fail=True) + + # Set defaults: + definition['kind'] = kind + definition['metadata']['name'] = params.get('name') + definition['metadata']['namespace'] = params.get('namespace') + + return resource, definition + + def execute_crud(self, kind, definition): + """ Module execution """ + resource = self.find_supported_resource(kind) + definition = self.set_defaults(resource, definition) + return self.perform_action(resource, definition) diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_cdi_upload.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_cdi_upload.py new file mode 100644 index 00000000..dfcf707e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_cdi_upload.py @@ -0,0 +1,184 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = ''' + +module: kubevirt_cdi_upload + +short_description: Upload local VM images to CDI Upload Proxy. + + +author: KubeVirt Team (@kubevirt) + + +description: + - Use Openshift Python SDK to create UploadTokenRequest objects. + - Transfer contents of local files to the CDI Upload Proxy. + +options: + pvc_name: + description: + - Use to specify the name of the target PersistentVolumeClaim. + required: true + pvc_namespace: + description: + - Use to specify the namespace of the target PersistentVolumeClaim. + required: true + upload_host: + description: + - URL containing the host and port on which the CDI Upload Proxy is available. + - "More info: U(https://github.com/kubevirt/containerized-data-importer/blob/master/doc/upload.md#expose-cdi-uploadproxy-service)" + upload_host_validate_certs: + description: + - Whether or not to verify the CDI Upload Proxy's SSL certificates against your system's CA trust store. + default: true + type: bool + aliases: [ upload_host_verify_ssl ] + path: + description: + - Path of local image file to transfer. + merge_type: + description: + - Whether to override the default patch merge approach with a specific type. By default, the strategic + merge will typically be used. + type: list + choices: [ json, merge, strategic-merge ] + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 + - requests >= 2.0.0 +''' + +EXAMPLES = ''' +- name: Upload local image to pvc-vm1 + community.kubevirt.kubevirt_cdi_upload: + pvc_namespace: default + pvc_name: pvc-vm1 + upload_host: https://localhost:8443 + upload_host_validate_certs: false + path: /tmp/cirros-0.4.0-x86_64-disk.img +''' + +RETURN = '''# ''' + +import copy +import traceback + +from collections import defaultdict + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC +from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule + +# 3rd party imports +try: + import requests + HAS_REQUESTS = True +except ImportError: + HAS_REQUESTS = False + + +SERVICE_ARG_SPEC = { + 'pvc_name': {'required': True}, + 'pvc_namespace': {'required': True}, + 'upload_host': {'required': True}, + 'upload_host_validate_certs': { + 'type': 'bool', + 'default': True, + 'aliases': ['upload_host_verify_ssl'] + }, + 'path': {'required': True}, + 'merge_type': { + 'type': 'list', + 'choices': ['json', 'merge', 'strategic-merge'] + }, +} + + +class KubeVirtCDIUpload(KubernetesRawModule): + def __init__(self, *args, **kwargs): + super(KubeVirtCDIUpload, self).__init__(*args, k8s_kind='UploadTokenRequest', **kwargs) + + if not HAS_REQUESTS: + self.fail("This module requires the python 'requests' package. Try `pip install requests`.") + + @property + def argspec(self): + """ argspec property builder """ + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(SERVICE_ARG_SPEC) + return argument_spec + + def execute_module(self): + """ Module execution """ + + API = 'v1alpha1' + KIND = 'UploadTokenRequest' + + self.client = self.get_api_client() + + api_version = 'upload.cdi.kubevirt.io/{0}'.format(API) + pvc_name = self.params.get('pvc_name') + pvc_namespace = self.params.get('pvc_namespace') + upload_host = self.params.get('upload_host') + upload_host_verify_ssl = self.params.get('upload_host_validate_certs') + path = self.params.get('path') + + definition = defaultdict(defaultdict) + + definition['kind'] = KIND + definition['apiVersion'] = api_version + + def_meta = definition['metadata'] + def_meta['name'] = pvc_name + def_meta['namespace'] = pvc_namespace + + def_spec = definition['spec'] + def_spec['pvcName'] = pvc_name + + # Let's check the file's there before we do anything else + imgfile = open(path, 'rb') + + resource = self.find_resource(KIND, api_version, fail=True) + definition = self.set_defaults(resource, definition) + result = self.perform_action(resource, definition) + + headers = {'Authorization': "Bearer {0}".format(result['result']['status']['token'])} + url = "{0}/{1}/upload".format(upload_host, API) + ret = requests.post(url, data=imgfile, headers=headers, verify=upload_host_verify_ssl) + + if ret.status_code != 200: + self.fail_request("Something went wrong while uploading data", method='POST', url=url, + reason=ret.reason, status_code=ret.status_code) + + self.exit_json(changed=True) + + def fail_request(self, msg, **kwargs): + req_info = {} + for k, v in kwargs.items(): + req_info['req_' + k] = v + self.fail_json(msg=msg, **req_info) + + +def main(): + module = KubeVirtCDIUpload() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_preset.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_preset.py new file mode 100644 index 00000000..ab6063c0 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_preset.py @@ -0,0 +1,154 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +DOCUMENTATION = ''' +--- +module: kubevirt_preset + +short_description: Manage KubeVirt virtual machine presets + +description: + - Use Openshift Python SDK to manage the state of KubeVirt virtual machine presets. + + +author: KubeVirt Team (@kubevirt) + +options: + state: + description: + - Create or delete virtual machine presets. + default: "present" + choices: + - present + - absent + type: str + name: + description: + - Name of the virtual machine preset. + required: true + type: str + namespace: + description: + - Namespace where the virtual machine preset exists. + required: true + type: str + selector: + description: + - "Selector is a label query over a set of virtual machine preset." + type: dict + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options +- community.kubevirt.kubevirt_vm_options +- community.kubevirt.kubevirt_common_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +''' + +EXAMPLES = ''' +- name: Create virtual machine preset 'vmi-preset-small' + community.kubevirt.kubevirt_preset: + state: present + name: vmi-preset-small + namespace: vms + memory: 64M + selector: + matchLabels: + kubevirt.io/vmPreset: vmi-preset-small + +- name: Remove virtual machine preset 'vmi-preset-small' + community.kubevirt.kubevirt_preset: + state: absent + name: vmi-preset-small + namespace: vms +''' + +RETURN = ''' +kubevirt_preset: + description: + - The virtual machine preset managed by the user. + - "This dictionary contains all values returned by the KubeVirt API all options + are described here U(https://kubevirt.io/api-reference/master/definitions.html#_v1_virtualmachineinstancepreset)" + returned: success + type: complex + contains: {} +''' + +import copy +import traceback + + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC + +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import ( + virtdict, + KubeVirtRawModule, + VM_COMMON_ARG_SPEC +) + + +KIND = 'VirtualMachineInstancePreset' +VMP_ARG_SPEC = { + 'selector': {'type': 'dict'}, +} + + +class KubeVirtVMPreset(KubeVirtRawModule): + + @property + def argspec(self): + """ argspec property builder """ + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(VM_COMMON_ARG_SPEC) + argument_spec.update(VMP_ARG_SPEC) + return argument_spec + + def execute_module(self): + # Parse parameters specific for this module: + definition = virtdict() + selector = self.params.get('selector') + + if selector: + definition['spec']['selector'] = selector + + # FIXME: Devices must be set, but we don't yet support any + # attributes there, remove when we do: + definition['spec']['domain']['devices'] = dict() + + # defaults for template + defaults = {'disks': [], 'volumes': [], 'interfaces': [], 'networks': []} + + # Execute the CURD of VM: + dummy, definition = self.construct_vm_definition(KIND, definition, definition, defaults) + result_crud = self.execute_crud(KIND, definition) + changed = result_crud['changed'] + result = result_crud.pop('result') + + # Return from the module: + self.exit_json(**{ + 'changed': changed, + 'kubevirt_preset': result, + 'result': result_crud, + }) + + +def main(): + module = KubeVirtVMPreset() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_pvc.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_pvc.py new file mode 100644 index 00000000..e21d05b8 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_pvc.py @@ -0,0 +1,457 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + + +DOCUMENTATION = ''' + +module: kubevirt_pvc + +short_description: Manage PVCs on Kubernetes + + +author: KubeVirt Team (@kubevirt) + +description: + - Use Openshift Python SDK to manage PVCs on Kubernetes + - Support Containerized Data Importer out of the box + +options: + resource_definition: + description: + - "A partial YAML definition of the PVC object being created/updated. Here you can define Kubernetes + PVC Resource parameters not covered by this module's parameters." + - "NOTE: I(resource_definition) has lower priority than module parameters. If you try to define e.g. + I(metadata.namespace) here, that value will be ignored and I(namespace) used instead." + aliases: + - definition + - inline + type: dict + state: + description: + - "Determines if an object should be created, patched, or deleted. When set to C(present), an object will be + created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to + C(present), an existing object will be patched, if its attributes differ from those specified using + module options and I(resource_definition)." + default: present + choices: + - present + - absent + force: + description: + - If set to C(True), and I(state) is C(present), an existing object will be replaced. + default: false + type: bool + merge_type: + description: + - Whether to override the default patch merge approach with a specific type. + - "This defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters + on resource kinds that combine Custom Resources and built-in resources." + - See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) + - If more than one merge_type is given, the merge_types will be tried in order + choices: + - json + - merge + - strategic-merge + type: list + name: + description: + - Use to specify a PVC object name. + required: true + type: str + namespace: + description: + - Use to specify a PVC object namespace. + required: true + type: str + annotations: + description: + - Annotations attached to this object. + - U(https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/) + type: dict + labels: + description: + - Labels attached to this object. + - U(https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) + type: dict + selector: + description: + - A label query over volumes to consider for binding. + - U(https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) + type: dict + access_modes: + description: + - Contains the desired access modes the volume should have. + - "More info: U(https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes)" + type: list + size: + description: + - How much storage to allocate to the PVC. + type: str + aliases: + - storage + storage_class_name: + description: + - Name of the StorageClass required by the claim. + - "More info: U(https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1)" + type: str + volume_mode: + description: + - "This defines what type of volume is required by the claim. Value of Filesystem is implied when not + included in claim spec. This is an alpha feature of kubernetes and may change in the future." + type: str + volume_name: + description: + - This is the binding reference to the PersistentVolume backing this claim. + type: str + cdi_source: + description: + - "If data is to be copied onto the PVC using the Containerized Data Importer you can specify the source of + the data (along with any additional configuration) as well as it's format." + - "Valid source types are: blank, http, s3, registry, pvc and upload. The last one requires using the + M(community.kubevirt.kubevirt_cdi_upload) module to actually perform an upload." + - "Source data format is specified using the optional I(content_type). Valid options are C(kubevirt) + (default; raw image) and C(archive) (tar.gz)." + - "This uses the DataVolume source syntax: + U(https://github.com/kubevirt/containerized-data-importer/blob/master/doc/datavolumes.md#https3registry-source)" + type: dict + wait: + description: + - "If set, this module will wait for the PVC to become bound and CDI (if enabled) to finish its operation + before returning." + - "Used only if I(state) set to C(present)." + - "Unless used in conjunction with I(cdi_source), this might result in a timeout, as clusters may be configured + to not bind PVCs until first usage." + default: false + type: bool + wait_timeout: + description: + - Specifies how much time in seconds to wait for PVC creation to complete if I(wait) option is enabled. + - Default value is reasonably high due to an expectation that CDI might take a while to finish its operation. + type: int + default: 300 + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +''' + +EXAMPLES = ''' +- name: Create a PVC and import data from an external source + community.kubevirt.kubevirt_pvc: + name: pvc1 + namespace: default + size: 100Mi + access_modes: + - ReadWriteOnce + cdi_source: + http: + url: https://www.source.example/path/of/data/vm.img + # If the URL points to a tar.gz containing the disk image, uncomment the line below: + #content_type: archive + +- name: Create a PVC as a clone from a different PVC + community.kubevirt.kubevirt_pvc: + name: pvc2 + namespace: default + size: 100Mi + access_modes: + - ReadWriteOnce + cdi_source: + pvc: + namespace: source-ns + name: source-pvc + +- name: Create a PVC ready for data upload + community.kubevirt.kubevirt_pvc: + name: pvc3 + namespace: default + size: 100Mi + access_modes: + - ReadWriteOnce + cdi_source: + upload: yes + # You need the kubevirt_cdi_upload module to actually upload something + +- name: Create a PVC with a blank raw image + community.kubevirt.kubevirt_pvc: + name: pvc4 + namespace: default + size: 100Mi + access_modes: + - ReadWriteOnce + cdi_source: + blank: yes + +- name: Create a PVC and fill it with data from a container + community.kubevirt.kubevirt_pvc: + name: pvc5 + namespace: default + size: 100Mi + access_modes: + - ReadWriteOnce + cdi_source: + registry: + url: "docker://kubevirt/fedora-cloud-registry-disk-demo" + +''' + +RETURN = ''' +result: + description: + - The created, patched, or otherwise present object. Will be empty in the case of a deletion. + returned: success + type: complex + contains: + api_version: + description: The versioned schema of this representation of an object. + returned: success + type: str + kind: + description: Represents the REST resource this object represents. + returned: success + type: str + metadata: + description: Standard object metadata. Includes name, namespace, annotations, labels, etc. + returned: success + type: complex + spec: + description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind). + returned: success + type: complex + status: + description: Current status details for the object. + returned: success + type: complex + items: + description: Returned only when multiple yaml documents are passed to src or resource_definition + returned: when resource_definition or src contains list of objects + type: list + duration: + description: elapsed time of task in seconds + returned: when C(wait) is true + type: int + sample: 48 +''' + + +import copy +import traceback + +from collections import defaultdict + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC +from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import virtdict, KubeVirtRawModule + + +PVC_ARG_SPEC = { + 'name': {'required': True}, + 'namespace': {'required': True}, + 'state': { + 'type': 'str', + 'choices': [ + 'present', 'absent' + ], + 'default': 'present' + }, + 'force': { + 'type': 'bool', + 'default': False, + }, + 'merge_type': { + 'type': 'list', + 'choices': ['json', 'merge', 'strategic-merge'] + }, + 'resource_definition': { + 'type': 'dict', + 'aliases': ['definition', 'inline'] + }, + 'labels': {'type': 'dict'}, + 'annotations': {'type': 'dict'}, + 'selector': {'type': 'dict'}, + 'access_modes': {'type': 'list'}, + 'size': { + 'type': 'str', + 'aliases': ['storage'] + }, + 'storage_class_name': {'type': 'str'}, + 'volume_mode': {'type': 'str'}, + 'volume_name': {'type': 'str'}, + 'cdi_source': {'type': 'dict'}, + 'wait': { + 'type': 'bool', + 'default': False + }, + 'wait_timeout': { + 'type': 'int', + 'default': 300 + } +} + + +class CreatePVCFailed(Exception): + pass + + +class KubevirtPVC(KubernetesRawModule): + def __init__(self): + super(KubevirtPVC, self).__init__() + + @property + def argspec(self): + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(PVC_ARG_SPEC) + return argument_spec + + @staticmethod + def fix_serialization(obj): + if obj and hasattr(obj, 'to_dict'): + return obj.to_dict() + return obj + + def _parse_cdi_source(self, _cdi_src, metadata): + cdi_src = copy.deepcopy(_cdi_src) + annotations = metadata['annotations'] + labels = metadata['labels'] + + valid_content_types = ('kubevirt', 'archive') + valid_sources = ('http', 's3', 'pvc', 'upload', 'blank', 'registry') + + if 'content_type' in cdi_src: + content_type = cdi_src.pop('content_type') + if content_type not in valid_content_types: + raise ValueError("cdi_source.content_type must be one of {0}, not: '{1}'".format( + valid_content_types, content_type)) + annotations['cdi.kubevirt.io/storage.contentType'] = content_type + + if len(cdi_src) != 1: + raise ValueError("You must specify exactly one valid CDI source, not {0}: {1}".format(len(cdi_src), tuple(cdi_src.keys()))) + + src_type = tuple(cdi_src.keys())[0] + src_spec = cdi_src[src_type] + + if src_type not in valid_sources: + raise ValueError("Got an invalid CDI source type: '{0}', must be one of {1}".format(src_type, valid_sources)) + + # True for all cases save one + labels['app'] = 'containerized-data-importer' + + if src_type == 'upload': + annotations['cdi.kubevirt.io/storage.upload.target'] = '' + elif src_type == 'blank': + annotations['cdi.kubevirt.io/storage.import.source'] = 'none' + elif src_type == 'pvc': + if not isinstance(src_spec, dict) or sorted(src_spec.keys()) != ['name', 'namespace']: + raise ValueError("CDI Source 'pvc' requires specifying 'name' and 'namespace' (and nothing else)") + labels['app'] = 'host-assisted-cloning' + annotations['k8s.io/CloneRequest'] = '{0}/{1}'.format(src_spec['namespace'], src_spec['name']) + elif src_type in ('http', 's3', 'registry'): + if not isinstance(src_spec, dict) or 'url' not in src_spec: + raise ValueError("CDI Source '{0}' requires specifying 'url'".format(src_type)) + unknown_params = set(src_spec.keys()).difference(set(('url', 'secretRef', 'certConfigMap'))) + if unknown_params: + raise ValueError("CDI Source '{0}' does not know recognize params: {1}".format(src_type, tuple(unknown_params))) + annotations['cdi.kubevirt.io/storage.import.source'] = src_type + annotations['cdi.kubevirt.io/storage.import.endpoint'] = src_spec['url'] + if 'secretRef' in src_spec: + annotations['cdi.kubevirt.io/storage.import.secretName'] = src_spec['secretRef'] + if 'certConfigMap' in src_spec: + annotations['cdi.kubevirt.io/storage.import.certConfigMap'] = src_spec['certConfigMap'] + + def _wait_for_creation(self, resource, uid): + return_obj = None + desired_cdi_status = 'Succeeded' + use_cdi = True if self.params.get('cdi_source') else False + if use_cdi and 'upload' in self.params['cdi_source']: + desired_cdi_status = 'Running' + + for event in resource.watch(namespace=self.namespace, timeout=self.params.get('wait_timeout')): + entity = event['object'] + metadata = entity.metadata + if not hasattr(metadata, 'uid') or metadata.uid != uid: + continue + if entity.status.phase == 'Bound': + if use_cdi and hasattr(metadata, 'annotations'): + import_status = metadata.annotations.get('cdi.kubevirt.io/storage.pod.phase') + if import_status == desired_cdi_status: + return_obj = entity + break + elif import_status == 'Failed': + raise CreatePVCFailed("PVC creation incomplete; importing data failed") + else: + return_obj = entity + break + elif entity.status.phase == 'Failed': + raise CreatePVCFailed("PVC creation failed") + + if not return_obj: + raise CreatePVCFailed("PVC creation timed out") + + return self.fix_serialization(return_obj) + + def execute_module(self): + KIND = 'PersistentVolumeClaim' + API = 'v1' + + definition = virtdict() + definition['kind'] = KIND + definition['apiVersion'] = API + + metadata = definition['metadata'] + metadata['name'] = self.params.get('name') + metadata['namespace'] = self.params.get('namespace') + if self.params.get('annotations'): + metadata['annotations'] = self.params.get('annotations') + if self.params.get('labels'): + metadata['labels'] = self.params.get('labels') + if self.params.get('cdi_source'): + self._parse_cdi_source(self.params.get('cdi_source'), metadata) + + spec = definition['spec'] + if self.params.get('access_modes'): + spec['accessModes'] = self.params.get('access_modes') + if self.params.get('size'): + spec['resources']['requests']['storage'] = self.params.get('size') + if self.params.get('storage_class_name'): + spec['storageClassName'] = self.params.get('storage_class_name') + if self.params.get('selector'): + spec['selector'] = self.params.get('selector') + if self.params.get('volume_mode'): + spec['volumeMode'] = self.params.get('volume_mode') + if self.params.get('volume_name'): + spec['volumeName'] = self.params.get('volume_name') + + # 'resource_definition:' has lower priority than module parameters + definition = dict(KubeVirtRawModule.merge_dicts(definition, self.resource_definitions[0])) + + self.client = self.get_api_client() + resource = self.find_resource(KIND, API, fail=True) + definition = self.set_defaults(resource, definition) + result = self.perform_action(resource, definition) + if self.params.get('wait') and self.params.get('state') == 'present': + result['result'] = self._wait_for_creation(resource, result['result']['metadata']['uid']) + + self.exit_json(**result) + + +def main(): + module = KubevirtPVC() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_rs.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_rs.py new file mode 100644 index 00000000..1e86dbda --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_rs.py @@ -0,0 +1,211 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +DOCUMENTATION = ''' +--- +module: kubevirt_rs + +short_description: Manage KubeVirt virtual machine replica sets + +description: + - Use Openshift Python SDK to manage the state of KubeVirt virtual machine replica sets. + + +author: KubeVirt Team (@kubevirt) + +options: + state: + description: + - Create or delete virtual machine replica sets. + default: "present" + choices: + - present + - absent + type: str + name: + description: + - Name of the virtual machine replica set. + required: true + type: str + namespace: + description: + - Namespace where the virtual machine replica set exists. + required: true + type: str + selector: + description: + - "Selector is a label query over a set of virtual machine." + required: true + type: dict + replicas: + description: + - Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. + - Replicas defaults to 1 if newly created replica set. + type: int + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options +- community.kubevirt.kubevirt_vm_options +- community.kubevirt.kubevirt_common_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +''' + +EXAMPLES = ''' +- name: Create virtual machine replica set 'myvmir' + community.kubevirt.kubevirt_rs: + state: present + name: myvmir + namespace: vms + wait: true + replicas: 3 + memory: 64M + labels: + myvmi: myvmi + selector: + matchLabels: + myvmi: myvmi + disks: + - name: containerdisk + volume: + containerDisk: + image: kubevirt/cirros-container-disk-demo:latest + path: /custom-disk/cirros.img + disk: + bus: virtio + +- name: Remove virtual machine replica set 'myvmir' + community.kubevirt.kubevirt_rs: + state: absent + name: myvmir + namespace: vms + wait: true +''' + +RETURN = ''' +kubevirt_rs: + description: + - The virtual machine virtual machine replica set managed by the user. + - "This dictionary contains all values returned by the KubeVirt API all options + are described here U(https://kubevirt.io/api-reference/master/definitions.html#_v1_virtualmachineinstance)" + returned: success + type: complex + contains: {} +''' + +import copy +import traceback + + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC + +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import ( + virtdict, + KubeVirtRawModule, + VM_COMMON_ARG_SPEC, +) + + +KIND = 'VirtualMachineInstanceReplicaSet' +VMIR_ARG_SPEC = { + 'replicas': {'type': 'int'}, + 'selector': {'type': 'dict'}, +} + + +class KubeVirtVMIRS(KubeVirtRawModule): + + @property + def argspec(self): + """ argspec property builder """ + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(copy.deepcopy(VM_COMMON_ARG_SPEC)) + argument_spec.update(copy.deepcopy(VMIR_ARG_SPEC)) + return argument_spec + + def wait_for_replicas(self, replicas): + """ Wait for ready_replicas to equal the requested number of replicas. """ + resource = self.find_supported_resource(KIND) + return_obj = None + + for event in resource.watch(namespace=self.namespace, timeout=self.params.get('wait_timeout')): + entity = event['object'] + if entity.metadata.name != self.name: + continue + status = entity.get('status', {}) + readyReplicas = status.get('readyReplicas', 0) + if readyReplicas == replicas: + return_obj = entity + break + + if not return_obj: + self.fail_json(msg="Error fetching the patched object. Try a higher wait_timeout value.") + if replicas and return_obj.status.readyReplicas is None: + self.fail_json(msg="Failed to fetch the number of ready replicas. Try a higher wait_timeout value.") + if replicas and return_obj.status.readyReplicas != replicas: + self.fail_json(msg="Number of ready replicas is {0}. Failed to reach {1} ready replicas within " + "the wait_timeout period.".format(return_obj.status.ready_replicas, replicas)) + return return_obj.to_dict() + + def execute_module(self): + # Parse parameters specific for this module: + definition = virtdict() + selector = self.params.get('selector') + replicas = self.params.get('replicas') + + if selector: + definition['spec']['selector'] = selector + + if replicas is not None: + definition['spec']['replicas'] = replicas + + # defaults for template + defaults = {'disks': [], 'volumes': [], 'interfaces': [], 'networks': []} + + # Execute the CURD of VM: + template = definition['spec']['template'] + dummy, definition = self.construct_vm_definition(KIND, definition, template, defaults) + result_crud = self.execute_crud(KIND, definition) + changed = result_crud['changed'] + result = result_crud.pop('result') + + # When creating a new VMIRS object without specifying `replicas`, assume it's '1' to make the + # wait logic work correctly + if changed and result_crud['method'] == 'create' and replicas is None: + replicas = 1 + + # Wait for the new number of ready replicas after a CRUD update + # Note1: doesn't work correctly when reducing number of replicas due to how VMIRS works (as of kubevirt 1.5.0) + # Note2: not the place to wait for the VMIs to get deleted when deleting the VMIRS object; that *might* be + # achievable in execute_crud(); keywords: orphanDependents, propagationPolicy, DeleteOptions + if self.params.get('wait') and replicas is not None and self.params.get('state') == 'present': + result = self.wait_for_replicas(replicas) + + # Return from the module: + self.exit_json(**{ + 'changed': changed, + 'kubevirt_rs': result, + 'result': result_crud, + }) + + +def main(): + module = KubeVirtVMIRS() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_template.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_template.py new file mode 100644 index 00000000..ee478b8d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_template.py @@ -0,0 +1,385 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +DOCUMENTATION = ''' +--- +module: kubevirt_template + +short_description: Manage KubeVirt templates + +description: + - Use Openshift Python SDK to manage the state of KubeVirt templates. + + +author: KubeVirt Team (@kubevirt) + +options: + name: + description: + - Name of the Template object. + required: true + type: str + namespace: + description: + - Namespace where the Template object exists. + required: true + type: str + objects: + description: + - List of any valid API objects, such as a I(DeploymentConfig), I(Service), etc. The object + will be created exactly as defined here, with any parameter values substituted in prior to creation. + The definition of these objects can reference parameters defined earlier. + - As part of the list user can pass also I(VirtualMachine) kind. When passing I(VirtualMachine) + user must use Ansible structure of the parameters not the Kubernetes API structure. For more information + please take a look at M(community.kubevirt.kubevirt_vm) module and at EXAMPLES section, where you can see example. + type: list + merge_type: + description: + - Whether to override the default patch merge approach with a specific type. By default, the strategic + merge will typically be used. + type: list + choices: [ json, merge, strategic-merge ] + display_name: + description: + - "A brief, user-friendly name, which can be employed by user interfaces." + type: str + description: + description: + - A description of the template. + - Include enough detail that the user will understand what is being deployed... + and any caveats they need to know before deploying. It should also provide links to additional information, + such as a README file." + type: str + long_description: + description: + - "Additional template description. This may be displayed by the service catalog, for example." + type: str + provider_display_name: + description: + - "The name of the person or organization providing the template." + type: str + documentation_url: + description: + - "A URL referencing further documentation for the template." + type: str + support_url: + description: + - "A URL where support can be obtained for the template." + type: str + editable: + description: + - "Extension for hinting at which elements should be considered editable. + List of jsonpath selectors. The jsonpath root is the objects: element of the template." + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: list + default_disk: + description: + - "The goal of default disk is to define what kind of disk is supported by the OS mainly in + terms of bus (ide, scsi, sata, virtio, ...)" + - The C(default_disk) parameter define configuration overlay for disks that will be applied on top of disks + during virtual machine creation to define global compatibility and/or performance defaults defined here. + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: dict + default_volume: + description: + - "The goal of default volume is to be able to configure mostly performance parameters like + caches if those are exposed by the underlying volume implementation." + - The C(default_volume) parameter define configuration overlay for volumes that will be applied on top of volumes + during virtual machine creation to define global compatibility and/or performance defaults defined here. + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: dict + default_nic: + description: + - "The goal of default network is similar to I(default_disk) and should be used as a template + to ensure OS compatibility and performance." + - The C(default_nic) parameter define configuration overlay for nic that will be applied on top of nics + during virtual machine creation to define global compatibility and/or performance defaults defined here. + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: dict + default_network: + description: + - "The goal of default network is similar to I(default_volume) and should be used as a template + that specifies performance and connection parameters (L2 bridge for example)" + - The C(default_network) parameter define configuration overlay for networks that will be applied on top of networks + during virtual machine creation to define global compatibility and/or performance defaults defined here. + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: dict + icon_class: + description: + - "An icon to be displayed with your template in the web console. Choose from our existing logo + icons when possible. You can also use icons from FontAwesome. Alternatively, provide icons through + CSS customizations that can be added to an OpenShift Container Platform cluster that uses your template. + You must specify an icon class that exists, or it will prevent falling back to the generic icon." + type: str + parameters: + description: + - "Parameters allow a value to be supplied by the user or generated when the template is instantiated. + Then, that value is substituted wherever the parameter is referenced. References can be defined in any + field in the objects list field. This is useful for generating random passwords or allowing the user to + supply a host name or other user-specific value that is required to customize the template." + - "More information can be found at: U(https://docs.openshift.com/container-platform/3.6/dev_guide/templates.html#writing-parameters)" + type: list + version: + description: + - Template structure version. + - This is parameter can be used only when kubevirt addon is installed on your openshift cluster. + type: str + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options +- community.kubernetes.k8s_state_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +''' + +EXAMPLES = ''' +- name: Create template 'mytemplate' + community.kubevirt.kubevirt_template: + state: present + name: myvmtemplate + namespace: templates + display_name: Generic cirros template + description: Basic cirros template + long_description: Verbose description of cirros template + provider_display_name: Just Be Cool, Inc. + documentation_url: http://theverycoolcompany.com + support_url: http://support.theverycoolcompany.com + icon_class: icon-linux + default_disk: + disk: + bus: virtio + default_nic: + model: virtio + default_network: + resource: + resourceName: bridge.network.kubevirt.io/cnvmgmt + default_volume: + containerDisk: + image: kubevirt/cirros-container-disk-demo:latest + objects: + - name: ${NAME} + kind: VirtualMachine + memory: ${MEMORY_SIZE} + state: present + namespace: vms + parameters: + - name: NAME + description: VM name + generate: expression + from: 'vm-[A-Za-z0-9]{8}' + - name: MEMORY_SIZE + description: Memory size + value: 1Gi + +- name: Remove template 'myvmtemplate' + community.kubevirt.kubevirt_template: + state: absent + name: myvmtemplate + namespace: templates +''' + +RETURN = ''' +kubevirt_template: + description: + - The template dictionary specification returned by the API. + returned: success + type: complex + contains: {} +''' + + +import copy +import traceback + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC + +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import ( + virtdict, + KubeVirtRawModule, + API_GROUP, + MAX_SUPPORTED_API_VERSION +) + + +TEMPLATE_ARG_SPEC = { + 'name': {'required': True}, + 'namespace': {'required': True}, + 'state': { + 'default': 'present', + 'choices': ['present', 'absent'], + }, + 'force': { + 'type': 'bool', + 'default': False, + }, + 'merge_type': { + 'type': 'list', + 'choices': ['json', 'merge', 'strategic-merge'] + }, + 'objects': { + 'type': 'list', + }, + 'display_name': { + 'type': 'str', + }, + 'description': { + 'type': 'str', + }, + 'long_description': { + 'type': 'str', + }, + 'provider_display_name': { + 'type': 'str', + }, + 'documentation_url': { + 'type': 'str', + }, + 'support_url': { + 'type': 'str', + }, + 'icon_class': { + 'type': 'str', + }, + 'version': { + 'type': 'str', + }, + 'editable': { + 'type': 'list', + }, + 'default_disk': { + 'type': 'dict', + }, + 'default_volume': { + 'type': 'dict', + }, + 'default_network': { + 'type': 'dict', + }, + 'default_nic': { + 'type': 'dict', + }, + 'parameters': { + 'type': 'list', + }, +} + + +class KubeVirtVMTemplate(KubeVirtRawModule): + + @property + def argspec(self): + """ argspec property builder """ + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(TEMPLATE_ARG_SPEC) + return argument_spec + + def execute_module(self): + # Parse parameters specific for this module: + definition = virtdict() + + # Execute the CRUD of VM template: + kind = 'Template' + template_api_version = 'template.openshift.io/v1' + + # Fill in template parameters: + definition['parameters'] = self.params.get('parameters') + + # Fill in the default Label + labels = definition['metadata']['labels'] + labels['template.cnv.io/type'] = 'vm' + + # Fill in Openshift/Kubevirt template annotations: + annotations = definition['metadata']['annotations'] + if self.params.get('display_name'): + annotations['openshift.io/display-name'] = self.params.get('display_name') + if self.params.get('description'): + annotations['description'] = self.params.get('description') + if self.params.get('long_description'): + annotations['openshift.io/long-description'] = self.params.get('long_description') + if self.params.get('provider_display_name'): + annotations['openshift.io/provider-display-name'] = self.params.get('provider_display_name') + if self.params.get('documentation_url'): + annotations['openshift.io/documentation-url'] = self.params.get('documentation_url') + if self.params.get('support_url'): + annotations['openshift.io/support-url'] = self.params.get('support_url') + if self.params.get('icon_class'): + annotations['iconClass'] = self.params.get('icon_class') + if self.params.get('version'): + annotations['template.cnv.io/version'] = self.params.get('version') + + # TODO: Make it more Ansiblish, so user don't have to specify API JSON path, but rather Ansible params: + if self.params.get('editable'): + annotations['template.cnv.io/editable'] = self.params.get('editable') + + # Set defaults annotations: + if self.params.get('default_disk'): + annotations['defaults.template.cnv.io/disk'] = self.params.get('default_disk').get('name') + if self.params.get('default_volume'): + annotations['defaults.template.cnv.io/volume'] = self.params.get('default_volume').get('name') + if self.params.get('default_nic'): + annotations['defaults.template.cnv.io/nic'] = self.params.get('default_nic').get('name') + if self.params.get('default_network'): + annotations['defaults.template.cnv.io/network'] = self.params.get('default_network').get('name') + + # Process objects: + self.client = self.get_api_client() + definition['objects'] = [] + objects = self.params.get('objects') or [] + for obj in objects: + if obj['kind'] != 'VirtualMachine': + definition['objects'].append(obj) + else: + vm_definition = virtdict() + + # Set VM defaults: + if self.params.get('default_disk'): + vm_definition['spec']['template']['spec']['domain']['devices']['disks'] = [self.params.get('default_disk')] + if self.params.get('default_volume'): + vm_definition['spec']['template']['spec']['volumes'] = [self.params.get('default_volume')] + if self.params.get('default_nic'): + vm_definition['spec']['template']['spec']['domain']['devices']['interfaces'] = [self.params.get('default_nic')] + if self.params.get('default_network'): + vm_definition['spec']['template']['spec']['networks'] = [self.params.get('default_network')] + + # Set kubevirt API version: + vm_definition['apiVersion'] = '%s/%s' % (API_GROUP, MAX_SUPPORTED_API_VERSION) + + # Construct k8s vm API object: + vm_template = vm_definition['spec']['template'] + dummy, vm_def = self.construct_vm_template_definition('VirtualMachine', vm_definition, vm_template, obj) + + definition['objects'].append(vm_def) + + # Create template: + resource = self.client.resources.get(api_version=template_api_version, kind=kind, name='templates') + definition = self.set_defaults(resource, definition) + result = self.perform_action(resource, definition) + + # Return from the module: + self.exit_json(**{ + 'changed': result['changed'], + 'kubevirt_template': result.pop('result'), + 'result': result, + }) + + +def main(): + module = KubeVirtVMTemplate() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_vm.py b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_vm.py new file mode 100644 index 00000000..5526dc12 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/plugins/modules/kubevirt_vm.py @@ -0,0 +1,469 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2019, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +DOCUMENTATION = ''' +--- +module: kubevirt_vm + +short_description: Manage KubeVirt virtual machine + +description: + - Use Openshift Python SDK to manage the state of KubeVirt virtual machines. + + +author: KubeVirt Team (@kubevirt) + +options: + state: + description: + - Set the virtual machine to either I(present), I(absent), I(running) or I(stopped). + - "I(present) - Create or update a virtual machine. (And run it if it's ephemeral.)" + - "I(absent) - Remove a virtual machine." + - "I(running) - Create or update a virtual machine and run it." + - "I(stopped) - Stop a virtual machine. (This deletes ephemeral VMs.)" + default: "present" + choices: + - present + - absent + - running + - stopped + type: str + name: + description: + - Name of the virtual machine. + required: true + type: str + namespace: + description: + - Namespace where the virtual machine exists. + required: true + type: str + ephemeral: + description: + - If (true) ephemeral virtual machine will be created. When destroyed it won't be accessible again. + - Works only with C(state) I(present) and I(absent). + type: bool + default: false + datavolumes: + description: + - "DataVolumes are a way to automate importing virtual machine disks onto pvcs during the virtual machine's + launch flow. Without using a DataVolume, users have to prepare a pvc with a disk image before assigning + it to a VM or VMI manifest. With a DataVolume, both the pvc creation and import is automated on behalf of the user." + type: list + template: + description: + - "Name of Template to be used in creation of a virtual machine." + type: str + template_parameters: + description: + - "New values of parameters from Template." + type: dict + +extends_documentation_fragment: +- community.kubernetes.k8s_auth_options +- community.kubevirt.kubevirt_vm_options +- community.kubevirt.kubevirt_common_options + + +requirements: + - python >= 2.7 + - openshift >= 0.8.2 +''' + +EXAMPLES = ''' +- name: Start virtual machine 'myvm' + community.kubevirt.kubevirt_vm: + state: running + name: myvm + namespace: vms + +- name: Create virtual machine 'myvm' and start it + community.kubevirt.kubevirt_vm: + state: running + name: myvm + namespace: vms + memory: 64Mi + cpu_cores: 1 + bootloader: efi + smbios_uuid: 5d307ca9-b3ef-428c-8861-06e72d69f223 + cpu_model: Conroe + headless: true + hugepage_size: 2Mi + tablets: + - bus: virtio + name: tablet1 + cpu_limit: 3 + cpu_shares: 2 + disks: + - name: containerdisk + volume: + containerDisk: + image: kubevirt/cirros-container-disk-demo:latest + path: /custom-disk/cirros.img + disk: + bus: virtio + +- name: Create virtual machine 'myvm' with multus network interface + community.kubevirt.kubevirt_vm: + name: myvm + namespace: vms + memory: 512M + interfaces: + - name: default + bridge: {} + network: + pod: {} + - name: mynet + bridge: {} + network: + multus: + networkName: mynetconf + +- name: Combine inline definition with Ansible parameters + community.kubevirt.kubevirt_vm: + # Kubernetes specification: + definition: + metadata: + labels: + app: galaxy + service: web + origin: vmware + + # Ansible parameters: + state: running + name: myvm + namespace: vms + memory: 64M + disks: + - name: containerdisk + volume: + containerDisk: + image: kubevirt/cirros-container-disk-demo:latest + path: /custom-disk/cirros.img + disk: + bus: virtio + +- name: Start ephemeral virtual machine 'myvm' and wait to be running + community.kubevirt.kubevirt_vm: + ephemeral: true + state: running + wait: true + wait_timeout: 180 + name: myvm + namespace: vms + memory: 64M + labels: + kubevirt.io/vm: myvm + disks: + - name: containerdisk + volume: + containerDisk: + image: kubevirt/cirros-container-disk-demo:latest + path: /custom-disk/cirros.img + disk: + bus: virtio + +- name: Start fedora vm with cloud init + community.kubevirt.kubevirt_vm: + state: running + wait: true + name: myvm + namespace: vms + memory: 1024M + cloud_init_nocloud: + userData: |- + #cloud-config + password: fedora + chpasswd: { expire: False } + disks: + - name: containerdisk + volume: + containerDisk: + image: kubevirt/fedora-cloud-container-disk-demo:latest + path: /disk/fedora.qcow2 + disk: + bus: virtio + node_affinity: + soft: + - weight: 1 + term: + match_expressions: + - key: security + operator: In + values: + - S2 + +- name: Create virtual machine with datavolume and specify node affinity + community.kubevirt.kubevirt_vm: + name: myvm + namespace: default + memory: 1024Mi + datavolumes: + - name: mydv + source: + http: + url: https://url/disk.qcow2 + pvc: + accessModes: + - ReadWriteOnce + storage: 5Gi + node_affinity: + hard: + - term: + match_expressions: + - key: security + operator: In + values: + - S1 + +- name: Remove virtual machine 'myvm' + community.kubevirt.kubevirt_vm: + state: absent + name: myvm + namespace: vms +''' + +RETURN = ''' +kubevirt_vm: + description: + - The virtual machine dictionary specification returned by the API. + - "This dictionary contains all values returned by the KubeVirt API all options + are described here U(https://kubevirt.io/api-reference/master/definitions.html#_v1_virtualmachine)" + returned: success + type: complex + contains: {} +''' + + +import copy +import traceback + +from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import ( + virtdict, + KubeVirtRawModule, + VM_COMMON_ARG_SPEC, + VM_SPEC_DEF_ARG_SPEC +) + +VM_ARG_SPEC = { + 'ephemeral': {'type': 'bool', 'default': False}, + 'state': { + 'type': 'str', + 'choices': [ + 'present', 'absent', 'running', 'stopped' + ], + 'default': 'present' + }, + 'datavolumes': {'type': 'list'}, + 'template': {'type': 'str'}, + 'template_parameters': {'type': 'dict'}, +} + +# Which params (can) modify 'spec:' contents of a VM: +VM_SPEC_PARAMS = list(VM_SPEC_DEF_ARG_SPEC.keys()) + ['datavolumes', 'template', 'template_parameters'] + + +class KubeVirtVM(KubeVirtRawModule): + + @property + def argspec(self): + """ argspec property builder """ + argument_spec = copy.deepcopy(AUTH_ARG_SPEC) + argument_spec.update(VM_COMMON_ARG_SPEC) + argument_spec.update(VM_ARG_SPEC) + return argument_spec + + @staticmethod + def fix_serialization(obj): + if obj and hasattr(obj, 'to_dict'): + return obj.to_dict() + return obj + + def _wait_for_vmi_running(self): + for event in self._kind_resource.watch(namespace=self.namespace, timeout=self.params.get('wait_timeout')): + entity = event['object'] + if entity.metadata.name != self.name: + continue + status = entity.get('status', {}) + phase = status.get('phase', None) + if phase == 'Running': + return entity + + self.fail("Timeout occurred while waiting for virtual machine to start. Maybe try a higher wait_timeout value?") + + def _wait_for_vm_state(self, new_state): + if new_state == 'running': + want_created = want_ready = True + else: + want_created = want_ready = False + + for event in self._kind_resource.watch(namespace=self.namespace, timeout=self.params.get('wait_timeout')): + entity = event['object'] + if entity.metadata.name != self.name: + continue + status = entity.get('status', {}) + created = status.get('created', False) + ready = status.get('ready', False) + if (created, ready) == (want_created, want_ready): + return entity + + self.fail("Timeout occurred while waiting for virtual machine to achieve '{0}' state. " + "Maybe try a higher wait_timeout value?".format(new_state)) + + def manage_vm_state(self, new_state, already_changed): + new_running = True if new_state == 'running' else False + changed = False + k8s_obj = {} + + if not already_changed: + k8s_obj = self.get_resource(self._kind_resource) + if not k8s_obj: + self.fail("VirtualMachine object disappeared during module operation, aborting.") + if k8s_obj.spec.get('running', False) == new_running: + return False, k8s_obj + + newdef = dict(metadata=dict(name=self.name, namespace=self.namespace), spec=dict(running=new_running)) + k8s_obj, err = self.patch_resource(self._kind_resource, newdef, k8s_obj, + self.name, self.namespace, merge_type='merge') + if err: + self.fail_json(**err) + else: + changed = True + + if self.params.get('wait'): + k8s_obj = self._wait_for_vm_state(new_state) + + return changed, k8s_obj + + def _process_template_defaults(self, proccess_template, processedtemplate, defaults): + def set_template_default(default_name, default_name_index, definition_spec): + default_value = proccess_template['metadata']['annotations'][default_name] + if default_value: + values = definition_spec[default_name_index] + default_values = [d for d in values if d.get('name') == default_value] + defaults[default_name_index] = default_values + if definition_spec[default_name_index] is None: + definition_spec[default_name_index] = [] + definition_spec[default_name_index].extend([d for d in values if d.get('name') != default_value]) + + devices = processedtemplate['spec']['template']['spec']['domain']['devices'] + spec = processedtemplate['spec']['template']['spec'] + + set_template_default('defaults.template.cnv.io/disk', 'disks', devices) + set_template_default('defaults.template.cnv.io/volume', 'volumes', spec) + set_template_default('defaults.template.cnv.io/nic', 'interfaces', devices) + set_template_default('defaults.template.cnv.io/network', 'networks', spec) + + def construct_definition(self, kind, our_state, ephemeral): + definition = virtdict() + processedtemplate = {} + + # Construct the API object definition: + defaults = {'disks': [], 'volumes': [], 'interfaces': [], 'networks': []} + vm_template = self.params.get('template') + if vm_template: + # Find the template the VM should be created from: + template_resource = self.client.resources.get(api_version='template.openshift.io/v1', kind='Template', name='templates') + proccess_template = template_resource.get(name=vm_template, namespace=self.params.get('namespace')) + + # Set proper template values taken from module option 'template_parameters': + for k, v in self.params.get('template_parameters', {}).items(): + for parameter in proccess_template.parameters: + if parameter.name == k: + parameter.value = v + + # Proccess the template: + processedtemplates_res = self.client.resources.get(api_version='template.openshift.io/v1', kind='Template', name='processedtemplates') + processedtemplate = processedtemplates_res.create(proccess_template.to_dict()).to_dict()['objects'][0] + + # Process defaults of the template: + self._process_template_defaults(proccess_template, processedtemplate, defaults) + + if not ephemeral: + definition['spec']['running'] = our_state == 'running' + template = definition if ephemeral else definition['spec']['template'] + template['metadata']['labels']['vm.cnv.io/name'] = self.params.get('name') + dummy, definition = self.construct_vm_definition(kind, definition, template, defaults) + + return self.merge_dicts(definition, processedtemplate) + + def execute_module(self): + # Parse parameters specific to this module: + ephemeral = self.params.get('ephemeral') + k8s_state = our_state = self.params.get('state') + kind = 'VirtualMachineInstance' if ephemeral else 'VirtualMachine' + _used_params = [name for name in self.params if self.params[name] is not None] + # Is 'spec:' getting changed? + vm_spec_change = True if set(VM_SPEC_PARAMS).intersection(_used_params) else False + changed = False + crud_executed = False + method = '' + + # Underlying module_utils/k8s/* code knows only of state == present/absent; let's make sure not to confuse it + if ephemeral: + # Ephemerals don't actually support running/stopped; we treat those as aliases for present/absent instead + if our_state == 'running': + self.params['state'] = k8s_state = 'present' + elif our_state == 'stopped': + self.params['state'] = k8s_state = 'absent' + else: + if our_state != 'absent': + self.params['state'] = k8s_state = 'present' + + # Start with fetching the current object to make sure it exists + # If it does, but we end up not performing any operations on it, at least we'll be able to return + # its current contents as part of the final json + self.client = self.get_api_client() + self._kind_resource = self.find_supported_resource(kind) + k8s_obj = self.get_resource(self._kind_resource) + if not self.check_mode and not vm_spec_change and k8s_state != 'absent' and not k8s_obj: + self.fail("It's impossible to create an empty VM or change state of a non-existent VM.") + + # If there are (potential) changes to `spec:` or we want to delete the object, that warrants a full CRUD + # Also check_mode always warrants a CRUD, as that'll produce a sane result + if vm_spec_change or k8s_state == 'absent' or self.check_mode: + definition = self.construct_definition(kind, our_state, ephemeral) + result = self.execute_crud(kind, definition) + changed = result['changed'] + k8s_obj = result['result'] + method = result['method'] + crud_executed = True + + if ephemeral and self.params.get('wait') and k8s_state == 'present' and not self.check_mode: + # Waiting for k8s_state==absent is handled inside execute_crud() + k8s_obj = self._wait_for_vmi_running() + + if not ephemeral and our_state in ['running', 'stopped'] and not self.check_mode: + # State==present/absent doesn't involve any additional VMI state management and is fully + # handled inside execute_crud() (including wait logic) + patched, k8s_obj = self.manage_vm_state(our_state, crud_executed) + changed = changed or patched + if changed: + method = method or 'patch' + + # Return from the module: + self.exit_json(**{ + 'changed': changed, + 'kubevirt_vm': self.fix_serialization(k8s_obj), + 'method': method + }) + + +def main(): + module = KubeVirtVM() + try: + module.execute_module() + except Exception as e: + module.fail_json(msg=str(e), exception=traceback.format_exc()) + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/aliases b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/aliases new file mode 100644 index 00000000..765b70da --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/aliases @@ -0,0 +1 @@ +shippable/posix/group2 diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/constraints.txt b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/constraints.txt new file mode 100644 index 00000000..c44f44e9 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/constraints.txt @@ -0,0 +1 @@ +setuptools < 45 ; python_version <= '2.7' # setuptools 45 and later require python 3.5 or later diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/inventory_diff.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/inventory_diff.py new file mode 100755 index 00000000..df5a7661 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/inventory_diff.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json +import sys + + +def check_hosts(contrib, plugin): + contrib_hosts = sorted(contrib['_meta']['hostvars'].keys()) + plugin_hosts = sorted(plugin['_meta']['hostvars'].keys()) + assert contrib_hosts == plugin_hosts + return contrib_hosts, plugin_hosts + + +def check_groups(contrib, plugin): + contrib_groups = set(contrib.keys()) + plugin_groups = set(plugin.keys()) + missing_groups = contrib_groups.difference(plugin_groups) + if missing_groups: + print("groups: %s are missing from the plugin" % missing_groups) + assert not missing_groups + return contrib_groups, plugin_groups + + +def check_host_vars(key, value, plugin, host): + # tags are a dict in the plugin + if key.startswith('ec2_tag'): + print('assert tag', key, value) + assert 'tags' in plugin['_meta']['hostvars'][host], 'b file does not have tags in host' + btags = plugin['_meta']['hostvars'][host]['tags'] + tagkey = key.replace('ec2_tag_', '') + assert tagkey in btags, '%s tag not in b file host tags' % tagkey + assert value == btags[tagkey], '%s != %s' % (value, btags[tagkey]) + else: + print('assert var', key, value, key in plugin['_meta']['hostvars'][host], plugin['_meta']['hostvars'][host].get(key)) + assert key in plugin['_meta']['hostvars'][host], "%s not in b's %s hostvars" % (key, host) + assert value == plugin['_meta']['hostvars'][host][key], "%s != %s" % (value, plugin['_meta']['hostvars'][host][key]) + + +def main(): + # a should be the source of truth (the script output) + a = sys.argv[1] + # b should be the thing to check (the plugin output) + b = sys.argv[2] + + with open(a, 'r') as f: + adata = json.loads(f.read()) + with open(b, 'r') as f: + bdata = json.loads(f.read()) + + print(adata) + print(bdata) + + # all hosts should be present obviously + ahosts, bhosts = check_hosts(adata, bdata) + + # all groups should be present obviously + agroups, bgroups = check_groups(adata, bdata) + + # check host vars can be reconstructed + for ahost in ahosts: + contrib_host_vars = adata['_meta']['hostvars'][ahost] + for key, value in contrib_host_vars.items(): + check_host_vars(key, value, bdata, ahost) + + +if __name__ == "__main__": + main() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/runme.sh b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/runme.sh new file mode 100755 index 00000000..ea163ab1 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/runme.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash + +if [[ $(python --version 2>&1) =~ 2\.6 ]] + then + echo "Openshift client is not supported on Python 2.6" + exit 0 +fi + +set -eux + +# TODO: quay.io/ansible/default-test-container:2.7.0 doesn't have virtualenv included +apt -y update +apt -y install python3-virtualenv + +source virtualenv.sh +pip install openshift -c constraints.txt + +./server.py & + +cleanup() { + kill -9 "$(jobs -p)" +} + +trap cleanup INT TERM EXIT + +# Fake auth file +mkdir -p ~/.kube/ +cat <<EOF > ~/.kube/config +apiVersion: v1 +clusters: +- cluster: + insecure-skip-tls-verify: true + server: http://localhost:12345 + name: development +contexts: +- context: + cluster: development + user: developer + name: dev-frontend +current-context: dev-frontend +kind: Config +preferences: {} +users: +- name: developer + user: + token: ZDNg7LzSlp8a0u0fht_tRnPMTOjxqgJGCyi_iy0ecUw +EOF + +################################################# +# RUN THE PLUGIN +################################################# + +# run the plugin second +export ANSIBLE_INVENTORY_ENABLED=community.kubevirt.kubevirt +export ANSIBLE_INVENTORY=test.kubevirt.yml + +cat << EOF > "$OUTPUT_DIR/test.kubevirt.yml" +plugin: community.kubevirt.kubevirt +connections: + - namespaces: + - default +EOF + +ANSIBLE_JINJA2_NATIVE=1 ansible-inventory -vvvv -i "$OUTPUT_DIR/test.kubevirt.yml" --list --output="$OUTPUT_DIR/plugin.out" + +################################################# +# DIFF THE RESULTS +################################################# + +./inventory_diff.py "$(pwd)/test.out" "$OUTPUT_DIR/plugin.out" diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/server.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/server.py new file mode 100755 index 00000000..376889e7 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/server.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json +import os + +try: + from http.server import HTTPServer + from http.server import SimpleHTTPRequestHandler +except ImportError: + from BaseHTTPServer import HTTPServer + from SimpleHTTPServer import SimpleHTTPRequestHandler + +from threading import Thread + +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse + + +class TestHandler(SimpleHTTPRequestHandler): + # Path handlers: + handlers = {} + + def log_message(self, format, *args): + """ + Empty method, so we don't mix output of HTTP server with tests + """ + pass + + def do_GET(self): + params = urlparse(self.path) + + if params.path in self.handlers: + self.handlers[params.path](self) + else: + SimpleHTTPRequestHandler.do_GET(self) + + def do_POST(self): + params = urlparse(self.path) + + if params.path in self.handlers: + self.handlers[params.path](self) + else: + SimpleHTTPRequestHandler.do_POST(self) + + +class TestServer(object): + # The host and port and path used by the embedded tests web server: + PORT = None + + # The embedded web server: + _httpd = None + # Thread for http server: + _thread = None + + def set_json_response(self, path, code, body): + def _handle_request(handler): + handler.send_response(code) + handler.send_header('Content-Type', 'application/json') + handler.end_headers() + + data = json.dumps(body, ensure_ascii=False).encode('utf-8') + handler.wfile.write(data) + + TestHandler.handlers[path] = _handle_request + + def start_server(self, host='localhost'): + self._httpd = HTTPServer((host, 12345), TestHandler) + self._thread = Thread(target=self._httpd.serve_forever) + self._thread.start() + + def stop_server(self): + self._httpd.shutdown() + self._thread.join() + + +if __name__ == '__main__': + print(os.getpid()) + server = TestServer() + server.start_server() + server.set_json_response(path="/version", code=200, body={}) + server.set_json_response(path="/api", code=200, body={ + "kind": "APIVersions", "versions": ["v1"], "serverAddressByClientCIDRs": [{"clientCIDR": "0.0.0.0/0", "serverAddress": "localhost:12345"}] + }) + server.set_json_response(path="/api/v1", code=200, body={'resources': {}}) + server.set_json_response(path="/apis", code=200, body={ + "kind": "APIGroupList", "apiVersion": "v1", + "groups": [{ + "name": "kubevirt.io", "versions": [{"groupVersion": "kubevirt.io/v1alpha3", "version": "v1alpha3"}], + "preferredVersion": {"groupVersion": "kubevirt.io/v1alpha3", "version": "v1alpha3"} + }] + }) + server.set_json_response( + path="/apis/kubevirt.io/v1alpha3", + code=200, + body={ + "kind": "APIResourceList", "apiVersion": "v1", "groupVersion": "kubevirt.io/v1alpha3", + "resources": [{ + "name": "virtualmachineinstances", "singularName": "virtualmachineinstance", + "namespaced": True, "kind": "VirtualMachineInstance", + "verbs": ["delete", "deletecollection", "get", "list", "patch", "create", "update", "watch"], + "shortNames":["vmi", "vmis"] + }] + } + ) + server.set_json_response( + path="/apis/kubevirt.io/v1alpha3/namespaces/default/virtualmachineinstances", + code=200, + body={'apiVersion': 'kubevirt.io/v1alpha3', + 'items': [{'apiVersion': 'kubevirt.io/v1alpha3', + 'kind': 'VirtualMachineInstance', + 'metadata': {'annotations': {'ansible': '{"data1": "yes", "data2": "no"}'}, + 'creationTimestamp': '2019-04-05T14:17:02Z', + 'generateName': 'myvm', + 'generation': 1, + 'labels': {'kubevirt.io/nodeName': 'localhost', + 'label': 'x', + 'vm.cnv.io/name': 'myvm'}, + 'name': 'myvm', + 'namespace': 'default', + 'ownerReferences': [{'apiVersion': 'kubevirt.io/v1alpha3', + 'blockOwnerDeletion': True, + 'controller': True, + 'kind': 'VirtualMachine', + 'name': 'myvm', + 'uid': 'f78ebe62-5666-11e9-a214-0800279ffc6b'}], + 'resourceVersion': '1614085', + 'selfLink': '/apis/kubevirt.io/v1alpha3/namespaces/default/virtualmachineinstances/myvm', + 'uid': '7ba1b196-57ad-11e9-9e2e-0800279ffc6b'}, + 'spec': {'domain': {'devices': {'disks': [{'disk': {'bus': 'virtio'}, + 'name': 'containerdisk'}, + {'disk': {'bus': 'virtio'}, 'name': 'ansiblecloudinitdisk'}], + 'interfaces': [{'bridge': {}, 'name': 'default'}]}, + 'firmware': {'uuid': 'cdf77e9e-871b-5acb-a707-80ef3d4b9849'}, + 'machine': {'type': ''}, + 'resources': {'requests': {'memory': '64M'}}}, + 'networks': [{'name': 'default', 'pod': {}}], + 'volumes': [{'containerDisk': {'image': 'kubevirt/cirros-container-disk-demo:v0.11.0'}, + 'name': 'containerdisk'}, + {'cloudInitNoCloud': {'userData': '#cloud-config\npassword: password\nchpasswd: { expire: False }'}, + 'name': 'ansiblecloudinitdisk'}]}, + 'status': {'conditions': [{'lastProbeTime': None, + 'lastTransitionTime': None, + 'status': 'True', + 'type': 'LiveMigratable'}, + {'lastProbeTime': None, + 'lastTransitionTime': '2019-04-05T14:17:27Z', + 'status': 'True', + 'type': 'Ready'}], + 'interfaces': [{'ipAddress': '172.17.0.19', + 'mac': '02:42:ac:11:00:13', + 'name': 'default'}], + 'migrationMethod': 'BlockMigration', + 'nodeName': 'localhost', + 'phase': 'Running'}}], + 'kind': 'VirtualMachineInstanceList', + 'metadata': {'continue': '', + 'resourceVersion': '1614862', + 'selfLink': '/apis/kubevirt.io/v1alpha3/namespaces/default/virtualmachineinstances'}} + ) diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/test.out b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/test.out new file mode 100644 index 00000000..932aade0 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/integration/targets/inventory_kubevirt/test.out @@ -0,0 +1,61 @@ +{ + "_meta": { + "hostvars": { + "default-myvm-7ba1b196-57ad-11e9-9e2e-0800279ffc6b": { + "annotations": { + "ansible": "{\"data1\": \"yes\", \"data2\": \"no\"}" + }, + "ansible_host": "172.17.0.19", + "data1": "yes", + "data2": "no", + "labels": { + "kubevirt.io/nodeName": "localhost", + "label": "x", + "vm.cnv.io/name": "myvm" + }, + "object_type": "vm", + "resource_version": "1614085", + "uid": "7ba1b196-57ad-11e9-9e2e-0800279ffc6b" + } + } + }, + "all": { + "children": [ + "label_kubevirt_io_nodeName_localhost", + "label_label_x", + "label_vm_cnv_io_name_myvm", + "localhost_12345", + "ungrouped" + ] + }, + "label_kubevirt_io_nodeName_localhost": { + "hosts": [ + "default-myvm-7ba1b196-57ad-11e9-9e2e-0800279ffc6b" + ] + }, + "label_label_x": { + "hosts": [ + "default-myvm-7ba1b196-57ad-11e9-9e2e-0800279ffc6b" + ] + }, + "label_vm_cnv_io_name_myvm": { + "hosts": [ + "default-myvm-7ba1b196-57ad-11e9-9e2e-0800279ffc6b" + ] + }, + "localhost_12345": { + "children": [ + "namespace_default" + ] + }, + "namespace_default": { + "children": [ + "namespace_default_vms" + ] + }, + "namespace_default_vms": { + "hosts": [ + "default-myvm-7ba1b196-57ad-11e9-9e2e-0800279ffc6b" + ] + } +} diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.10.txt b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.10.txt new file mode 100644 index 00000000..63be782b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.10.txt @@ -0,0 +1,20 @@ +plugins/modules/kubevirt_cdi_upload.py validate-modules:doc-missing-type +plugins/modules/kubevirt_cdi_upload.py validate-modules:doc-required-mismatch +plugins/modules/kubevirt_cdi_upload.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_cdi_upload.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_preset.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_preset.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_preset.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_pvc.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_pvc.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_pvc.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_pvc.py validate-modules:return-syntax-error +plugins/modules/kubevirt_rs.py validate-modules:doc-required-mismatch +plugins/modules/kubevirt_rs.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_rs.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_rs.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_template.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_template.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_vm.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_vm.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_vm.py validate-modules:parameter-type-not-in-doc diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.11.txt b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.11.txt new file mode 100644 index 00000000..63be782b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.11.txt @@ -0,0 +1,20 @@ +plugins/modules/kubevirt_cdi_upload.py validate-modules:doc-missing-type +plugins/modules/kubevirt_cdi_upload.py validate-modules:doc-required-mismatch +plugins/modules/kubevirt_cdi_upload.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_cdi_upload.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_preset.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_preset.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_preset.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_pvc.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_pvc.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_pvc.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_pvc.py validate-modules:return-syntax-error +plugins/modules/kubevirt_rs.py validate-modules:doc-required-mismatch +plugins/modules/kubevirt_rs.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_rs.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_rs.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_template.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_template.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_vm.py validate-modules:mutually_exclusive-unknown +plugins/modules/kubevirt_vm.py validate-modules:parameter-list-no-elements +plugins/modules/kubevirt_vm.py validate-modules:parameter-type-not-in-doc diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.9.txt b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.9.txt new file mode 100644 index 00000000..beccb65d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/sanity/ignore-2.9.txt @@ -0,0 +1,5 @@ +plugins/modules/kubevirt_cdi_upload.py validate-modules:doc-missing-type +plugins/modules/kubevirt_preset.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_pvc.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_rs.py validate-modules:parameter-type-not-in-doc +plugins/modules/kubevirt_vm.py validate-modules:parameter-type-not-in-doc diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/__init__.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/mock.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/mock.py new file mode 100644 index 00000000..0972cd2e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/mock.py @@ -0,0 +1,122 @@ +# (c) 2014, Toshio Kuratomi <tkuratomi@ansible.com> +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +''' +Compat module for Python3.x's unittest.mock module +''' +import sys + +# Python 2.7 + +# Note: Could use the pypi mock library on python3.x as well as python2.x. It +# is the same as the python3 stdlib mock library + +try: + # Allow wildcard import because we really do want to import all of mock's + # symbols into this compat shim + # pylint: disable=wildcard-import,unused-wildcard-import + from unittest.mock import * +except ImportError: + # Python 2 + # pylint: disable=wildcard-import,unused-wildcard-import + try: + from mock import * + except ImportError: + print('You need the mock library installed on python2.x to run tests') + + +# Prior to 3.4.4, mock_open cannot handle binary read_data +if sys.version_info >= (3,) and sys.version_info < (3, 4, 4): + file_spec = None + + def _iterate_read_data(read_data): + # Helper for mock_open: + # Retrieve lines from read_data via a generator so that separate calls to + # readline, read, and readlines are properly interleaved + sep = b'\n' if isinstance(read_data, bytes) else '\n' + data_as_list = [l + sep for l in read_data.split(sep)] + + if data_as_list[-1] == sep: + # If the last line ended in a newline, the list comprehension will have an + # extra entry that's just a newline. Remove this. + data_as_list = data_as_list[:-1] + else: + # If there wasn't an extra newline by itself, then the file being + # emulated doesn't have a newline to end the last line remove the + # newline that our naive format() added + data_as_list[-1] = data_as_list[-1][:-1] + + for line in data_as_list: + yield line + + def mock_open(mock=None, read_data=''): + """ + A helper function to create a mock to replace the use of `open`. It works + for `open` called directly or used as a context manager. + + The `mock` argument is the mock object to configure. If `None` (the + default) then a `MagicMock` will be created for you, with the API limited + to methods or attributes available on standard file handles. + + `read_data` is a string for the `read` methoddline`, and `readlines` of the + file handle to return. This is an empty string by default. + """ + def _readlines_side_effect(*args, **kwargs): + if handle.readlines.return_value is not None: + return handle.readlines.return_value + return list(_data) + + def _read_side_effect(*args, **kwargs): + if handle.read.return_value is not None: + return handle.read.return_value + return type(read_data)().join(_data) + + def _readline_side_effect(): + if handle.readline.return_value is not None: + while True: + yield handle.readline.return_value + for line in _data: + yield line + + global file_spec + if file_spec is None: + import _io + file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) + + if mock is None: + mock = MagicMock(name='open', spec=open) + + handle = MagicMock(spec=file_spec) + handle.__enter__.return_value = handle + + _data = _iterate_read_data(read_data) + + handle.write.return_value = None + handle.read.return_value = None + handle.readline.return_value = None + handle.readlines.return_value = None + + handle.read.side_effect = _read_side_effect + handle.readline.side_effect = _readline_side_effect() + handle.readlines.side_effect = _readlines_side_effect + + mock.return_value = handle + return mock diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/unittest.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/unittest.py new file mode 100644 index 00000000..98f08ad6 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/compat/unittest.py @@ -0,0 +1,38 @@ +# (c) 2014, Toshio Kuratomi <tkuratomi@ansible.com> +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +''' +Compat module for Python2.7's unittest module +''' + +import sys + +# Allow wildcard import because we really do want to import all of +# unittests's symbols into this compat shim +# pylint: disable=wildcard-import,unused-wildcard-import +if sys.version_info < (2, 7): + try: + # Need unittest2 on python2.6 + from unittest2 import * + except ImportError: + print('You need unittest2 installed on python2.6.x to run tests') +else: + from unittest import * diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/module_utils/test_kubevirt.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/module_utils/test_kubevirt.py new file mode 100644 index 00000000..5cec7d4e --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/module_utils/test_kubevirt.py @@ -0,0 +1,54 @@ +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json +import pytest + +from ansible_collections.community.kubevirt.plugins.module_utils import kubevirt as mymodule + + +def test_simple_merge_dicts(): + dict1 = {'labels': {'label1': 'value'}} + dict2 = {'labels': {'label2': 'value'}} + dict3 = json.dumps({'labels': {'label1': 'value', 'label2': 'value'}}, sort_keys=True) + assert dict3 == json.dumps(dict(mymodule.KubeVirtRawModule.merge_dicts(dict1, dict2)), sort_keys=True) + + +def test_simple_multi_merge_dicts(): + dict1 = {'labels': {'label1': 'value', 'label3': 'value'}} + dict2 = {'labels': {'label2': 'value'}} + dict3 = json.dumps({'labels': {'label1': 'value', 'label2': 'value', 'label3': 'value'}}, sort_keys=True) + assert dict3 == json.dumps(dict(mymodule.KubeVirtRawModule.merge_dicts(dict1, dict2)), sort_keys=True) + + +def test_double_nested_merge_dicts(): + dict1 = {'metadata': {'labels': {'label1': 'value', 'label3': 'value'}}} + dict2 = {'metadata': {'labels': {'label2': 'value'}}} + dict3 = json.dumps({'metadata': {'labels': {'label1': 'value', 'label2': 'value', 'label3': 'value'}}}, sort_keys=True) + assert dict3 == json.dumps(dict(mymodule.KubeVirtRawModule.merge_dicts(dict1, dict2)), sort_keys=True) + + +@pytest.mark.parametrize("lval, operations, rval, result", [ + ('v1', ['<', '<='], 'v2', True), + ('v1', ['>', '>=', '=='], 'v2', False), + ('v1', ['>'], 'v1alpha1', True), + ('v1', ['==', '<', '<='], 'v1alpha1', False), + ('v1beta5', ['==', '<=', '>='], 'v1beta5', True), + ('v1beta5', ['<', '>', '!='], 'v1beta5', False), + +]) +def test_kubeapiversion_comparisons(lval, operations, rval, result): + KubeAPIVersion = mymodule.KubeAPIVersion + for op in operations: + test = '(KubeAPIVersion("{0}") {1} KubeAPIVersion("{2}")) == {3}'.format(lval, op, rval, result) + assert eval(test) + + +@pytest.mark.parametrize("ver", ('nope', 'v1delta7', '1.5', 'v1beta', 'v')) +def test_kubeapiversion_unsupported_versions(ver): + threw = False + try: + mymodule.KubeAPIVersion(ver) + except ValueError: + threw = True + assert threw diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/__init__.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/__init__.py diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/kubevirt_fixtures.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/kubevirt_fixtures.py new file mode 100644 index 00000000..645c70ca --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/kubevirt_fixtures.py @@ -0,0 +1,74 @@ +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import pytest + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.community.kubevirt.tests.unit.compat.mock import MagicMock + +from ansible_collections.community.kubernetes.plugins.module_utils.common import K8sAnsibleMixin +from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import KubeVirtRawModule + +import openshift.dynamic + +RESOURCE_DEFAULT_ARGS = {'api_version': 'v1alpha3', 'group': 'kubevirt.io', + 'prefix': 'apis', 'namespaced': True} + + +class AnsibleExitJson(Exception): + """Exception class to be raised by module.exit_json and caught + by the test case""" + def __init__(self, **kwargs): + for k in kwargs: + setattr(self, k, kwargs[k]) + + def __getitem__(self, attr): + return getattr(self, attr) + + +class AnsibleFailJson(Exception): + """Exception class to be raised by module.fail_json and caught + by the test case""" + def __init__(self, **kwargs): + for k in kwargs: + setattr(self, k, kwargs[k]) + + def __getitem__(self, attr): + return getattr(self, attr) + + +def exit_json(*args, **kwargs): + kwargs['success'] = True + if 'changed' not in kwargs: + kwargs['changed'] = False + raise AnsibleExitJson(**kwargs) + + +def fail_json(*args, **kwargs): + kwargs['success'] = False + raise AnsibleFailJson(**kwargs) + + +@pytest.fixture() +def base_fixture(monkeypatch): + monkeypatch.setattr( + AnsibleModule, "exit_json", exit_json) + monkeypatch.setattr( + AnsibleModule, "fail_json", fail_json) + # Create mock methods in Resource directly, otherwise dyn client + # tries binding those to corresponding methods in DynamicClient + # (with partial()), which is more problematic to intercept + openshift.dynamic.Resource.get = MagicMock() + openshift.dynamic.Resource.create = MagicMock() + openshift.dynamic.Resource.delete = MagicMock() + openshift.dynamic.Resource.patch = MagicMock() + openshift.dynamic.Resource.search = MagicMock() + openshift.dynamic.Resource.watch = MagicMock() + # Globally mock some methods, since all tests will use this + KubernetesRawModule.patch_resource = MagicMock() + KubernetesRawModule.patch_resource.return_value = ({}, None) + K8sAnsibleMixin.get_api_client = MagicMock() + K8sAnsibleMixin.get_api_client.return_value = None + K8sAnsibleMixin.find_resource = MagicMock() + KubeVirtRawModule.find_supported_resource = MagicMock() diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_rs.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_rs.py new file mode 100644 index 00000000..b9425ee9 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_rs.py @@ -0,0 +1,78 @@ +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import pytest + +openshiftdynamic = pytest.importorskip("openshift.dynamic") + +from ansible_collections.community.kubevirt.tests.unit.plugins.modules.utils import set_module_args +from .kubevirt_fixtures import base_fixture, RESOURCE_DEFAULT_ARGS, AnsibleExitJson + +from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule +from ansible_collections.community.kubevirt.plugins.modules import kubevirt_rs as mymodule + +KIND = 'VirtualMachineInstanceReplicaSet' + + +@pytest.mark.usefixtures("base_fixture") +@pytest.mark.parametrize("_replicas, _changed", ((1, True), + (3, True), + (2, False), + (5, True),)) +def test_scale_rs_nowait(_replicas, _changed): + _name = 'test-rs' + # Desired state: + args = dict(name=_name, namespace='vms', replicas=_replicas, wait=False) + set_module_args(args) + + # Mock pre-change state: + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + mymodule.KubeVirtVMIRS.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + res_inst = openshiftdynamic.ResourceInstance('', dict(kind=KIND, metadata={'name': _name}, spec={'replicas': 2})) + openshiftdynamic.Resource.get.return_value = res_inst + openshiftdynamic.Resource.search.return_value = [res_inst] + + # Final state, after patching the object + KubernetesRawModule.patch_resource.return_value = dict(kind=KIND, metadata={'name': _name}, + spec={'replicas': _replicas}), None + + # Run code: + with pytest.raises(AnsibleExitJson) as result: + mymodule.KubeVirtVMIRS().execute_module() + + # Verify result: + assert result.value['changed'] == _changed + + +@pytest.mark.usefixtures("base_fixture") +@pytest.mark.parametrize("_replicas, _success", ((1, False), + (2, False), + (5, True),)) +def test_scale_rs_wait(_replicas, _success): + _name = 'test-rs' + # Desired state: + args = dict(name=_name, namespace='vms', replicas=5, wait=True) + set_module_args(args) + + # Mock pre-change state: + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + mymodule.KubeVirtVMIRS.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + res_inst = openshiftdynamic.ResourceInstance('', dict(kind=KIND, metadata={'name': _name}, spec={'replicas': 2})) + openshiftdynamic.Resource.get.return_value = res_inst + openshiftdynamic.Resource.search.return_value = [res_inst] + + # ~Final state, after patching the object (`replicas` match desired state) + KubernetesRawModule.patch_resource.return_value = dict(kind=KIND, name=_name, metadata={'name': _name}, + spec={'replicas': 5}), None + + # Final final state, as returned by resource.watch() + final_obj = dict(metadata=dict(name=_name), status=dict(readyReplicas=_replicas), **resource_args) + event = openshiftdynamic.ResourceInstance(None, final_obj) + openshiftdynamic.Resource.watch.return_value = [dict(object=event)] + + # Run code: + with pytest.raises(Exception) as result: + mymodule.KubeVirtVMIRS().execute_module() + + # Verify result: + assert result.value['success'] == _success diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_vm.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_vm.py new file mode 100644 index 00000000..975876e7 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/test_kubevirt_vm.py @@ -0,0 +1,113 @@ +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import pytest + +openshiftdynamic = pytest.importorskip("openshift.dynamic") + +from ansible_collections.community.kubevirt.tests.unit.plugins.modules.utils import set_module_args +from .kubevirt_fixtures import base_fixture, RESOURCE_DEFAULT_ARGS, AnsibleExitJson + +from ansible_collections.community.kubevirt.plugins.module_utils.kubevirt import KubeVirtRawModule +from ansible_collections.community.kubevirt.plugins.modules import kubevirt_vm as mymodule + +KIND = 'VirtulMachine' + + +@pytest.mark.usefixtures("base_fixture") +def test_create_vm_with_multus_nowait(): + # Desired state: + args = dict( + state='present', name='testvm', + namespace='vms', + interfaces=[ + {'bridge': {}, 'name': 'default', 'network': {'pod': {}}}, + {'bridge': {}, 'name': 'mynet', 'network': {'multus': {'networkName': 'mynet'}}}, + ], + wait=False, + ) + set_module_args(args) + + # State as "returned" by the "k8s cluster": + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster + + # Run code: + with pytest.raises(AnsibleExitJson) as result: + mymodule.KubeVirtVM().execute_module() + + # Verify result: + assert result.value['changed'] + assert result.value['method'] == 'create' + + +@pytest.mark.usefixtures("base_fixture") +@pytest.mark.parametrize("_wait", (False, True)) +def test_vm_is_absent(_wait): + # Desired state: + args = dict( + state='absent', name='testvmi', + namespace='vms', + wait=_wait, + ) + set_module_args(args) + + # State as "returned" by the "k8s cluster": + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster + + # Run code: + with pytest.raises(AnsibleExitJson) as result: + mymodule.KubeVirtVM().execute_module() + + # Verify result: + assert not result.value['kubevirt_vm'] + assert result.value['method'] == 'delete' + # Note: nothing actually gets deleted, as we mock that there's not object in the cluster present, + # so if the method changes to something other than 'delete' at some point, that's fine + + +@pytest.mark.usefixtures("base_fixture") +def test_vmpreset_create(): + KIND = 'VirtulMachineInstancePreset' + # Desired state: + args = dict(state='present', name='testvmipreset', namespace='vms', memory='1024Mi', wait=False) + set_module_args(args) + + # State as "returned" by the "k8s cluster": + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster + + # Run code: + with pytest.raises(AnsibleExitJson) as result: + mymodule.KubeVirtVM().execute_module() + + # Verify result: + assert result.value['changed'] + assert result.value['method'] == 'create' + + +@pytest.mark.usefixtures("base_fixture") +def test_vmpreset_is_absent(): + KIND = 'VirtulMachineInstancePreset' + # Desired state: + args = dict(state='absent', name='testvmipreset', namespace='vms') + set_module_args(args) + + # State as "returned" by the "k8s cluster": + resource_args = dict(kind=KIND, **RESOURCE_DEFAULT_ARGS) + KubeVirtRawModule.find_supported_resource.return_value = openshiftdynamic.Resource(**resource_args) + openshiftdynamic.Resource.get.return_value = None # Object doesn't exist in the cluster + + # Run code: + with pytest.raises(AnsibleExitJson) as result: + mymodule.KubeVirtVM().execute_module() + + # Verify result: + assert not result.value['kubevirt_vm'] + assert result.value['method'] == 'delete' + # Note: nothing actually gets deleted, as we mock that there's not object in the cluster present, + # so if the method changes to something other than 'delete' at some point, that's fine diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/utils.py b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/utils.py new file mode 100644 index 00000000..a340d28d --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/plugins/modules/utils.py @@ -0,0 +1,52 @@ +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json + +from ansible_collections.community.kubevirt.tests.unit.compat import unittest +from ansible_collections.community.kubevirt.tests.unit.compat.mock import patch +from ansible.module_utils import basic +from ansible.module_utils._text import to_bytes + + +def set_module_args(args): + if '_ansible_remote_tmp' not in args: + args['_ansible_remote_tmp'] = '/tmp' + if '_ansible_keep_remote_files' not in args: + args['_ansible_keep_remote_files'] = False + + args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + basic._ANSIBLE_ARGS = to_bytes(args) + + +class AnsibleExitJson(Exception): + pass + + +class AnsibleFailJson(Exception): + pass + + +def exit_json(*args, **kwargs): + if 'changed' not in kwargs: + kwargs['changed'] = False + raise AnsibleExitJson(kwargs) + + +def fail_json(*args, **kwargs): + kwargs['failed'] = True + raise AnsibleFailJson(kwargs) + + +class ModuleTestCase(unittest.TestCase): + + def setUp(self): + self.mock_module = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) + self.mock_module.start() + self.mock_sleep = patch('time.sleep') + self.mock_sleep.start() + set_module_args({}) + self.addCleanup(self.mock_module.stop) + self.addCleanup(self.mock_sleep.stop) diff --git a/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/requirements.txt b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/requirements.txt new file mode 100644 index 00000000..73fafe55 --- /dev/null +++ b/collections-debian-merged/ansible_collections/community/kubevirt/tests/unit/requirements.txt @@ -0,0 +1,2 @@ +# requirement for kubevirt modules +openshift ; python_version >= '2.7' |