mirror of
https://github.com/ansible/awx.git
synced 2026-04-07 02:59:21 -02:30
Compare commits
83 Commits
21.2.0
...
revert-124
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ba8dd4d98 | ||
|
|
33e445f4f6 | ||
|
|
9bcb60d9e0 | ||
|
|
40109d58c7 | ||
|
|
2ef3f5f9e8 | ||
|
|
389c4a3180 | ||
|
|
cbb019ed09 | ||
|
|
bf5dfdaba7 | ||
|
|
0f7f8af9b8 | ||
|
|
0237402390 | ||
|
|
84d7fa882d | ||
|
|
cd2fae3471 | ||
|
|
8be64145f9 | ||
|
|
23d28fb4c8 | ||
|
|
aeffd6f393 | ||
|
|
ab6b4bad03 | ||
|
|
769c253ac2 | ||
|
|
8031b3d402 | ||
|
|
bd93ac7edd | ||
|
|
37ff9913d3 | ||
|
|
9cb44a7e52 | ||
|
|
6279295541 | ||
|
|
de17cff39c | ||
|
|
22ca49e673 | ||
|
|
008a4b4d30 | ||
|
|
8d4089c7f3 | ||
|
|
e296d0adad | ||
|
|
401b30b3ed | ||
|
|
20cc54694c | ||
|
|
e6ec0952fb | ||
|
|
db1dec3a98 | ||
|
|
1853d3850e | ||
|
|
1e57c84383 | ||
|
|
3cf120c6a7 | ||
|
|
fd671ecc9d | ||
|
|
a0d5f1fb03 | ||
|
|
ff882a322b | ||
|
|
b70231f7d0 | ||
|
|
93d1aa0a9d | ||
|
|
c586f8bbc6 | ||
|
|
26912a06d1 | ||
|
|
218a3d333b | ||
|
|
d2013bd416 | ||
|
|
6a3f9690b0 | ||
|
|
d59b6f834c | ||
|
|
cbea36745e | ||
|
|
ae7be525e1 | ||
|
|
5062ce1e61 | ||
|
|
566665ee8c | ||
|
|
96423af160 | ||
|
|
a01bef8d2c | ||
|
|
0522233892 | ||
|
|
63ea6bb5b3 | ||
|
|
c2715d7c29 | ||
|
|
783b744bdb | ||
|
|
f7982a0d64 | ||
|
|
2147ac226e | ||
|
|
6cc22786bc | ||
|
|
861a9f581e | ||
|
|
e57a8183ba | ||
|
|
8a7163ffad | ||
|
|
439b351c95 | ||
|
|
14afab918e | ||
|
|
ef8d4e73ae | ||
|
|
61f483ae32 | ||
|
|
21bed7473d | ||
|
|
31d8ddcf84 | ||
|
|
9419270897 | ||
|
|
f755d93a58 | ||
|
|
05df2ebad2 | ||
|
|
b44442c460 | ||
|
|
989b389ba4 | ||
|
|
5bd4aade0e | ||
|
|
470910b612 | ||
|
|
dbb81551c8 | ||
|
|
f7c5cb2979 | ||
|
|
babd6f0975 | ||
|
|
7bcceb7e98 | ||
|
|
c92619a2dc | ||
|
|
e7d37b26f3 | ||
|
|
bda335cb19 | ||
|
|
02e7424f51 | ||
|
|
127016d36b |
1
.github/dependabot.yml
vendored
1
.github/dependabot.yml
vendored
@@ -13,7 +13,6 @@ updates:
|
|||||||
- "kialam"
|
- "kialam"
|
||||||
- "mabashian"
|
- "mabashian"
|
||||||
- "marshmalien"
|
- "marshmalien"
|
||||||
- "nixocio"
|
|
||||||
labels:
|
labels:
|
||||||
- "component:ui"
|
- "component:ui"
|
||||||
- "dependencies"
|
- "dependencies"
|
||||||
|
|||||||
42
.github/triage_replies.md
vendored
42
.github/triage_replies.md
vendored
@@ -1,5 +1,5 @@
|
|||||||
## General
|
## General
|
||||||
- For the roundup of all the different mailing lists available from AWX, Ansible, and beyond visit: https://docs.ansible.com/ansible/latest/community/communication.html
|
- For the roundup of all the different mailing lists available from AWX, Ansible, and beyond visit: https://docs.ansible.com/ansible/latest/community/communication.html
|
||||||
- Hello, we think your question is answered in our FAQ. Does this: https://www.ansible.com/products/awx-project/faq cover your question?
|
- Hello, we think your question is answered in our FAQ. Does this: https://www.ansible.com/products/awx-project/faq cover your question?
|
||||||
- You can find the latest documentation here: https://docs.ansible.com/automation-controller/latest/html/userguide/index.html
|
- You can find the latest documentation here: https://docs.ansible.com/automation-controller/latest/html/userguide/index.html
|
||||||
|
|
||||||
@@ -29,12 +29,24 @@ In the future, sometimes starting a discussion on the development list prior to
|
|||||||
Thank you once again for this and your interest in AWX!
|
Thank you once again for this and your interest in AWX!
|
||||||
|
|
||||||
|
|
||||||
### No Progress
|
### No Progress Issue
|
||||||
|
- Hi! \
|
||||||
|
\
|
||||||
|
Thank you very much for for this issue. It means a lot to us that you have taken time to contribute by opening this report. \
|
||||||
|
\
|
||||||
|
On this issue, there were comments added but it has been some time since then without response. At this time we are closing this issue. If you get time to address the comments we can reopen the issue if you can contact us by using any of the communication methods listed in the page below: \
|
||||||
|
\
|
||||||
|
https://github.com/ansible/awx/#get-involved \
|
||||||
|
\
|
||||||
|
Thank you once again for this and your interest in AWX!
|
||||||
|
|
||||||
|
|
||||||
|
### No Progress PR
|
||||||
- Hi! \
|
- Hi! \
|
||||||
\
|
\
|
||||||
Thank you very much for your submission to AWX. It means a lot to us that you have taken time to contribute. \
|
Thank you very much for your submission to AWX. It means a lot to us that you have taken time to contribute. \
|
||||||
\
|
\
|
||||||
On this PR, changes were requested but it has been some time since then. We think this PR has merit but without the requested changes we are unable to merge it. At this time we are closing you PR. If you get time to address the changes you are welcome to open another PR or we can reopen this PR upon request if you contact us by using any of the communication methods listed in the page below: \
|
On this PR, changes were requested but it has been some time since then. We think this PR has merit but without the requested changes we are unable to merge it. At this time we are closing your PR. If you get time to address the changes you are welcome to open another PR or we can reopen this PR upon request if you contact us by using any of the communication methods listed in the page below: \
|
||||||
\
|
\
|
||||||
https://github.com/ansible/awx/#get-involved \
|
https://github.com/ansible/awx/#get-involved \
|
||||||
\
|
\
|
||||||
@@ -46,11 +58,15 @@ Thank you once again for this and your interest in AWX!
|
|||||||
## Common
|
## Common
|
||||||
|
|
||||||
### Give us more info
|
### Give us more info
|
||||||
- Hello, we'd love to help, but we need a little more information about the problem you're having. Screenshots, log outputs, or any reproducers would be very helpful.
|
- Hello, we'd love to help, but we need a little more information about the problem you're having. Screenshots, log outputs, or any reproducers would be very helpful.
|
||||||
|
|
||||||
### Code of Conduct
|
### Code of Conduct
|
||||||
- Hello. Please keep in mind that Ansible adheres to a Code of Conduct in its community spaces. The spirit of the code of conduct is to be kind, and this is your friendly reminder to be so. Please see the full code of conduct here if you have questions: https://docs.ansible.com/ansible/latest/community/code_of_conduct.html
|
- Hello. Please keep in mind that Ansible adheres to a Code of Conduct in its community spaces. The spirit of the code of conduct is to be kind, and this is your friendly reminder to be so. Please see the full code of conduct here if you have questions: https://docs.ansible.com/ansible/latest/community/code_of_conduct.html
|
||||||
|
|
||||||
|
### EE Contents / Community General
|
||||||
|
- Hello. The awx-ee contains the collections and dependencies needed for supported AWX features to function. Anything beyond that (like the community.general package) will require you to build your own EE. For information on how to do that, see https://ansible-builder.readthedocs.io/en/stable/ \
|
||||||
|
\
|
||||||
|
The Ansible Community is looking at building an EE that corresponds to all of the collections inside the ansible package. That may help you if and when it happens; see https://github.com/ansible-community/community-topics/issues/31 for details.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -63,29 +79,31 @@ Thank you once again for this and your interest in AWX!
|
|||||||
- Hello, we think your idea is good! Please consider contributing a PR for this following our contributing guidelines: https://github.com/ansible/awx/blob/devel/CONTRIBUTING.md
|
- Hello, we think your idea is good! Please consider contributing a PR for this following our contributing guidelines: https://github.com/ansible/awx/blob/devel/CONTRIBUTING.md
|
||||||
|
|
||||||
### Receptor
|
### Receptor
|
||||||
- You can find the receptor docs here: https://receptor.readthedocs.io/en/latest/
|
- You can find the receptor docs here: https://receptor.readthedocs.io/en/latest/
|
||||||
- Hello, your issue seems related to receptor. Could you please open an issue in the receptor repository? https://github.com/ansible/receptor. Thanks!
|
- Hello, your issue seems related to receptor. Could you please open an issue in the receptor repository? https://github.com/ansible/receptor. Thanks!
|
||||||
|
|
||||||
### Ansible Engine not AWX
|
### Ansible Engine not AWX
|
||||||
- Hello, your question seems to be about Ansible development, not about AWX. Try asking on the Ansible-devel specific mailing list: https://groups.google.com/g/ansible-devel
|
- Hello, your question seems to be about Ansible development, not about AWX. Try asking on the Ansible-devel specific mailing list: https://groups.google.com/g/ansible-devel
|
||||||
- Hello, your question seems to be about using Ansible, not about AWX. https://groups.google.com/g/ansible-project is the best place to visit for user questions about Ansible. Thanks!
|
- Hello, your question seems to be about using Ansible, not about AWX. https://groups.google.com/g/ansible-project is the best place to visit for user questions about Ansible. Thanks!
|
||||||
|
|
||||||
### Ansible Galaxy not AWX
|
### Ansible Galaxy not AWX
|
||||||
- Hey there. That sounds like an FAQ question. Did this: https://www.ansible.com/products/awx-project/faq cover your question?
|
- Hey there. That sounds like an FAQ question. Did this: https://www.ansible.com/products/awx-project/faq cover your question?
|
||||||
|
|
||||||
### Contributing Guidelines
|
### Contributing Guidelines
|
||||||
- AWX: https://github.com/ansible/awx/blob/devel/CONTRIBUTING.md
|
- AWX: https://github.com/ansible/awx/blob/devel/CONTRIBUTING.md
|
||||||
- AWX-Operator: https://github.com/ansible/awx-operator/blob/devel/CONTRIBUTING.md
|
- AWX-Operator: https://github.com/ansible/awx-operator/blob/devel/CONTRIBUTING.md
|
||||||
|
|
||||||
### AWX Release
|
### AWX Release
|
||||||
|
Subject: Announcing AWX Xa.Ya.za and AWX-Operator Xb.Yb.zb
|
||||||
|
|
||||||
- Hi all, \
|
- Hi all, \
|
||||||
\
|
\
|
||||||
We're happy to announce that the next release of AWX, version <X> is now available! \
|
We're happy to announce that the next release of AWX, version <b>`Xa.Ya.za`</b> is now available! \
|
||||||
In addition AWX Operator version <Y> has also been release! \
|
In addition AWX Operator version <b>`Xb.Yb.zb`</b> has also been released! \
|
||||||
\
|
\
|
||||||
Please see the releases pages for more details: \
|
Please see the releases pages for more details: \
|
||||||
AWX: https://github.com/ansible/awx/releases/tag/<X> \
|
AWX: https://github.com/ansible/awx/releases/tag/Xa.Ya.za \
|
||||||
Operator: https://github.com/ansible/awx-operator/releases/tag/<Y> \
|
Operator: https://github.com/ansible/awx-operator/releases/tag/Xb.Yb.zb \
|
||||||
\
|
\
|
||||||
The AWX team.
|
The AWX team.
|
||||||
|
|
||||||
|
|||||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -113,7 +113,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install playbook dependencies
|
- name: Install playbook dependencies
|
||||||
run: |
|
run: |
|
||||||
python3 -m pip install docker
|
python3 -m pip install docker setuptools_scm
|
||||||
|
|
||||||
- name: Build AWX image
|
- name: Build AWX image
|
||||||
working-directory: awx
|
working-directory: awx
|
||||||
|
|||||||
4
.github/workflows/promote.yml
vendored
4
.github/workflows/promote.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python${{ env.py_version }} -m pip install wheel twine
|
python${{ env.py_version }} -m pip install wheel twine setuptools-scm
|
||||||
|
|
||||||
- name: Set official collection namespace
|
- name: Set official collection namespace
|
||||||
run: echo collection_namespace=awx >> $GITHUB_ENV
|
run: echo collection_namespace=awx >> $GITHUB_ENV
|
||||||
@@ -70,4 +70,4 @@ jobs:
|
|||||||
docker tag ghcr.io/${{ github.repository }}:${{ github.event.release.tag_name }} quay.io/${{ github.repository }}:latest
|
docker tag ghcr.io/${{ github.repository }}:${{ github.event.release.tag_name }} quay.io/${{ github.repository }}:latest
|
||||||
docker push quay.io/${{ github.repository }}:${{ github.event.release.tag_name }}
|
docker push quay.io/${{ github.repository }}:${{ github.event.release.tag_name }}
|
||||||
docker push quay.io/${{ github.repository }}:latest
|
docker push quay.io/${{ github.repository }}:latest
|
||||||
|
|
||||||
|
|||||||
2
.github/workflows/stage.yml
vendored
2
.github/workflows/stage.yml
vendored
@@ -65,7 +65,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Install playbook dependencies
|
- name: Install playbook dependencies
|
||||||
run: |
|
run: |
|
||||||
python3 -m pip install docker
|
python3 -m pip install docker setuptools_scm
|
||||||
|
|
||||||
- name: Build and stage AWX
|
- name: Build and stage AWX
|
||||||
working-directory: awx
|
working-directory: awx
|
||||||
|
|||||||
18
Makefile
18
Makefile
@@ -5,8 +5,8 @@ NPM_BIN ?= npm
|
|||||||
CHROMIUM_BIN=/tmp/chrome-linux/chrome
|
CHROMIUM_BIN=/tmp/chrome-linux/chrome
|
||||||
GIT_BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
|
GIT_BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
|
||||||
MANAGEMENT_COMMAND ?= awx-manage
|
MANAGEMENT_COMMAND ?= awx-manage
|
||||||
VERSION := $(shell $(PYTHON) setup.py --version)
|
VERSION := $(shell $(PYTHON) tools/scripts/scm_version.py)
|
||||||
COLLECTION_VERSION := $(shell $(PYTHON) setup.py --version | cut -d . -f 1-3)
|
COLLECTION_VERSION := $(shell $(PYTHON) tools/scripts/scm_version.py | cut -d . -f 1-3)
|
||||||
|
|
||||||
# NOTE: This defaults the container image version to the branch that's active
|
# NOTE: This defaults the container image version to the branch that's active
|
||||||
COMPOSE_TAG ?= $(GIT_BRANCH)
|
COMPOSE_TAG ?= $(GIT_BRANCH)
|
||||||
@@ -49,7 +49,7 @@ I18N_FLAG_FILE = .i18n_built
|
|||||||
.PHONY: awx-link clean clean-tmp clean-venv requirements requirements_dev \
|
.PHONY: awx-link clean clean-tmp clean-venv requirements requirements_dev \
|
||||||
develop refresh adduser migrate dbchange \
|
develop refresh adduser migrate dbchange \
|
||||||
receiver test test_unit test_coverage coverage_html \
|
receiver test test_unit test_coverage coverage_html \
|
||||||
dev_build release_build sdist \
|
sdist \
|
||||||
ui-release ui-devel \
|
ui-release ui-devel \
|
||||||
VERSION PYTHON_VERSION docker-compose-sources \
|
VERSION PYTHON_VERSION docker-compose-sources \
|
||||||
.git/hooks/pre-commit
|
.git/hooks/pre-commit
|
||||||
@@ -273,7 +273,7 @@ api-lint:
|
|||||||
yamllint -s .
|
yamllint -s .
|
||||||
|
|
||||||
awx-link:
|
awx-link:
|
||||||
[ -d "/awx_devel/awx.egg-info" ] || $(PYTHON) /awx_devel/setup.py egg_info_dev
|
[ -d "/awx_devel/awx.egg-info" ] || $(PYTHON) /awx_devel/tools/scripts/egg_info_dev
|
||||||
cp -f /tmp/awx.egg-link /var/lib/awx/venv/awx/lib/$(PYTHON)/site-packages/awx.egg-link
|
cp -f /tmp/awx.egg-link /var/lib/awx/venv/awx/lib/$(PYTHON)/site-packages/awx.egg-link
|
||||||
|
|
||||||
TEST_DIRS ?= awx/main/tests/unit awx/main/tests/functional awx/conf/tests awx/sso/tests
|
TEST_DIRS ?= awx/main/tests/unit awx/main/tests/functional awx/conf/tests awx/sso/tests
|
||||||
@@ -424,21 +424,13 @@ ui-test-general:
|
|||||||
$(NPM_BIN) run --prefix awx/ui pretest
|
$(NPM_BIN) run --prefix awx/ui pretest
|
||||||
$(NPM_BIN) run --prefix awx/ui/ test-general --runInBand
|
$(NPM_BIN) run --prefix awx/ui/ test-general --runInBand
|
||||||
|
|
||||||
# Build a pip-installable package into dist/ with a timestamped version number.
|
|
||||||
dev_build:
|
|
||||||
$(PYTHON) setup.py dev_build
|
|
||||||
|
|
||||||
# Build a pip-installable package into dist/ with the release version number.
|
|
||||||
release_build:
|
|
||||||
$(PYTHON) setup.py release_build
|
|
||||||
|
|
||||||
HEADLESS ?= no
|
HEADLESS ?= no
|
||||||
ifeq ($(HEADLESS), yes)
|
ifeq ($(HEADLESS), yes)
|
||||||
dist/$(SDIST_TAR_FILE):
|
dist/$(SDIST_TAR_FILE):
|
||||||
else
|
else
|
||||||
dist/$(SDIST_TAR_FILE): $(UI_BUILD_FLAG_FILE)
|
dist/$(SDIST_TAR_FILE): $(UI_BUILD_FLAG_FILE)
|
||||||
endif
|
endif
|
||||||
$(PYTHON) setup.py $(SDIST_COMMAND)
|
$(PYTHON) -m build -s
|
||||||
ln -sf $(SDIST_TAR_FILE) dist/awx.tar.gz
|
ln -sf $(SDIST_TAR_FILE) dist/awx.tar.gz
|
||||||
|
|
||||||
sdist: dist/$(SDIST_TAR_FILE)
|
sdist: dist/$(SDIST_TAR_FILE)
|
||||||
|
|||||||
@@ -6,9 +6,40 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from pkg_resources import get_distribution
|
|
||||||
|
|
||||||
__version__ = get_distribution('awx').version
|
def get_version():
|
||||||
|
version_from_file = get_version_from_file()
|
||||||
|
if version_from_file:
|
||||||
|
return version_from_file
|
||||||
|
else:
|
||||||
|
from setuptools_scm import get_version
|
||||||
|
|
||||||
|
version = get_version(root='..', relative_to=__file__)
|
||||||
|
return version
|
||||||
|
|
||||||
|
|
||||||
|
def get_version_from_file():
|
||||||
|
vf = version_file()
|
||||||
|
if vf:
|
||||||
|
with open(vf, 'r') as file:
|
||||||
|
return file.read().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def version_file():
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
version_file = os.path.join(current_dir, '..', 'VERSION')
|
||||||
|
|
||||||
|
if os.path.exists(version_file):
|
||||||
|
return version_file
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
import pkg_resources
|
||||||
|
|
||||||
|
__version__ = pkg_resources.get_distribution('awx').version
|
||||||
|
except pkg_resources.DistributionNotFound:
|
||||||
|
__version__ = get_version()
|
||||||
|
|
||||||
__all__ = ['__version__']
|
__all__ = ['__version__']
|
||||||
|
|
||||||
|
|
||||||
@@ -21,7 +52,6 @@ try:
|
|||||||
except ImportError: # pragma: no cover
|
except ImportError: # pragma: no cover
|
||||||
MODE = 'production'
|
MODE = 'production'
|
||||||
|
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -2073,7 +2073,7 @@ class InventorySourceSerializer(UnifiedJobTemplateSerializer, InventorySourceOpt
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = InventorySource
|
model = InventorySource
|
||||||
fields = ('*', 'name', 'inventory', 'update_on_launch', 'update_cache_timeout', 'source_project', 'update_on_project_update') + (
|
fields = ('*', 'name', 'inventory', 'update_on_launch', 'update_cache_timeout', 'source_project') + (
|
||||||
'last_update_failed',
|
'last_update_failed',
|
||||||
'last_updated',
|
'last_updated',
|
||||||
) # Backwards compatibility.
|
) # Backwards compatibility.
|
||||||
@@ -2136,11 +2136,6 @@ class InventorySourceSerializer(UnifiedJobTemplateSerializer, InventorySourceOpt
|
|||||||
raise serializers.ValidationError(_("Cannot use manual project for SCM-based inventory."))
|
raise serializers.ValidationError(_("Cannot use manual project for SCM-based inventory."))
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def validate_update_on_project_update(self, value):
|
|
||||||
if value and self.instance and self.instance.schedules.exists():
|
|
||||||
raise serializers.ValidationError(_("Setting not compatible with existing schedules."))
|
|
||||||
return value
|
|
||||||
|
|
||||||
def validate_inventory(self, value):
|
def validate_inventory(self, value):
|
||||||
if value and value.kind == 'smart':
|
if value and value.kind == 'smart':
|
||||||
raise serializers.ValidationError({"detail": _("Cannot create Inventory Source for Smart Inventory")})
|
raise serializers.ValidationError({"detail": _("Cannot create Inventory Source for Smart Inventory")})
|
||||||
@@ -2191,7 +2186,7 @@ class InventorySourceSerializer(UnifiedJobTemplateSerializer, InventorySourceOpt
|
|||||||
if ('source' in attrs or 'source_project' in attrs) and get_field_from_model_or_attrs('source_project') is None:
|
if ('source' in attrs or 'source_project' in attrs) and get_field_from_model_or_attrs('source_project') is None:
|
||||||
raise serializers.ValidationError({"source_project": _("Project required for scm type sources.")})
|
raise serializers.ValidationError({"source_project": _("Project required for scm type sources.")})
|
||||||
else:
|
else:
|
||||||
redundant_scm_fields = list(filter(lambda x: attrs.get(x, None), ['source_project', 'source_path', 'update_on_project_update']))
|
redundant_scm_fields = list(filter(lambda x: attrs.get(x, None), ['source_project', 'source_path']))
|
||||||
if redundant_scm_fields:
|
if redundant_scm_fields:
|
||||||
raise serializers.ValidationError({"detail": _("Cannot set %s if not SCM type." % ' '.join(redundant_scm_fields))})
|
raise serializers.ValidationError({"detail": _("Cannot set %s if not SCM type." % ' '.join(redundant_scm_fields))})
|
||||||
|
|
||||||
@@ -4745,13 +4740,6 @@ class ScheduleSerializer(LaunchConfigurationBaseSerializer, SchedulePreviewSeria
|
|||||||
raise serializers.ValidationError(_('Inventory Source must be a cloud resource.'))
|
raise serializers.ValidationError(_('Inventory Source must be a cloud resource.'))
|
||||||
elif type(value) == Project and value.scm_type == '':
|
elif type(value) == Project and value.scm_type == '':
|
||||||
raise serializers.ValidationError(_('Manual Project cannot have a schedule set.'))
|
raise serializers.ValidationError(_('Manual Project cannot have a schedule set.'))
|
||||||
elif type(value) == InventorySource and value.source == 'scm' and value.update_on_project_update:
|
|
||||||
raise serializers.ValidationError(
|
|
||||||
_(
|
|
||||||
'Inventory sources with `update_on_project_update` cannot be scheduled. '
|
|
||||||
'Schedule its source project `{}` instead.'.format(value.source_project.name)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def validate(self, attrs):
|
def validate(self, attrs):
|
||||||
|
|||||||
@@ -115,7 +115,6 @@ from awx.api.metadata import RoleMetadata
|
|||||||
from awx.main.constants import ACTIVE_STATES, SURVEY_TYPE_MAPPING
|
from awx.main.constants import ACTIVE_STATES, SURVEY_TYPE_MAPPING
|
||||||
from awx.main.scheduler.dag_workflow import WorkflowDAG
|
from awx.main.scheduler.dag_workflow import WorkflowDAG
|
||||||
from awx.api.views.mixin import (
|
from awx.api.views.mixin import (
|
||||||
ControlledByScmMixin,
|
|
||||||
InstanceGroupMembershipMixin,
|
InstanceGroupMembershipMixin,
|
||||||
OrganizationCountsMixin,
|
OrganizationCountsMixin,
|
||||||
RelatedJobsPreventDeleteMixin,
|
RelatedJobsPreventDeleteMixin,
|
||||||
@@ -1675,7 +1674,7 @@ class HostList(HostRelatedSearchMixin, ListCreateAPIView):
|
|||||||
return Response(dict(error=_(str(e))), status=status.HTTP_400_BAD_REQUEST)
|
return Response(dict(error=_(str(e))), status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
|
||||||
class HostDetail(RelatedJobsPreventDeleteMixin, ControlledByScmMixin, RetrieveUpdateDestroyAPIView):
|
class HostDetail(RelatedJobsPreventDeleteMixin, RetrieveUpdateDestroyAPIView):
|
||||||
|
|
||||||
always_allow_superuser = False
|
always_allow_superuser = False
|
||||||
model = models.Host
|
model = models.Host
|
||||||
@@ -1709,7 +1708,7 @@ class InventoryHostsList(HostRelatedSearchMixin, SubListCreateAttachDetachAPIVie
|
|||||||
return qs
|
return qs
|
||||||
|
|
||||||
|
|
||||||
class HostGroupsList(ControlledByScmMixin, SubListCreateAttachDetachAPIView):
|
class HostGroupsList(SubListCreateAttachDetachAPIView):
|
||||||
'''the list of groups a host is directly a member of'''
|
'''the list of groups a host is directly a member of'''
|
||||||
|
|
||||||
model = models.Group
|
model = models.Group
|
||||||
@@ -1825,7 +1824,7 @@ class EnforceParentRelationshipMixin(object):
|
|||||||
return super(EnforceParentRelationshipMixin, self).create(request, *args, **kwargs)
|
return super(EnforceParentRelationshipMixin, self).create(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class GroupChildrenList(ControlledByScmMixin, EnforceParentRelationshipMixin, SubListCreateAttachDetachAPIView):
|
class GroupChildrenList(EnforceParentRelationshipMixin, SubListCreateAttachDetachAPIView):
|
||||||
|
|
||||||
model = models.Group
|
model = models.Group
|
||||||
serializer_class = serializers.GroupSerializer
|
serializer_class = serializers.GroupSerializer
|
||||||
@@ -1871,7 +1870,7 @@ class GroupPotentialChildrenList(SubListAPIView):
|
|||||||
return qs.exclude(pk__in=except_pks)
|
return qs.exclude(pk__in=except_pks)
|
||||||
|
|
||||||
|
|
||||||
class GroupHostsList(HostRelatedSearchMixin, ControlledByScmMixin, SubListCreateAttachDetachAPIView):
|
class GroupHostsList(HostRelatedSearchMixin, SubListCreateAttachDetachAPIView):
|
||||||
'''the list of hosts directly below a group'''
|
'''the list of hosts directly below a group'''
|
||||||
|
|
||||||
model = models.Host
|
model = models.Host
|
||||||
@@ -1935,7 +1934,7 @@ class GroupActivityStreamList(SubListAPIView):
|
|||||||
return qs.filter(Q(group=parent) | Q(host__in=parent.hosts.all()))
|
return qs.filter(Q(group=parent) | Q(host__in=parent.hosts.all()))
|
||||||
|
|
||||||
|
|
||||||
class GroupDetail(RelatedJobsPreventDeleteMixin, ControlledByScmMixin, RetrieveUpdateDestroyAPIView):
|
class GroupDetail(RelatedJobsPreventDeleteMixin, RetrieveUpdateDestroyAPIView):
|
||||||
|
|
||||||
model = models.Group
|
model = models.Group
|
||||||
serializer_class = serializers.GroupSerializer
|
serializer_class = serializers.GroupSerializer
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ from awx.api.serializers import (
|
|||||||
JobTemplateSerializer,
|
JobTemplateSerializer,
|
||||||
LabelSerializer,
|
LabelSerializer,
|
||||||
)
|
)
|
||||||
from awx.api.views.mixin import RelatedJobsPreventDeleteMixin, ControlledByScmMixin
|
from awx.api.views.mixin import RelatedJobsPreventDeleteMixin
|
||||||
|
|
||||||
from awx.api.pagination import UnifiedJobEventPagination
|
from awx.api.pagination import UnifiedJobEventPagination
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ class InventoryList(ListCreateAPIView):
|
|||||||
serializer_class = InventorySerializer
|
serializer_class = InventorySerializer
|
||||||
|
|
||||||
|
|
||||||
class InventoryDetail(RelatedJobsPreventDeleteMixin, ControlledByScmMixin, RetrieveUpdateDestroyAPIView):
|
class InventoryDetail(RelatedJobsPreventDeleteMixin, RetrieveUpdateDestroyAPIView):
|
||||||
|
|
||||||
model = Inventory
|
model = Inventory
|
||||||
serializer_class = InventorySerializer
|
serializer_class = InventorySerializer
|
||||||
|
|||||||
@@ -10,13 +10,12 @@ from django.shortcuts import get_object_or_404
|
|||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
from rest_framework.permissions import SAFE_METHODS
|
|
||||||
from rest_framework.exceptions import PermissionDenied
|
from rest_framework.exceptions import PermissionDenied
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework import status
|
from rest_framework import status
|
||||||
|
|
||||||
from awx.main.constants import ACTIVE_STATES
|
from awx.main.constants import ACTIVE_STATES
|
||||||
from awx.main.utils import get_object_or_400, parse_yaml_or_json
|
from awx.main.utils import get_object_or_400
|
||||||
from awx.main.models.ha import Instance, InstanceGroup
|
from awx.main.models.ha import Instance, InstanceGroup
|
||||||
from awx.main.models.organization import Team
|
from awx.main.models.organization import Team
|
||||||
from awx.main.models.projects import Project
|
from awx.main.models.projects import Project
|
||||||
@@ -186,35 +185,6 @@ class OrganizationCountsMixin(object):
|
|||||||
return full_context
|
return full_context
|
||||||
|
|
||||||
|
|
||||||
class ControlledByScmMixin(object):
|
|
||||||
"""
|
|
||||||
Special method to reset SCM inventory commit hash
|
|
||||||
if anything that it manages changes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def _reset_inv_src_rev(self, obj):
|
|
||||||
if self.request.method in SAFE_METHODS or not obj:
|
|
||||||
return
|
|
||||||
project_following_sources = obj.inventory_sources.filter(update_on_project_update=True, source='scm')
|
|
||||||
if project_following_sources:
|
|
||||||
# Allow inventory changes unrelated to variables
|
|
||||||
if self.model == Inventory and (
|
|
||||||
not self.request or not self.request.data or parse_yaml_or_json(self.request.data.get('variables', '')) == parse_yaml_or_json(obj.variables)
|
|
||||||
):
|
|
||||||
return
|
|
||||||
project_following_sources.update(scm_last_revision='')
|
|
||||||
|
|
||||||
def get_object(self):
|
|
||||||
obj = super(ControlledByScmMixin, self).get_object()
|
|
||||||
self._reset_inv_src_rev(obj)
|
|
||||||
return obj
|
|
||||||
|
|
||||||
def get_parent_object(self):
|
|
||||||
obj = super(ControlledByScmMixin, self).get_parent_object()
|
|
||||||
self._reset_inv_src_rev(obj)
|
|
||||||
return obj
|
|
||||||
|
|
||||||
|
|
||||||
class NoTruncateMixin(object):
|
class NoTruncateMixin(object):
|
||||||
def get_serializer_context(self):
|
def get_serializer_context(self):
|
||||||
context = super().get_serializer_context()
|
context = super().get_serializer_context()
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ def config(since, **kwargs):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@register('counts', '1.1', description=_('Counts of objects such as organizations, inventories, and projects'))
|
@register('counts', '1.2', description=_('Counts of objects such as organizations, inventories, and projects'))
|
||||||
def counts(since, **kwargs):
|
def counts(since, **kwargs):
|
||||||
counts = {}
|
counts = {}
|
||||||
for cls in (
|
for cls in (
|
||||||
@@ -172,6 +172,13 @@ def counts(since, **kwargs):
|
|||||||
.count()
|
.count()
|
||||||
)
|
)
|
||||||
counts['pending_jobs'] = models.UnifiedJob.objects.exclude(launch_type='sync').filter(status__in=('pending',)).count()
|
counts['pending_jobs'] = models.UnifiedJob.objects.exclude(launch_type='sync').filter(status__in=('pending',)).count()
|
||||||
|
if connection.vendor == 'postgresql':
|
||||||
|
with connection.cursor() as cursor:
|
||||||
|
cursor.execute(f"select count(*) from pg_stat_activity where datname=\'{connection.settings_dict['NAME']}\'")
|
||||||
|
counts['database_connections'] = cursor.fetchone()[0]
|
||||||
|
else:
|
||||||
|
# We should be using postgresql, but if we do that change that ever we should change the below value
|
||||||
|
counts['database_connections'] = 1
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
@@ -389,7 +396,7 @@ def events_table_partitioned_modified(since, full_path, until, **kwargs):
|
|||||||
return _events_table(since, full_path, until, 'main_jobevent', 'modified', project_job_created=True, **kwargs)
|
return _events_table(since, full_path, until, 'main_jobevent', 'modified', project_job_created=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
@register('unified_jobs_table', '1.3', format='csv', description=_('Data on jobs run'), expensive=four_hour_slicing)
|
@register('unified_jobs_table', '1.4', format='csv', description=_('Data on jobs run'), expensive=four_hour_slicing)
|
||||||
def unified_jobs_table(since, full_path, until, **kwargs):
|
def unified_jobs_table(since, full_path, until, **kwargs):
|
||||||
unified_job_query = '''COPY (SELECT main_unifiedjob.id,
|
unified_job_query = '''COPY (SELECT main_unifiedjob.id,
|
||||||
main_unifiedjob.polymorphic_ctype_id,
|
main_unifiedjob.polymorphic_ctype_id,
|
||||||
@@ -415,7 +422,8 @@ def unified_jobs_table(since, full_path, until, **kwargs):
|
|||||||
main_unifiedjob.job_explanation,
|
main_unifiedjob.job_explanation,
|
||||||
main_unifiedjob.instance_group_id,
|
main_unifiedjob.instance_group_id,
|
||||||
main_unifiedjob.installed_collections,
|
main_unifiedjob.installed_collections,
|
||||||
main_unifiedjob.ansible_version
|
main_unifiedjob.ansible_version,
|
||||||
|
main_job.forks
|
||||||
FROM main_unifiedjob
|
FROM main_unifiedjob
|
||||||
JOIN django_content_type ON main_unifiedjob.polymorphic_ctype_id = django_content_type.id
|
JOIN django_content_type ON main_unifiedjob.polymorphic_ctype_id = django_content_type.id
|
||||||
LEFT JOIN main_job ON main_unifiedjob.id = main_job.unifiedjob_ptr_id
|
LEFT JOIN main_job ON main_unifiedjob.id = main_job.unifiedjob_ptr_id
|
||||||
|
|||||||
@@ -126,6 +126,8 @@ def metrics():
|
|||||||
LICENSE_INSTANCE_TOTAL = Gauge('awx_license_instance_total', 'Total number of managed hosts provided by your license', registry=REGISTRY)
|
LICENSE_INSTANCE_TOTAL = Gauge('awx_license_instance_total', 'Total number of managed hosts provided by your license', registry=REGISTRY)
|
||||||
LICENSE_INSTANCE_FREE = Gauge('awx_license_instance_free', 'Number of remaining managed hosts provided by your license', registry=REGISTRY)
|
LICENSE_INSTANCE_FREE = Gauge('awx_license_instance_free', 'Number of remaining managed hosts provided by your license', registry=REGISTRY)
|
||||||
|
|
||||||
|
DATABASE_CONNECTIONS = Gauge('awx_database_connections_total', 'Number of connections to database', registry=REGISTRY)
|
||||||
|
|
||||||
license_info = get_license()
|
license_info = get_license()
|
||||||
SYSTEM_INFO.info(
|
SYSTEM_INFO.info(
|
||||||
{
|
{
|
||||||
@@ -163,6 +165,8 @@ def metrics():
|
|||||||
USER_SESSIONS.labels(type='user').set(current_counts['active_user_sessions'])
|
USER_SESSIONS.labels(type='user').set(current_counts['active_user_sessions'])
|
||||||
USER_SESSIONS.labels(type='anonymous').set(current_counts['active_anonymous_sessions'])
|
USER_SESSIONS.labels(type='anonymous').set(current_counts['active_anonymous_sessions'])
|
||||||
|
|
||||||
|
DATABASE_CONNECTIONS.set(current_counts['database_connections'])
|
||||||
|
|
||||||
all_job_data = job_counts(None)
|
all_job_data = job_counts(None)
|
||||||
statuses = all_job_data.get('status', {})
|
statuses = all_job_data.get('status', {})
|
||||||
for status, value in statuses.items():
|
for status, value in statuses.items():
|
||||||
|
|||||||
@@ -213,6 +213,8 @@ class Metrics:
|
|||||||
m.reset_value(self.conn)
|
m.reset_value(self.conn)
|
||||||
self.metrics_have_changed = True
|
self.metrics_have_changed = True
|
||||||
self.conn.delete(root_key + "_lock")
|
self.conn.delete(root_key + "_lock")
|
||||||
|
for m in self.conn.scan_iter(root_key + '_instance_*'):
|
||||||
|
self.conn.delete(m)
|
||||||
|
|
||||||
def inc(self, field, value):
|
def inc(self, field, value):
|
||||||
if value != 0:
|
if value != 0:
|
||||||
|
|||||||
@@ -10,6 +10,27 @@ from awx.main.models import Instance, UnifiedJob, WorkflowJob
|
|||||||
logger = logging.getLogger('awx.main.dispatch')
|
logger = logging.getLogger('awx.main.dispatch')
|
||||||
|
|
||||||
|
|
||||||
|
def startup_reaping():
|
||||||
|
"""
|
||||||
|
If this particular instance is starting, then we know that any running jobs are invalid
|
||||||
|
so we will reap those jobs as a special action here
|
||||||
|
"""
|
||||||
|
me = Instance.objects.me()
|
||||||
|
jobs = UnifiedJob.objects.filter(status='running', controller_node=me.hostname)
|
||||||
|
job_ids = []
|
||||||
|
for j in jobs:
|
||||||
|
job_ids.append(j.id)
|
||||||
|
j.status = 'failed'
|
||||||
|
j.start_args = ''
|
||||||
|
j.job_explanation += 'Task was marked as running at system start up. The system must have not shut down properly, so it has been marked as failed.'
|
||||||
|
j.save(update_fields=['status', 'start_args', 'job_explanation'])
|
||||||
|
if hasattr(j, 'send_notification_templates'):
|
||||||
|
j.send_notification_templates('failed')
|
||||||
|
j.websocket_emit_status('failed')
|
||||||
|
if job_ids:
|
||||||
|
logger.error(f'Unified jobs {job_ids} were reaped on dispatch startup')
|
||||||
|
|
||||||
|
|
||||||
def reap_job(j, status):
|
def reap_job(j, status):
|
||||||
if UnifiedJob.objects.get(id=j.id).status not in ('running', 'waiting'):
|
if UnifiedJob.objects.get(id=j.id).status not in ('running', 'waiting'):
|
||||||
# just in case, don't reap jobs that aren't running
|
# just in case, don't reap jobs that aren't running
|
||||||
|
|||||||
@@ -169,8 +169,9 @@ class AWXConsumerPG(AWXConsumerBase):
|
|||||||
logger.exception(f"Error consuming new events from postgres, will retry for {self.pg_max_wait} s")
|
logger.exception(f"Error consuming new events from postgres, will retry for {self.pg_max_wait} s")
|
||||||
self.pg_down_time = time.time()
|
self.pg_down_time = time.time()
|
||||||
self.pg_is_down = True
|
self.pg_is_down = True
|
||||||
if time.time() - self.pg_down_time > self.pg_max_wait:
|
current_downtime = time.time() - self.pg_down_time
|
||||||
logger.warning(f"Postgres event consumer has not recovered in {self.pg_max_wait} s, exiting")
|
if current_downtime > self.pg_max_wait:
|
||||||
|
logger.exception(f"Postgres event consumer has not recovered in {current_downtime} s, exiting")
|
||||||
raise
|
raise
|
||||||
# Wait for a second before next attempt, but still listen for any shutdown signals
|
# Wait for a second before next attempt, but still listen for any shutdown signals
|
||||||
for i in range(10):
|
for i in range(10):
|
||||||
@@ -179,6 +180,10 @@ class AWXConsumerPG(AWXConsumerBase):
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
for conn in db.connections.all():
|
for conn in db.connections.all():
|
||||||
conn.close_if_unusable_or_obsolete()
|
conn.close_if_unusable_or_obsolete()
|
||||||
|
except Exception:
|
||||||
|
# Log unanticipated exception in addition to writing to stderr to get timestamps and other metadata
|
||||||
|
logger.exception('Encountered unhandled error in dispatcher main loop')
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
class BaseWorker(object):
|
class BaseWorker(object):
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ class Command(BaseCommand):
|
|||||||
# (like the node heartbeat)
|
# (like the node heartbeat)
|
||||||
periodic.run_continuously()
|
periodic.run_continuously()
|
||||||
|
|
||||||
reaper.reap()
|
reaper.startup_reaping()
|
||||||
consumer = None
|
consumer = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Generated by Django 3.2.13 on 2022-06-21 21:29
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger("awx")
|
||||||
|
|
||||||
|
|
||||||
|
def forwards(apps, schema_editor):
|
||||||
|
InventorySource = apps.get_model('main', 'InventorySource')
|
||||||
|
sources = InventorySource.objects.filter(update_on_project_update=True)
|
||||||
|
for src in sources:
|
||||||
|
if src.update_on_launch == False:
|
||||||
|
src.update_on_launch = True
|
||||||
|
src.save(update_fields=['update_on_launch'])
|
||||||
|
logger.info(f"Setting update_on_launch to True for {src}")
|
||||||
|
proj = src.source_project
|
||||||
|
if proj and proj.scm_update_on_launch is False:
|
||||||
|
proj.scm_update_on_launch = True
|
||||||
|
proj.save(update_fields=['scm_update_on_launch'])
|
||||||
|
logger.warning(f"Setting scm_update_on_launch to True for {proj}")
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('main', '0163_convert_job_tags_to_textfield'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(forwards, migrations.RunPython.noop),
|
||||||
|
migrations.RemoveField(
|
||||||
|
model_name='inventorysource',
|
||||||
|
name='scm_last_revision',
|
||||||
|
),
|
||||||
|
migrations.RemoveField(
|
||||||
|
model_name='inventorysource',
|
||||||
|
name='update_on_project_update',
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -35,6 +35,7 @@ def gce(cred, env, private_data_dir):
|
|||||||
container_path = to_container_path(path, private_data_dir)
|
container_path = to_container_path(path, private_data_dir)
|
||||||
env['GCE_CREDENTIALS_FILE_PATH'] = container_path
|
env['GCE_CREDENTIALS_FILE_PATH'] = container_path
|
||||||
env['GCP_SERVICE_ACCOUNT_FILE'] = container_path
|
env['GCP_SERVICE_ACCOUNT_FILE'] = container_path
|
||||||
|
env['GOOGLE_APPLICATION_CREDENTIALS'] = container_path
|
||||||
|
|
||||||
# Handle env variables for new module types.
|
# Handle env variables for new module types.
|
||||||
# This includes gcp_compute inventory plugin and
|
# This includes gcp_compute inventory plugin and
|
||||||
|
|||||||
@@ -985,22 +985,11 @@ class InventorySource(UnifiedJobTemplate, InventorySourceOptions, CustomVirtualE
|
|||||||
default=None,
|
default=None,
|
||||||
null=True,
|
null=True,
|
||||||
)
|
)
|
||||||
scm_last_revision = models.CharField(
|
|
||||||
max_length=1024,
|
|
||||||
blank=True,
|
|
||||||
default='',
|
|
||||||
editable=False,
|
|
||||||
)
|
|
||||||
update_on_project_update = models.BooleanField(
|
|
||||||
default=False,
|
|
||||||
help_text=_(
|
|
||||||
'This field is deprecated and will be removed in a future release. '
|
|
||||||
'In future release, functionality will be migrated to source project update_on_launch.'
|
|
||||||
),
|
|
||||||
)
|
|
||||||
update_on_launch = models.BooleanField(
|
update_on_launch = models.BooleanField(
|
||||||
default=False,
|
default=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
update_cache_timeout = models.PositiveIntegerField(
|
update_cache_timeout = models.PositiveIntegerField(
|
||||||
default=0,
|
default=0,
|
||||||
)
|
)
|
||||||
@@ -1038,14 +1027,6 @@ class InventorySource(UnifiedJobTemplate, InventorySourceOptions, CustomVirtualE
|
|||||||
self.name = 'inventory source (%s)' % replace_text
|
self.name = 'inventory source (%s)' % replace_text
|
||||||
if 'name' not in update_fields:
|
if 'name' not in update_fields:
|
||||||
update_fields.append('name')
|
update_fields.append('name')
|
||||||
# Reset revision if SCM source has changed parameters
|
|
||||||
if self.source == 'scm' and not is_new_instance:
|
|
||||||
before_is = self.__class__.objects.get(pk=self.pk)
|
|
||||||
if before_is.source_path != self.source_path or before_is.source_project_id != self.source_project_id:
|
|
||||||
# Reset the scm_revision if file changed to force update
|
|
||||||
self.scm_last_revision = ''
|
|
||||||
if 'scm_last_revision' not in update_fields:
|
|
||||||
update_fields.append('scm_last_revision')
|
|
||||||
|
|
||||||
# Do the actual save.
|
# Do the actual save.
|
||||||
super(InventorySource, self).save(*args, **kwargs)
|
super(InventorySource, self).save(*args, **kwargs)
|
||||||
@@ -1054,10 +1035,6 @@ class InventorySource(UnifiedJobTemplate, InventorySourceOptions, CustomVirtualE
|
|||||||
if replace_text in self.name:
|
if replace_text in self.name:
|
||||||
self.name = self.name.replace(replace_text, str(self.pk))
|
self.name = self.name.replace(replace_text, str(self.pk))
|
||||||
super(InventorySource, self).save(update_fields=['name'])
|
super(InventorySource, self).save(update_fields=['name'])
|
||||||
if self.source == 'scm' and is_new_instance and self.update_on_project_update:
|
|
||||||
# Schedule a new Project update if one is not already queued
|
|
||||||
if self.source_project and not self.source_project.project_updates.filter(status__in=['new', 'pending', 'waiting']).exists():
|
|
||||||
self.update()
|
|
||||||
if not getattr(_inventory_updates, 'is_updating', False):
|
if not getattr(_inventory_updates, 'is_updating', False):
|
||||||
if self.inventory is not None:
|
if self.inventory is not None:
|
||||||
self.inventory.update_computed_fields()
|
self.inventory.update_computed_fields()
|
||||||
@@ -1147,25 +1124,6 @@ class InventorySource(UnifiedJobTemplate, InventorySourceOptions, CustomVirtualE
|
|||||||
)
|
)
|
||||||
return dict(error=list(error_notification_templates), started=list(started_notification_templates), success=list(success_notification_templates))
|
return dict(error=list(error_notification_templates), started=list(started_notification_templates), success=list(success_notification_templates))
|
||||||
|
|
||||||
def clean_update_on_project_update(self):
|
|
||||||
if (
|
|
||||||
self.update_on_project_update is True
|
|
||||||
and self.source == 'scm'
|
|
||||||
and InventorySource.objects.filter(Q(inventory=self.inventory, update_on_project_update=True, source='scm') & ~Q(id=self.id)).exists()
|
|
||||||
):
|
|
||||||
raise ValidationError(_("More than one SCM-based inventory source with update on project update per-inventory not allowed."))
|
|
||||||
return self.update_on_project_update
|
|
||||||
|
|
||||||
def clean_update_on_launch(self):
|
|
||||||
if self.update_on_project_update is True and self.source == 'scm' and self.update_on_launch is True:
|
|
||||||
raise ValidationError(
|
|
||||||
_(
|
|
||||||
"Cannot update SCM-based inventory source on launch if set to update on project update. "
|
|
||||||
"Instead, configure the corresponding source project to update on launch."
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return self.update_on_launch
|
|
||||||
|
|
||||||
def clean_source_path(self):
|
def clean_source_path(self):
|
||||||
if self.source != 'scm' and self.source_path:
|
if self.source != 'scm' and self.source_path:
|
||||||
raise ValidationError(_("Cannot set source_path if not SCM type."))
|
raise ValidationError(_("Cannot set source_path if not SCM type."))
|
||||||
@@ -1301,13 +1259,6 @@ class InventoryUpdate(UnifiedJob, InventorySourceOptions, JobNotificationMixin,
|
|||||||
return self.global_instance_groups
|
return self.global_instance_groups
|
||||||
return selected_groups
|
return selected_groups
|
||||||
|
|
||||||
def cancel(self, job_explanation=None, is_chain=False):
|
|
||||||
res = super(InventoryUpdate, self).cancel(job_explanation=job_explanation, is_chain=is_chain)
|
|
||||||
if res:
|
|
||||||
if self.launch_type != 'scm' and self.source_project_update:
|
|
||||||
self.source_project_update.cancel(job_explanation=job_explanation)
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class CustomInventoryScript(CommonModelNameNotUnique, ResourceMixin):
|
class CustomInventoryScript(CommonModelNameNotUnique, ResourceMixin):
|
||||||
class Meta:
|
class Meta:
|
||||||
|
|||||||
@@ -743,6 +743,12 @@ class Job(UnifiedJob, JobOptions, SurveyJobMixin, JobNotificationMixin, TaskMana
|
|||||||
return "$hidden due to Ansible no_log flag$"
|
return "$hidden due to Ansible no_log flag$"
|
||||||
return artifacts
|
return artifacts
|
||||||
|
|
||||||
|
def get_effective_artifacts(self, **kwargs):
|
||||||
|
"""Return unified job artifacts (from set_stats) to pass downstream in workflows"""
|
||||||
|
if isinstance(self.artifacts, dict):
|
||||||
|
return self.artifacts
|
||||||
|
return {}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_container_group_task(self):
|
def is_container_group_task(self):
|
||||||
return bool(self.instance_group and self.instance_group.is_container_group)
|
return bool(self.instance_group and self.instance_group.is_container_group)
|
||||||
|
|||||||
@@ -408,6 +408,7 @@ class JobNotificationMixin(object):
|
|||||||
'inventory': 'Stub Inventory',
|
'inventory': 'Stub Inventory',
|
||||||
'id': 42,
|
'id': 42,
|
||||||
'hosts': {},
|
'hosts': {},
|
||||||
|
'extra_vars': {},
|
||||||
'friendly_name': 'Job',
|
'friendly_name': 'Job',
|
||||||
'finished': False,
|
'finished': False,
|
||||||
'credential': 'Stub credential',
|
'credential': 'Stub credential',
|
||||||
|
|||||||
@@ -533,7 +533,7 @@ class UnifiedJob(
|
|||||||
('workflow', _('Workflow')), # Job was started from a workflow job.
|
('workflow', _('Workflow')), # Job was started from a workflow job.
|
||||||
('webhook', _('Webhook')), # Job was started from a webhook event.
|
('webhook', _('Webhook')), # Job was started from a webhook event.
|
||||||
('sync', _('Sync')), # Job was started from a project sync.
|
('sync', _('Sync')), # Job was started from a project sync.
|
||||||
('scm', _('SCM Update')), # Job was created as an Inventory SCM sync.
|
('scm', _('SCM Update')), # (deprecated) Job was created as an Inventory SCM sync.
|
||||||
]
|
]
|
||||||
|
|
||||||
PASSWORD_FIELDS = ('start_args',)
|
PASSWORD_FIELDS = ('start_args',)
|
||||||
@@ -1204,6 +1204,10 @@ class UnifiedJob(
|
|||||||
pass
|
pass
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_effective_artifacts(self, **kwargs):
|
||||||
|
"""Return unified job artifacts (from set_stats) to pass downstream in workflows"""
|
||||||
|
return {}
|
||||||
|
|
||||||
def get_passwords_needed_to_start(self):
|
def get_passwords_needed_to_start(self):
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@@ -318,8 +318,8 @@ class WorkflowJobNode(WorkflowNodeBase):
|
|||||||
for parent_node in self.get_parent_nodes():
|
for parent_node in self.get_parent_nodes():
|
||||||
is_root_node = False
|
is_root_node = False
|
||||||
aa_dict.update(parent_node.ancestor_artifacts)
|
aa_dict.update(parent_node.ancestor_artifacts)
|
||||||
if parent_node.job and hasattr(parent_node.job, 'artifacts'):
|
if parent_node.job:
|
||||||
aa_dict.update(parent_node.job.artifacts)
|
aa_dict.update(parent_node.job.get_effective_artifacts(parents_set=set([self.workflow_job_id])))
|
||||||
if aa_dict and not is_root_node:
|
if aa_dict and not is_root_node:
|
||||||
self.ancestor_artifacts = aa_dict
|
self.ancestor_artifacts = aa_dict
|
||||||
self.save(update_fields=['ancestor_artifacts'])
|
self.save(update_fields=['ancestor_artifacts'])
|
||||||
@@ -659,6 +659,13 @@ class WorkflowJob(UnifiedJob, WorkflowJobOptions, SurveyJobMixin, JobNotificatio
|
|||||||
node_job_description = 'job #{0}, "{1}", which finished with status {2}.'.format(node.job.id, node.job.name, node.job.status)
|
node_job_description = 'job #{0}, "{1}", which finished with status {2}.'.format(node.job.id, node.job.name, node.job.status)
|
||||||
str_arr.append("- node #{0} spawns {1}".format(node.id, node_job_description))
|
str_arr.append("- node #{0} spawns {1}".format(node.id, node_job_description))
|
||||||
result['body'] = '\n'.join(str_arr)
|
result['body'] = '\n'.join(str_arr)
|
||||||
|
result.update(
|
||||||
|
dict(
|
||||||
|
inventory=self.inventory.name if self.inventory else None,
|
||||||
|
limit=self.limit,
|
||||||
|
extra_vars=self.display_extra_vars(),
|
||||||
|
)
|
||||||
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -682,6 +689,27 @@ class WorkflowJob(UnifiedJob, WorkflowJobOptions, SurveyJobMixin, JobNotificatio
|
|||||||
wj = wj.get_workflow_job()
|
wj = wj.get_workflow_job()
|
||||||
return ancestors
|
return ancestors
|
||||||
|
|
||||||
|
def get_effective_artifacts(self, **kwargs):
|
||||||
|
"""
|
||||||
|
For downstream jobs of a workflow nested inside of a workflow,
|
||||||
|
we send aggregated artifacts from the nodes inside of the nested workflow
|
||||||
|
"""
|
||||||
|
artifacts = {}
|
||||||
|
job_queryset = (
|
||||||
|
UnifiedJob.objects.filter(unified_job_node__workflow_job=self)
|
||||||
|
.defer('job_args', 'job_cwd', 'start_args', 'result_traceback')
|
||||||
|
.order_by('finished', 'id')
|
||||||
|
.filter(status__in=['successful', 'failed'])
|
||||||
|
.iterator()
|
||||||
|
)
|
||||||
|
parents_set = kwargs.get('parents_set', set())
|
||||||
|
new_parents_set = parents_set | {self.id}
|
||||||
|
for job in job_queryset:
|
||||||
|
if job.id in parents_set:
|
||||||
|
continue
|
||||||
|
artifacts.update(job.get_effective_artifacts(parents_set=new_parents_set))
|
||||||
|
return artifacts
|
||||||
|
|
||||||
def get_notification_templates(self):
|
def get_notification_templates(self):
|
||||||
return self.workflow_job_template.notification_templates
|
return self.workflow_job_template.notification_templates
|
||||||
|
|
||||||
@@ -885,3 +913,12 @@ class WorkflowApproval(UnifiedJob, JobNotificationMixin):
|
|||||||
@property
|
@property
|
||||||
def workflow_job(self):
|
def workflow_job(self):
|
||||||
return self.unified_job_node.workflow_job
|
return self.unified_job_node.workflow_job
|
||||||
|
|
||||||
|
def notification_data(self):
|
||||||
|
result = super(WorkflowApproval, self).notification_data()
|
||||||
|
result.update(
|
||||||
|
dict(
|
||||||
|
extra_vars=self.workflow_job.display_extra_vars(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|||||||
@@ -248,11 +248,11 @@ class TaskManager:
|
|||||||
workflow_job.save(update_fields=update_fields)
|
workflow_job.save(update_fields=update_fields)
|
||||||
status_changed = True
|
status_changed = True
|
||||||
if status_changed:
|
if status_changed:
|
||||||
|
if workflow_job.spawned_by_workflow:
|
||||||
|
schedule_task_manager()
|
||||||
workflow_job.websocket_emit_status(workflow_job.status)
|
workflow_job.websocket_emit_status(workflow_job.status)
|
||||||
# Operations whose queries rely on modifications made during the atomic scheduling session
|
# Operations whose queries rely on modifications made during the atomic scheduling session
|
||||||
workflow_job.send_notification_templates('succeeded' if workflow_job.status == 'successful' else 'failed')
|
workflow_job.send_notification_templates('succeeded' if workflow_job.status == 'successful' else 'failed')
|
||||||
if workflow_job.spawned_by_workflow:
|
|
||||||
schedule_task_manager()
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@timeit
|
@timeit
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from awx.main.redact import UriCleaner
|
|||||||
from awx.main.constants import MINIMAL_EVENTS, ANSIBLE_RUNNER_NEEDS_UPDATE_MESSAGE
|
from awx.main.constants import MINIMAL_EVENTS, ANSIBLE_RUNNER_NEEDS_UPDATE_MESSAGE
|
||||||
from awx.main.utils.update_model import update_model
|
from awx.main.utils.update_model import update_model
|
||||||
from awx.main.queue import CallbackQueueDispatcher
|
from awx.main.queue import CallbackQueueDispatcher
|
||||||
|
from awx.main.tasks.signals import signal_callback
|
||||||
|
|
||||||
logger = logging.getLogger('awx.main.tasks.callback')
|
logger = logging.getLogger('awx.main.tasks.callback')
|
||||||
|
|
||||||
@@ -179,7 +180,13 @@ class RunnerCallback:
|
|||||||
Ansible runner callback to tell the job when/if it is canceled
|
Ansible runner callback to tell the job when/if it is canceled
|
||||||
"""
|
"""
|
||||||
unified_job_id = self.instance.pk
|
unified_job_id = self.instance.pk
|
||||||
self.instance = self.update_model(unified_job_id)
|
if signal_callback():
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
self.instance = self.update_model(unified_job_id)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(f'Encountered error during cancel check for {unified_job_id}, canceling now')
|
||||||
|
return True
|
||||||
if not self.instance:
|
if not self.instance:
|
||||||
logger.error('unified job {} was deleted while running, canceling'.format(unified_job_id))
|
logger.error('unified job {} was deleted while running, canceling'.format(unified_job_id))
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ from uuid import uuid4
|
|||||||
|
|
||||||
# Django
|
# Django
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db import transaction
|
|
||||||
|
|
||||||
|
|
||||||
# Runner
|
# Runner
|
||||||
@@ -34,7 +33,6 @@ from gitdb.exc import BadName as BadGitName
|
|||||||
from awx.main.dispatch.publish import task
|
from awx.main.dispatch.publish import task
|
||||||
from awx.main.dispatch import get_local_queuename
|
from awx.main.dispatch import get_local_queuename
|
||||||
from awx.main.constants import (
|
from awx.main.constants import (
|
||||||
ACTIVE_STATES,
|
|
||||||
PRIVILEGE_ESCALATION_METHODS,
|
PRIVILEGE_ESCALATION_METHODS,
|
||||||
STANDARD_INVENTORY_UPDATE_ENV,
|
STANDARD_INVENTORY_UPDATE_ENV,
|
||||||
JOB_FOLDER_PREFIX,
|
JOB_FOLDER_PREFIX,
|
||||||
@@ -64,6 +62,7 @@ from awx.main.tasks.callback import (
|
|||||||
RunnerCallbackForProjectUpdate,
|
RunnerCallbackForProjectUpdate,
|
||||||
RunnerCallbackForSystemJob,
|
RunnerCallbackForSystemJob,
|
||||||
)
|
)
|
||||||
|
from awx.main.tasks.signals import with_signal_handling, signal_callback
|
||||||
from awx.main.tasks.receptor import AWXReceptorJob
|
from awx.main.tasks.receptor import AWXReceptorJob
|
||||||
from awx.main.exceptions import AwxTaskError, PostRunError, ReceptorNodeNotFound
|
from awx.main.exceptions import AwxTaskError, PostRunError, ReceptorNodeNotFound
|
||||||
from awx.main.utils.ansible import read_ansible_config
|
from awx.main.utils.ansible import read_ansible_config
|
||||||
@@ -394,6 +393,7 @@ class BaseTask(object):
|
|||||||
instance.save(update_fields=['ansible_version'])
|
instance.save(update_fields=['ansible_version'])
|
||||||
|
|
||||||
@with_path_cleanup
|
@with_path_cleanup
|
||||||
|
@with_signal_handling
|
||||||
def run(self, pk, **kwargs):
|
def run(self, pk, **kwargs):
|
||||||
"""
|
"""
|
||||||
Run the job/task and capture its output.
|
Run the job/task and capture its output.
|
||||||
@@ -425,7 +425,7 @@ class BaseTask(object):
|
|||||||
private_data_dir = self.build_private_data_dir(self.instance)
|
private_data_dir = self.build_private_data_dir(self.instance)
|
||||||
self.pre_run_hook(self.instance, private_data_dir)
|
self.pre_run_hook(self.instance, private_data_dir)
|
||||||
self.instance.log_lifecycle("preparing_playbook")
|
self.instance.log_lifecycle("preparing_playbook")
|
||||||
if self.instance.cancel_flag:
|
if self.instance.cancel_flag or signal_callback():
|
||||||
self.instance = self.update_model(self.instance.pk, status='canceled')
|
self.instance = self.update_model(self.instance.pk, status='canceled')
|
||||||
if self.instance.status != 'running':
|
if self.instance.status != 'running':
|
||||||
# Stop the task chain and prevent starting the job if it has
|
# Stop the task chain and prevent starting the job if it has
|
||||||
@@ -547,6 +547,11 @@ class BaseTask(object):
|
|||||||
self.runner_callback.delay_update(skip_if_already_set=True, job_explanation=f"Job terminated due to {status}")
|
self.runner_callback.delay_update(skip_if_already_set=True, job_explanation=f"Job terminated due to {status}")
|
||||||
if status == 'timeout':
|
if status == 'timeout':
|
||||||
status = 'failed'
|
status = 'failed'
|
||||||
|
elif status == 'canceled':
|
||||||
|
self.instance = self.update_model(pk)
|
||||||
|
if (getattr(self.instance, 'cancel_flag', False) is False) and signal_callback():
|
||||||
|
self.runner_callback.delay_update(job_explanation="Task was canceled due to receiving a shutdown signal.")
|
||||||
|
status = 'failed'
|
||||||
except ReceptorNodeNotFound as exc:
|
except ReceptorNodeNotFound as exc:
|
||||||
self.runner_callback.delay_update(job_explanation=str(exc))
|
self.runner_callback.delay_update(job_explanation=str(exc))
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -1168,64 +1173,6 @@ class RunProjectUpdate(BaseTask):
|
|||||||
d[r'^Are you sure you want to continue connecting \(yes/no\)\?\s*?$'] = 'yes'
|
d[r'^Are you sure you want to continue connecting \(yes/no\)\?\s*?$'] = 'yes'
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def _update_dependent_inventories(self, project_update, dependent_inventory_sources):
|
|
||||||
scm_revision = project_update.project.scm_revision
|
|
||||||
inv_update_class = InventoryUpdate._get_task_class()
|
|
||||||
for inv_src in dependent_inventory_sources:
|
|
||||||
if not inv_src.update_on_project_update:
|
|
||||||
continue
|
|
||||||
if inv_src.scm_last_revision == scm_revision:
|
|
||||||
logger.debug('Skipping SCM inventory update for `{}` because ' 'project has not changed.'.format(inv_src.name))
|
|
||||||
continue
|
|
||||||
logger.debug('Local dependent inventory update for `{}`.'.format(inv_src.name))
|
|
||||||
with transaction.atomic():
|
|
||||||
if InventoryUpdate.objects.filter(inventory_source=inv_src, status__in=ACTIVE_STATES).exists():
|
|
||||||
logger.debug('Skipping SCM inventory update for `{}` because ' 'another update is already active.'.format(inv_src.name))
|
|
||||||
continue
|
|
||||||
|
|
||||||
if settings.IS_K8S:
|
|
||||||
instance_group = InventoryUpdate(inventory_source=inv_src).preferred_instance_groups[0]
|
|
||||||
else:
|
|
||||||
instance_group = project_update.instance_group
|
|
||||||
|
|
||||||
local_inv_update = inv_src.create_inventory_update(
|
|
||||||
_eager_fields=dict(
|
|
||||||
launch_type='scm',
|
|
||||||
status='running',
|
|
||||||
instance_group=instance_group,
|
|
||||||
execution_node=project_update.execution_node,
|
|
||||||
controller_node=project_update.execution_node,
|
|
||||||
source_project_update=project_update,
|
|
||||||
celery_task_id=project_update.celery_task_id,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
local_inv_update.log_lifecycle("controller_node_chosen")
|
|
||||||
local_inv_update.log_lifecycle("execution_node_chosen")
|
|
||||||
try:
|
|
||||||
create_partition(local_inv_update.event_class._meta.db_table, start=local_inv_update.created)
|
|
||||||
inv_update_class().run(local_inv_update.id)
|
|
||||||
except Exception:
|
|
||||||
logger.exception('{} Unhandled exception updating dependent SCM inventory sources.'.format(project_update.log_format))
|
|
||||||
|
|
||||||
try:
|
|
||||||
project_update.refresh_from_db()
|
|
||||||
except ProjectUpdate.DoesNotExist:
|
|
||||||
logger.warning('Project update deleted during updates of dependent SCM inventory sources.')
|
|
||||||
break
|
|
||||||
try:
|
|
||||||
local_inv_update.refresh_from_db()
|
|
||||||
except InventoryUpdate.DoesNotExist:
|
|
||||||
logger.warning('%s Dependent inventory update deleted during execution.', project_update.log_format)
|
|
||||||
continue
|
|
||||||
if project_update.cancel_flag:
|
|
||||||
logger.info('Project update {} was canceled while updating dependent inventories.'.format(project_update.log_format))
|
|
||||||
break
|
|
||||||
if local_inv_update.cancel_flag:
|
|
||||||
logger.info('Continuing to process project dependencies after {} was canceled'.format(local_inv_update.log_format))
|
|
||||||
if local_inv_update.status == 'successful':
|
|
||||||
inv_src.scm_last_revision = scm_revision
|
|
||||||
inv_src.save(update_fields=['scm_last_revision'])
|
|
||||||
|
|
||||||
def release_lock(self, instance):
|
def release_lock(self, instance):
|
||||||
try:
|
try:
|
||||||
fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
|
fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
|
||||||
@@ -1435,12 +1382,6 @@ class RunProjectUpdate(BaseTask):
|
|||||||
p.inventory_files = p.inventories
|
p.inventory_files = p.inventories
|
||||||
p.save(update_fields=['scm_revision', 'playbook_files', 'inventory_files'])
|
p.save(update_fields=['scm_revision', 'playbook_files', 'inventory_files'])
|
||||||
|
|
||||||
# Update any inventories that depend on this project
|
|
||||||
dependent_inventory_sources = p.scm_inventory_sources.filter(update_on_project_update=True)
|
|
||||||
if len(dependent_inventory_sources) > 0:
|
|
||||||
if status == 'successful' and instance.launch_type != 'sync':
|
|
||||||
self._update_dependent_inventories(instance, dependent_inventory_sources)
|
|
||||||
|
|
||||||
def build_execution_environment_params(self, instance, private_data_dir):
|
def build_execution_environment_params(self, instance, private_data_dir):
|
||||||
if settings.IS_K8S:
|
if settings.IS_K8S:
|
||||||
return {}
|
return {}
|
||||||
@@ -1620,9 +1561,7 @@ class RunInventoryUpdate(BaseTask):
|
|||||||
source_project = None
|
source_project = None
|
||||||
if inventory_update.inventory_source:
|
if inventory_update.inventory_source:
|
||||||
source_project = inventory_update.inventory_source.source_project
|
source_project = inventory_update.inventory_source.source_project
|
||||||
if (
|
if inventory_update.source == 'scm' and source_project and source_project.scm_type: # never ever update manual projects
|
||||||
inventory_update.source == 'scm' and inventory_update.launch_type != 'scm' and source_project and source_project.scm_type
|
|
||||||
): # never ever update manual projects
|
|
||||||
|
|
||||||
# Check if the content cache exists, so that we do not unnecessarily re-download roles
|
# Check if the content cache exists, so that we do not unnecessarily re-download roles
|
||||||
sync_needs = ['update_{}'.format(source_project.scm_type)]
|
sync_needs = ['update_{}'.format(source_project.scm_type)]
|
||||||
@@ -1655,8 +1594,6 @@ class RunInventoryUpdate(BaseTask):
|
|||||||
sync_task = project_update_task(job_private_data_dir=private_data_dir)
|
sync_task = project_update_task(job_private_data_dir=private_data_dir)
|
||||||
sync_task.run(local_project_sync.id)
|
sync_task.run(local_project_sync.id)
|
||||||
local_project_sync.refresh_from_db()
|
local_project_sync.refresh_from_db()
|
||||||
inventory_update.inventory_source.scm_last_revision = local_project_sync.scm_revision
|
|
||||||
inventory_update.inventory_source.save(update_fields=['scm_last_revision'])
|
|
||||||
except Exception:
|
except Exception:
|
||||||
inventory_update = self.update_model(
|
inventory_update = self.update_model(
|
||||||
inventory_update.pk,
|
inventory_update.pk,
|
||||||
@@ -1667,9 +1604,6 @@ class RunInventoryUpdate(BaseTask):
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
elif inventory_update.source == 'scm' and inventory_update.launch_type == 'scm' and source_project:
|
|
||||||
# This follows update, not sync, so make copy here
|
|
||||||
RunProjectUpdate.make_local_copy(source_project, private_data_dir)
|
|
||||||
|
|
||||||
def post_run_hook(self, inventory_update, status):
|
def post_run_hook(self, inventory_update, status):
|
||||||
super(RunInventoryUpdate, self).post_run_hook(inventory_update, status)
|
super(RunInventoryUpdate, self).post_run_hook(inventory_update, status)
|
||||||
|
|||||||
63
awx/main/tasks/signals.py
Normal file
63
awx/main/tasks/signals.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import signal
|
||||||
|
import functools
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger('awx.main.tasks.signals')
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ['with_signal_handling', 'signal_callback']
|
||||||
|
|
||||||
|
|
||||||
|
class SignalState:
|
||||||
|
def reset(self):
|
||||||
|
self.sigterm_flag = False
|
||||||
|
self.is_active = False
|
||||||
|
self.original_sigterm = None
|
||||||
|
self.original_sigint = None
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.reset()
|
||||||
|
|
||||||
|
def set_flag(self, *args):
|
||||||
|
"""Method to pass into the python signal.signal method to receive signals"""
|
||||||
|
self.sigterm_flag = True
|
||||||
|
|
||||||
|
def connect_signals(self):
|
||||||
|
self.original_sigterm = signal.getsignal(signal.SIGTERM)
|
||||||
|
self.original_sigint = signal.getsignal(signal.SIGINT)
|
||||||
|
signal.signal(signal.SIGTERM, self.set_flag)
|
||||||
|
signal.signal(signal.SIGINT, self.set_flag)
|
||||||
|
self.is_active = True
|
||||||
|
|
||||||
|
def restore_signals(self):
|
||||||
|
signal.signal(signal.SIGTERM, self.original_sigterm)
|
||||||
|
signal.signal(signal.SIGINT, self.original_sigint)
|
||||||
|
self.reset()
|
||||||
|
|
||||||
|
|
||||||
|
signal_state = SignalState()
|
||||||
|
|
||||||
|
|
||||||
|
def signal_callback():
|
||||||
|
return signal_state.sigterm_flag
|
||||||
|
|
||||||
|
|
||||||
|
def with_signal_handling(f):
|
||||||
|
"""
|
||||||
|
Change signal handling to make signal_callback return True in event of SIGTERM or SIGINT.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@functools.wraps(f)
|
||||||
|
def _wrapped(*args, **kwargs):
|
||||||
|
try:
|
||||||
|
this_is_outermost_caller = False
|
||||||
|
if not signal_state.is_active:
|
||||||
|
signal_state.connect_signals()
|
||||||
|
this_is_outermost_caller = True
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
finally:
|
||||||
|
if this_is_outermost_caller:
|
||||||
|
signal_state.restore_signals()
|
||||||
|
|
||||||
|
return _wrapped
|
||||||
@@ -114,10 +114,6 @@ def inform_cluster_of_shutdown():
|
|||||||
try:
|
try:
|
||||||
this_inst = Instance.objects.get(hostname=settings.CLUSTER_HOST_ID)
|
this_inst = Instance.objects.get(hostname=settings.CLUSTER_HOST_ID)
|
||||||
this_inst.mark_offline(update_last_seen=True, errors=_('Instance received normal shutdown signal'))
|
this_inst.mark_offline(update_last_seen=True, errors=_('Instance received normal shutdown signal'))
|
||||||
try:
|
|
||||||
reaper.reap(this_inst)
|
|
||||||
except Exception:
|
|
||||||
logger.exception('failed to reap jobs for {}'.format(this_inst.hostname))
|
|
||||||
logger.warning('Normal shutdown signal for instance {}, ' 'removed self from capacity pool.'.format(this_inst.hostname))
|
logger.warning('Normal shutdown signal for instance {}, ' 'removed self from capacity pool.'.format(this_inst.hostname))
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception('Encountered problem with normal shutdown signal.')
|
logger.exception('Encountered problem with normal shutdown signal.')
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
"ANSIBLE_JINJA2_NATIVE": "True",
|
"ANSIBLE_JINJA2_NATIVE": "True",
|
||||||
"ANSIBLE_TRANSFORM_INVALID_GROUP_CHARS": "never",
|
"ANSIBLE_TRANSFORM_INVALID_GROUP_CHARS": "never",
|
||||||
"GCE_CREDENTIALS_FILE_PATH": "{{ file_reference }}",
|
"GCE_CREDENTIALS_FILE_PATH": "{{ file_reference }}",
|
||||||
|
"GOOGLE_APPLICATION_CREDENTIALS": "{{ file_reference }}",
|
||||||
"GCP_AUTH_KIND": "serviceaccount",
|
"GCP_AUTH_KIND": "serviceaccount",
|
||||||
"GCP_ENV_TYPE": "tower",
|
"GCP_ENV_TYPE": "tower",
|
||||||
"GCP_PROJECT": "fooo",
|
"GCP_PROJECT": "fooo",
|
||||||
"GCP_SERVICE_ACCOUNT_FILE": "{{ file_reference }}"
|
"GCP_SERVICE_ACCOUNT_FILE": "{{ file_reference }}"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ def test_empty():
|
|||||||
"workflow_job_template": 0,
|
"workflow_job_template": 0,
|
||||||
"unified_job": 0,
|
"unified_job": 0,
|
||||||
"pending_jobs": 0,
|
"pending_jobs": 0,
|
||||||
|
"database_connections": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ EXPECTED_VALUES = {
|
|||||||
'awx_license_instance_total': 0,
|
'awx_license_instance_total': 0,
|
||||||
'awx_license_instance_free': 0,
|
'awx_license_instance_free': 0,
|
||||||
'awx_pending_jobs_total': 0,
|
'awx_pending_jobs_total': 0,
|
||||||
|
'awx_database_connections_total': 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,7 @@ from awx.api.versioning import reverse
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def ec2_source(inventory, project):
|
def ec2_source(inventory, project):
|
||||||
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
||||||
return inventory.inventory_sources.create(
|
return inventory.inventory_sources.create(name='some_source', source='ec2', source_project=project)
|
||||||
name='some_source', update_on_project_update=True, source='ec2', source_project=project, scm_last_revision=project.scm_revision
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|||||||
@@ -13,9 +13,7 @@ from awx.main.models import InventorySource, Inventory, ActivityStream
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def scm_inventory(inventory, project):
|
def scm_inventory(inventory, project):
|
||||||
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
||||||
inventory.inventory_sources.create(
|
inventory.inventory_sources.create(name='foobar', source='scm', source_project=project)
|
||||||
name='foobar', update_on_project_update=True, source='scm', source_project=project, scm_last_revision=project.scm_revision
|
|
||||||
)
|
|
||||||
return inventory
|
return inventory
|
||||||
|
|
||||||
|
|
||||||
@@ -23,9 +21,7 @@ def scm_inventory(inventory, project):
|
|||||||
def factory_scm_inventory(inventory, project):
|
def factory_scm_inventory(inventory, project):
|
||||||
def fn(**kwargs):
|
def fn(**kwargs):
|
||||||
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
||||||
return inventory.inventory_sources.create(
|
return inventory.inventory_sources.create(source_project=project, overwrite_vars=True, source='scm', **kwargs)
|
||||||
source_project=project, overwrite_vars=True, source='scm', scm_last_revision=project.scm_revision, **kwargs
|
|
||||||
)
|
|
||||||
|
|
||||||
return fn
|
return fn
|
||||||
|
|
||||||
@@ -544,15 +540,12 @@ class TestControlledBySCM:
|
|||||||
def test_safe_method_works(self, get, options, scm_inventory, admin_user):
|
def test_safe_method_works(self, get, options, scm_inventory, admin_user):
|
||||||
get(scm_inventory.get_absolute_url(), admin_user, expect=200)
|
get(scm_inventory.get_absolute_url(), admin_user, expect=200)
|
||||||
options(scm_inventory.get_absolute_url(), admin_user, expect=200)
|
options(scm_inventory.get_absolute_url(), admin_user, expect=200)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision != ''
|
|
||||||
|
|
||||||
def test_vars_edit_reset(self, patch, scm_inventory, admin_user):
|
def test_vars_edit_reset(self, patch, scm_inventory, admin_user):
|
||||||
patch(scm_inventory.get_absolute_url(), {'variables': 'hello: world'}, admin_user, expect=200)
|
patch(scm_inventory.get_absolute_url(), {'variables': 'hello: world'}, admin_user, expect=200)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''
|
|
||||||
|
|
||||||
def test_name_edit_allowed(self, patch, scm_inventory, admin_user):
|
def test_name_edit_allowed(self, patch, scm_inventory, admin_user):
|
||||||
patch(scm_inventory.get_absolute_url(), {'variables': '---', 'name': 'newname'}, admin_user, expect=200)
|
patch(scm_inventory.get_absolute_url(), {'variables': '---', 'name': 'newname'}, admin_user, expect=200)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision != ''
|
|
||||||
|
|
||||||
def test_host_associations_reset(self, post, scm_inventory, admin_user):
|
def test_host_associations_reset(self, post, scm_inventory, admin_user):
|
||||||
inv_src = scm_inventory.inventory_sources.first()
|
inv_src = scm_inventory.inventory_sources.first()
|
||||||
@@ -560,14 +553,12 @@ class TestControlledBySCM:
|
|||||||
g = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
g = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
||||||
post(reverse('api:host_groups_list', kwargs={'pk': h.id}), {'id': g.id}, admin_user, expect=204)
|
post(reverse('api:host_groups_list', kwargs={'pk': h.id}), {'id': g.id}, admin_user, expect=204)
|
||||||
post(reverse('api:group_hosts_list', kwargs={'pk': g.id}), {'id': h.id}, admin_user, expect=204)
|
post(reverse('api:group_hosts_list', kwargs={'pk': g.id}), {'id': h.id}, admin_user, expect=204)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''
|
|
||||||
|
|
||||||
def test_group_group_associations_reset(self, post, scm_inventory, admin_user):
|
def test_group_group_associations_reset(self, post, scm_inventory, admin_user):
|
||||||
inv_src = scm_inventory.inventory_sources.first()
|
inv_src = scm_inventory.inventory_sources.first()
|
||||||
g1 = inv_src.groups.create(name='barland', inventory=scm_inventory)
|
g1 = inv_src.groups.create(name='barland', inventory=scm_inventory)
|
||||||
g2 = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
g2 = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
||||||
post(reverse('api:group_children_list', kwargs={'pk': g1.id}), {'id': g2.id}, admin_user, expect=204)
|
post(reverse('api:group_children_list', kwargs={'pk': g1.id}), {'id': g2.id}, admin_user, expect=204)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''
|
|
||||||
|
|
||||||
def test_host_group_delete_reset(self, delete, scm_inventory, admin_user):
|
def test_host_group_delete_reset(self, delete, scm_inventory, admin_user):
|
||||||
inv_src = scm_inventory.inventory_sources.first()
|
inv_src = scm_inventory.inventory_sources.first()
|
||||||
@@ -575,7 +566,6 @@ class TestControlledBySCM:
|
|||||||
g = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
g = inv_src.groups.create(name='fooland', inventory=scm_inventory)
|
||||||
delete(h.get_absolute_url(), admin_user, expect=204)
|
delete(h.get_absolute_url(), admin_user, expect=204)
|
||||||
delete(g.get_absolute_url(), admin_user, expect=204)
|
delete(g.get_absolute_url(), admin_user, expect=204)
|
||||||
assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''
|
|
||||||
|
|
||||||
def test_remove_scm_inv_src(self, delete, scm_inventory, admin_user):
|
def test_remove_scm_inv_src(self, delete, scm_inventory, admin_user):
|
||||||
inv_src = scm_inventory.inventory_sources.first()
|
inv_src = scm_inventory.inventory_sources.first()
|
||||||
@@ -588,7 +578,6 @@ class TestControlledBySCM:
|
|||||||
{
|
{
|
||||||
'name': 'new inv src',
|
'name': 'new inv src',
|
||||||
'source_project': project.pk,
|
'source_project': project.pk,
|
||||||
'update_on_project_update': False,
|
|
||||||
'source': 'scm',
|
'source': 'scm',
|
||||||
'overwrite_vars': True,
|
'overwrite_vars': True,
|
||||||
'source_vars': 'plugin: a.b.c',
|
'source_vars': 'plugin: a.b.c',
|
||||||
@@ -597,27 +586,6 @@ class TestControlledBySCM:
|
|||||||
expect=201,
|
expect=201,
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_adding_inv_src_prohibited(self, post, scm_inventory, project, admin_user):
|
|
||||||
post(
|
|
||||||
reverse('api:inventory_inventory_sources_list', kwargs={'pk': scm_inventory.id}),
|
|
||||||
{'name': 'new inv src', 'source_project': project.pk, 'update_on_project_update': True, 'source': 'scm', 'overwrite_vars': True},
|
|
||||||
admin_user,
|
|
||||||
expect=400,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_two_update_on_project_update_inv_src_prohibited(self, patch, scm_inventory, factory_scm_inventory, project, admin_user):
|
|
||||||
scm_inventory2 = factory_scm_inventory(name="scm_inventory2")
|
|
||||||
res = patch(
|
|
||||||
reverse('api:inventory_source_detail', kwargs={'pk': scm_inventory2.id}),
|
|
||||||
{
|
|
||||||
'update_on_project_update': True,
|
|
||||||
},
|
|
||||||
admin_user,
|
|
||||||
expect=400,
|
|
||||||
)
|
|
||||||
content = json.loads(res.content)
|
|
||||||
assert content['update_on_project_update'] == ["More than one SCM-based inventory source with update on project update " "per-inventory not allowed."]
|
|
||||||
|
|
||||||
def test_adding_inv_src_without_proj_access_prohibited(self, post, project, inventory, rando):
|
def test_adding_inv_src_without_proj_access_prohibited(self, post, project, inventory, rando):
|
||||||
inventory.admin_role.members.add(rando)
|
inventory.admin_role.members.add(rando)
|
||||||
post(
|
post(
|
||||||
|
|||||||
@@ -347,9 +347,7 @@ def scm_inventory_source(inventory, project):
|
|||||||
source_project=project,
|
source_project=project,
|
||||||
source='scm',
|
source='scm',
|
||||||
source_path='inventory_file',
|
source_path='inventory_file',
|
||||||
update_on_project_update=True,
|
|
||||||
inventory=inventory,
|
inventory=inventory,
|
||||||
scm_last_revision=project.scm_revision,
|
|
||||||
)
|
)
|
||||||
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):
|
||||||
inv_src.save()
|
inv_src.save()
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
from django.core.exceptions import ValidationError
|
|
||||||
|
|
||||||
# AWX
|
# AWX
|
||||||
from awx.main.models import Host, Inventory, InventorySource, InventoryUpdate, CredentialType, Credential, Job
|
from awx.main.models import Host, Inventory, InventorySource, InventoryUpdate, CredentialType, Credential, Job
|
||||||
from awx.main.constants import CLOUD_PROVIDERS
|
from awx.main.constants import CLOUD_PROVIDERS
|
||||||
@@ -123,19 +121,6 @@ class TestActiveCount:
|
|||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestSCMUpdateFeatures:
|
class TestSCMUpdateFeatures:
|
||||||
def test_automatic_project_update_on_create(self, inventory, project):
|
|
||||||
inv_src = InventorySource(source_project=project, source_path='inventory_file', inventory=inventory, update_on_project_update=True, source='scm')
|
|
||||||
with mock.patch.object(inv_src, 'update') as mck_update:
|
|
||||||
inv_src.save()
|
|
||||||
mck_update.assert_called_once_with()
|
|
||||||
|
|
||||||
def test_reset_scm_revision(self, scm_inventory_source):
|
|
||||||
starting_rev = scm_inventory_source.scm_last_revision
|
|
||||||
assert starting_rev != ''
|
|
||||||
scm_inventory_source.source_path = '/newfolder/newfile.ini'
|
|
||||||
scm_inventory_source.save()
|
|
||||||
assert scm_inventory_source.scm_last_revision == ''
|
|
||||||
|
|
||||||
def test_source_location(self, scm_inventory_source):
|
def test_source_location(self, scm_inventory_source):
|
||||||
# Combines project directory with the inventory file specified
|
# Combines project directory with the inventory file specified
|
||||||
inventory_update = InventoryUpdate(inventory_source=scm_inventory_source, source_path=scm_inventory_source.source_path)
|
inventory_update = InventoryUpdate(inventory_source=scm_inventory_source, source_path=scm_inventory_source.source_path)
|
||||||
@@ -167,22 +152,6 @@ class TestRelatedJobs:
|
|||||||
assert job.id in [jerb.id for jerb in group._get_related_jobs()]
|
assert job.id in [jerb.id for jerb in group._get_related_jobs()]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestSCMClean:
|
|
||||||
def test_clean_update_on_project_update_multiple(self, inventory):
|
|
||||||
inv_src1 = InventorySource(inventory=inventory, update_on_project_update=True, source='scm')
|
|
||||||
inv_src1.clean_update_on_project_update()
|
|
||||||
inv_src1.save()
|
|
||||||
|
|
||||||
inv_src1.source_vars = '---\nhello: world'
|
|
||||||
inv_src1.clean_update_on_project_update()
|
|
||||||
|
|
||||||
inv_src2 = InventorySource(inventory=inventory, update_on_project_update=True, source='scm')
|
|
||||||
|
|
||||||
with pytest.raises(ValidationError):
|
|
||||||
inv_src2.clean_update_on_project_update()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
class TestInventorySourceInjectors:
|
class TestInventorySourceInjectors:
|
||||||
def test_extra_credentials(self, project, credential):
|
def test_extra_credentials(self, project, credential):
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ from awx.api.views import WorkflowJobTemplateNodeSuccessNodesList
|
|||||||
# Django
|
# Django
|
||||||
from django.test import TransactionTestCase
|
from django.test import TransactionTestCase
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.utils.timezone import now
|
||||||
|
|
||||||
|
|
||||||
class TestWorkflowDAGFunctional(TransactionTestCase):
|
class TestWorkflowDAGFunctional(TransactionTestCase):
|
||||||
@@ -381,3 +382,38 @@ def test_workflow_ancestors_recursion_prevention(organization):
|
|||||||
WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=wfjt, job=wfj) # well, this is a problem
|
WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=wfjt, job=wfj) # well, this is a problem
|
||||||
# mostly, we just care that this assertion finishes in finite time
|
# mostly, we just care that this assertion finishes in finite time
|
||||||
assert wfj.get_ancestor_workflows() == []
|
assert wfj.get_ancestor_workflows() == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestCombinedArtifacts:
|
||||||
|
@pytest.fixture
|
||||||
|
def wfj_artifacts(self, job_template, organization):
|
||||||
|
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='has_artifacts')
|
||||||
|
wfj = WorkflowJob.objects.create(workflow_job_template=wfjt, launch_type='workflow')
|
||||||
|
job = job_template.create_unified_job(_eager_fields=dict(artifacts={'foooo': 'bar'}, status='successful', finished=now()))
|
||||||
|
WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=job_template, job=job)
|
||||||
|
return wfj
|
||||||
|
|
||||||
|
def test_multiple_types(self, project, wfj_artifacts):
|
||||||
|
project_update = project.create_unified_job()
|
||||||
|
WorkflowJobNode.objects.create(workflow_job=wfj_artifacts, unified_job_template=project, job=project_update)
|
||||||
|
|
||||||
|
assert wfj_artifacts.get_effective_artifacts() == {'foooo': 'bar'}
|
||||||
|
|
||||||
|
def test_precedence_based_on_time(self, wfj_artifacts, job_template):
|
||||||
|
later_job = job_template.create_unified_job(
|
||||||
|
_eager_fields=dict(artifacts={'foooo': 'zoo'}, status='successful', finished=now()) # finished later, should win
|
||||||
|
)
|
||||||
|
WorkflowJobNode.objects.create(workflow_job=wfj_artifacts, unified_job_template=job_template, job=later_job)
|
||||||
|
|
||||||
|
assert wfj_artifacts.get_effective_artifacts() == {'foooo': 'zoo'}
|
||||||
|
|
||||||
|
def test_bad_data_with_artifacts(self, organization):
|
||||||
|
# This is toxic database data, this tests that it doesn't create an infinite loop
|
||||||
|
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='child')
|
||||||
|
wfj = WorkflowJob.objects.create(workflow_job_template=wfjt, launch_type='workflow')
|
||||||
|
WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=wfjt, job=wfj)
|
||||||
|
job = Job.objects.create(artifacts={'foo': 'bar'}, status='successful')
|
||||||
|
WorkflowJobNode.objects.create(workflow_job=wfj, job=job)
|
||||||
|
# mostly, we just care that this assertion finishes in finite time
|
||||||
|
assert wfj.get_effective_artifacts() == {'foo': 'bar'}
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ import os
|
|||||||
import tempfile
|
import tempfile
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
from awx.main.tasks.jobs import RunProjectUpdate, RunInventoryUpdate
|
|
||||||
from awx.main.tasks.system import execution_node_health_check, _cleanup_images_and_files
|
from awx.main.tasks.system import execution_node_health_check, _cleanup_images_and_files
|
||||||
from awx.main.models import ProjectUpdate, InventoryUpdate, InventorySource, Instance, Job
|
from awx.main.models import Instance, Job
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -27,63 +26,6 @@ def test_no_worker_info_on_AWX_nodes(node_type):
|
|||||||
execution_node_health_check(hostname)
|
execution_node_health_check(hostname)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
|
||||||
class TestDependentInventoryUpdate:
|
|
||||||
def test_dependent_inventory_updates_is_called(self, scm_inventory_source, scm_revision_file, mock_me):
|
|
||||||
task = RunProjectUpdate()
|
|
||||||
task.revision_path = scm_revision_file
|
|
||||||
proj_update = scm_inventory_source.source_project.create_project_update()
|
|
||||||
with mock.patch.object(RunProjectUpdate, '_update_dependent_inventories') as inv_update_mck:
|
|
||||||
with mock.patch.object(RunProjectUpdate, 'release_lock'):
|
|
||||||
task.post_run_hook(proj_update, 'successful')
|
|
||||||
inv_update_mck.assert_called_once_with(proj_update, mock.ANY)
|
|
||||||
|
|
||||||
def test_no_unwanted_dependent_inventory_updates(self, project, scm_revision_file, mock_me):
|
|
||||||
task = RunProjectUpdate()
|
|
||||||
task.revision_path = scm_revision_file
|
|
||||||
proj_update = project.create_project_update()
|
|
||||||
with mock.patch.object(RunProjectUpdate, '_update_dependent_inventories') as inv_update_mck:
|
|
||||||
with mock.patch.object(RunProjectUpdate, 'release_lock'):
|
|
||||||
task.post_run_hook(proj_update, 'successful')
|
|
||||||
assert not inv_update_mck.called
|
|
||||||
|
|
||||||
def test_dependent_inventory_updates(self, scm_inventory_source, default_instance_group, mock_me):
|
|
||||||
task = RunProjectUpdate()
|
|
||||||
scm_inventory_source.scm_last_revision = ''
|
|
||||||
proj_update = ProjectUpdate.objects.create(project=scm_inventory_source.source_project)
|
|
||||||
with mock.patch.object(RunInventoryUpdate, 'run') as iu_run_mock:
|
|
||||||
with mock.patch('awx.main.tasks.jobs.create_partition'):
|
|
||||||
task._update_dependent_inventories(proj_update, [scm_inventory_source])
|
|
||||||
assert InventoryUpdate.objects.count() == 1
|
|
||||||
inv_update = InventoryUpdate.objects.first()
|
|
||||||
iu_run_mock.assert_called_once_with(inv_update.id)
|
|
||||||
assert inv_update.source_project_update_id == proj_update.pk
|
|
||||||
|
|
||||||
def test_dependent_inventory_project_cancel(self, project, inventory, default_instance_group, mock_me):
|
|
||||||
"""
|
|
||||||
Test that dependent inventory updates exhibit good behavior on cancel
|
|
||||||
of the source project update
|
|
||||||
"""
|
|
||||||
task = RunProjectUpdate()
|
|
||||||
proj_update = ProjectUpdate.objects.create(project=project)
|
|
||||||
|
|
||||||
kwargs = dict(source_project=project, source='scm', source_path='inventory_file', update_on_project_update=True, inventory=inventory)
|
|
||||||
|
|
||||||
is1 = InventorySource.objects.create(name="test-scm-inv", **kwargs)
|
|
||||||
is2 = InventorySource.objects.create(name="test-scm-inv2", **kwargs)
|
|
||||||
|
|
||||||
def user_cancels_project(pk):
|
|
||||||
ProjectUpdate.objects.all().update(cancel_flag=True)
|
|
||||||
|
|
||||||
with mock.patch.object(RunInventoryUpdate, 'run') as iu_run_mock:
|
|
||||||
with mock.patch('awx.main.tasks.jobs.create_partition'):
|
|
||||||
iu_run_mock.side_effect = user_cancels_project
|
|
||||||
task._update_dependent_inventories(proj_update, [is1, is2])
|
|
||||||
# Verify that it bails after 1st update, detecting a cancel
|
|
||||||
assert is2.inventory_updates.count() == 0
|
|
||||||
iu_run_mock.assert_called_once()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_job_folder(request):
|
def mock_job_folder(request):
|
||||||
pdd_path = tempfile.mkdtemp(prefix='awx_123_')
|
pdd_path = tempfile.mkdtemp(prefix='awx_123_')
|
||||||
|
|||||||
@@ -69,21 +69,21 @@ class TestJobTemplateLabelList:
|
|||||||
|
|
||||||
class TestInventoryInventorySourcesUpdate:
|
class TestInventoryInventorySourcesUpdate:
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"can_update, can_access, is_source, is_up_on_proj, expected",
|
"can_update, can_access, is_source, expected",
|
||||||
[
|
[
|
||||||
(True, True, "ec2", False, [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
(True, True, "ec2", [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
||||||
(False, True, "gce", False, [{'status': 'Could not start because `can_update` returned False', 'inventory_source': 1}]),
|
(False, True, "gce", [{'status': 'Could not start because `can_update` returned False', 'inventory_source': 1}]),
|
||||||
(True, False, "scm", True, [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
(True, False, "scm", [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_post(self, mocker, can_update, can_access, is_source, is_up_on_proj, expected):
|
def test_post(self, mocker, can_update, can_access, is_source, expected):
|
||||||
class InventoryUpdate:
|
class InventoryUpdate:
|
||||||
id = 1
|
id = 1
|
||||||
|
|
||||||
class Project:
|
class Project:
|
||||||
name = 'project'
|
name = 'project'
|
||||||
|
|
||||||
InventorySource = namedtuple('InventorySource', ['source', 'update_on_project_update', 'pk', 'can_update', 'update', 'source_project'])
|
InventorySource = namedtuple('InventorySource', ['source', 'pk', 'can_update', 'update', 'source_project'])
|
||||||
|
|
||||||
class InventorySources(object):
|
class InventorySources(object):
|
||||||
def all(self):
|
def all(self):
|
||||||
@@ -92,7 +92,6 @@ class TestInventoryInventorySourcesUpdate:
|
|||||||
pk=1,
|
pk=1,
|
||||||
source=is_source,
|
source=is_source,
|
||||||
source_project=Project,
|
source_project=Project,
|
||||||
update_on_project_update=is_up_on_proj,
|
|
||||||
can_update=can_update,
|
can_update=can_update,
|
||||||
update=lambda: InventoryUpdate,
|
update=lambda: InventoryUpdate,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,28 +1,13 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from unittest import mock
|
|
||||||
|
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
|
|
||||||
from awx.main.models import (
|
from awx.main.models import (
|
||||||
UnifiedJob,
|
|
||||||
InventoryUpdate,
|
InventoryUpdate,
|
||||||
InventorySource,
|
InventorySource,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_cancel(mocker):
|
|
||||||
with mock.patch.object(UnifiedJob, 'cancel', return_value=True) as parent_cancel:
|
|
||||||
iu = InventoryUpdate()
|
|
||||||
|
|
||||||
iu.save = mocker.MagicMock()
|
|
||||||
build_job_explanation_mock = mocker.MagicMock()
|
|
||||||
iu._build_job_explanation = mocker.MagicMock(return_value=build_job_explanation_mock)
|
|
||||||
|
|
||||||
iu.cancel()
|
|
||||||
|
|
||||||
parent_cancel.assert_called_with(is_chain=False, job_explanation=None)
|
|
||||||
|
|
||||||
|
|
||||||
def test__build_job_explanation():
|
def test__build_job_explanation():
|
||||||
iu = InventoryUpdate(id=3, name='I_am_an_Inventory_Update')
|
iu = InventoryUpdate(id=3, name='I_am_an_Inventory_Update')
|
||||||
|
|
||||||
@@ -53,9 +38,3 @@ class TestControlledBySCM:
|
|||||||
|
|
||||||
with pytest.raises(ValidationError):
|
with pytest.raises(ValidationError):
|
||||||
inv_src.clean_source_path()
|
inv_src.clean_source_path()
|
||||||
|
|
||||||
def test_clean_update_on_launch_update_on_project_update(self):
|
|
||||||
inv_src = InventorySource(update_on_project_update=True, update_on_launch=True, source='scm')
|
|
||||||
|
|
||||||
with pytest.raises(ValidationError):
|
|
||||||
inv_src.clean_update_on_launch()
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from awx.main.tasks.callback import RunnerCallback
|
from awx.main.tasks.callback import RunnerCallback
|
||||||
from awx.main.constants import ANSIBLE_RUNNER_NEEDS_UPDATE_MESSAGE
|
from awx.main.constants import ANSIBLE_RUNNER_NEEDS_UPDATE_MESSAGE
|
||||||
|
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
|
||||||
def test_delay_update(mock_me):
|
def test_delay_update(mock_me):
|
||||||
|
|||||||
50
awx/main/tests/unit/tasks/test_signals.py
Normal file
50
awx/main/tests/unit/tasks/test_signals.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import signal
|
||||||
|
|
||||||
|
from awx.main.tasks.signals import signal_state, signal_callback, with_signal_handling
|
||||||
|
|
||||||
|
|
||||||
|
def test_outer_inner_signal_handling():
|
||||||
|
"""
|
||||||
|
Even if the flag is set in the outer context, its value should persist in the inner context
|
||||||
|
"""
|
||||||
|
|
||||||
|
@with_signal_handling
|
||||||
|
def f2():
|
||||||
|
assert signal_callback()
|
||||||
|
|
||||||
|
@with_signal_handling
|
||||||
|
def f1():
|
||||||
|
assert signal_callback() is False
|
||||||
|
signal_state.set_flag()
|
||||||
|
assert signal_callback()
|
||||||
|
f2()
|
||||||
|
|
||||||
|
original_sigterm = signal.getsignal(signal.SIGTERM)
|
||||||
|
assert signal_callback() is False
|
||||||
|
f1()
|
||||||
|
assert signal_callback() is False
|
||||||
|
assert signal.getsignal(signal.SIGTERM) is original_sigterm
|
||||||
|
|
||||||
|
|
||||||
|
def test_inner_outer_signal_handling():
|
||||||
|
"""
|
||||||
|
Even if the flag is set in the inner context, its value should persist in the outer context
|
||||||
|
"""
|
||||||
|
|
||||||
|
@with_signal_handling
|
||||||
|
def f2():
|
||||||
|
assert signal_callback() is False
|
||||||
|
signal_state.set_flag()
|
||||||
|
assert signal_callback()
|
||||||
|
|
||||||
|
@with_signal_handling
|
||||||
|
def f1():
|
||||||
|
assert signal_callback() is False
|
||||||
|
f2()
|
||||||
|
assert signal_callback()
|
||||||
|
|
||||||
|
original_sigterm = signal.getsignal(signal.SIGTERM)
|
||||||
|
assert signal_callback() is False
|
||||||
|
f1()
|
||||||
|
assert signal_callback() is False
|
||||||
|
assert signal.getsignal(signal.SIGTERM) is original_sigterm
|
||||||
@@ -922,7 +922,8 @@ class TestJobCredentials(TestJobExecution):
|
|||||||
assert env['AWS_SECURITY_TOKEN'] == 'token'
|
assert env['AWS_SECURITY_TOKEN'] == 'token'
|
||||||
assert safe_env['AWS_SECRET_ACCESS_KEY'] == HIDDEN_PASSWORD
|
assert safe_env['AWS_SECRET_ACCESS_KEY'] == HIDDEN_PASSWORD
|
||||||
|
|
||||||
def test_gce_credentials(self, private_data_dir, job, mock_me):
|
@pytest.mark.parametrize("cred_env_var", ['GCE_CREDENTIALS_FILE_PATH', 'GOOGLE_APPLICATION_CREDENTIALS'])
|
||||||
|
def test_gce_credentials(self, cred_env_var, private_data_dir, job, mock_me):
|
||||||
gce = CredentialType.defaults['gce']()
|
gce = CredentialType.defaults['gce']()
|
||||||
credential = Credential(pk=1, credential_type=gce, inputs={'username': 'bob', 'project': 'some-project', 'ssh_key_data': self.EXAMPLE_PRIVATE_KEY})
|
credential = Credential(pk=1, credential_type=gce, inputs={'username': 'bob', 'project': 'some-project', 'ssh_key_data': self.EXAMPLE_PRIVATE_KEY})
|
||||||
credential.inputs['ssh_key_data'] = encrypt_field(credential, 'ssh_key_data')
|
credential.inputs['ssh_key_data'] = encrypt_field(credential, 'ssh_key_data')
|
||||||
@@ -931,7 +932,7 @@ class TestJobCredentials(TestJobExecution):
|
|||||||
env = {}
|
env = {}
|
||||||
safe_env = {}
|
safe_env = {}
|
||||||
credential.credential_type.inject_credential(credential, env, safe_env, [], private_data_dir)
|
credential.credential_type.inject_credential(credential, env, safe_env, [], private_data_dir)
|
||||||
runner_path = env['GCE_CREDENTIALS_FILE_PATH']
|
runner_path = env[cred_env_var]
|
||||||
local_path = to_host_path(runner_path, private_data_dir)
|
local_path = to_host_path(runner_path, private_data_dir)
|
||||||
json_data = json.load(open(local_path, 'rb'))
|
json_data = json.load(open(local_path, 'rb'))
|
||||||
assert json_data['type'] == 'service_account'
|
assert json_data['type'] == 'service_account'
|
||||||
@@ -1316,6 +1317,7 @@ class TestJobCredentials(TestJobExecution):
|
|||||||
assert env['AZURE_AD_USER'] == 'bob'
|
assert env['AZURE_AD_USER'] == 'bob'
|
||||||
assert env['AZURE_PASSWORD'] == 'secret'
|
assert env['AZURE_PASSWORD'] == 'secret'
|
||||||
|
|
||||||
|
# Because this is testing a mix of multiple cloud creds, we are not going to test the GOOGLE_APPLICATION_CREDENTIALS here
|
||||||
path = to_host_path(env['GCE_CREDENTIALS_FILE_PATH'], private_data_dir)
|
path = to_host_path(env['GCE_CREDENTIALS_FILE_PATH'], private_data_dir)
|
||||||
json_data = json.load(open(path, 'rb'))
|
json_data = json.load(open(path, 'rb'))
|
||||||
assert json_data['type'] == 'service_account'
|
assert json_data['type'] == 'service_account'
|
||||||
@@ -1645,7 +1647,8 @@ class TestInventoryUpdateCredentials(TestJobExecution):
|
|||||||
|
|
||||||
assert safe_env['AZURE_PASSWORD'] == HIDDEN_PASSWORD
|
assert safe_env['AZURE_PASSWORD'] == HIDDEN_PASSWORD
|
||||||
|
|
||||||
def test_gce_source(self, inventory_update, private_data_dir, mocker, mock_me):
|
@pytest.mark.parametrize("cred_env_var", ['GCE_CREDENTIALS_FILE_PATH', 'GOOGLE_APPLICATION_CREDENTIALS'])
|
||||||
|
def test_gce_source(self, cred_env_var, inventory_update, private_data_dir, mocker, mock_me):
|
||||||
task = jobs.RunInventoryUpdate()
|
task = jobs.RunInventoryUpdate()
|
||||||
task.instance = inventory_update
|
task.instance = inventory_update
|
||||||
gce = CredentialType.defaults['gce']()
|
gce = CredentialType.defaults['gce']()
|
||||||
@@ -1669,7 +1672,7 @@ class TestInventoryUpdateCredentials(TestJobExecution):
|
|||||||
credential.credential_type.inject_credential(credential, env, safe_env, [], private_data_dir)
|
credential.credential_type.inject_credential(credential, env, safe_env, [], private_data_dir)
|
||||||
|
|
||||||
assert env['GCE_ZONE'] == expected_gce_zone
|
assert env['GCE_ZONE'] == expected_gce_zone
|
||||||
json_data = json.load(open(env['GCE_CREDENTIALS_FILE_PATH'], 'rb'))
|
json_data = json.load(open(env[cred_env_var], 'rb'))
|
||||||
assert json_data['type'] == 'service_account'
|
assert json_data['type'] == 'service_account'
|
||||||
assert json_data['private_key'] == self.EXAMPLE_PRIVATE_KEY
|
assert json_data['private_key'] == self.EXAMPLE_PRIVATE_KEY
|
||||||
assert json_data['client_email'] == 'bob'
|
assert json_data['client_email'] == 'bob'
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from django.db import transaction, DatabaseError, InterfaceError
|
|||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
from awx.main.tasks.signals import signal_callback
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger('awx.main.tasks.utils')
|
logger = logging.getLogger('awx.main.tasks.utils')
|
||||||
|
|
||||||
@@ -37,7 +39,10 @@ def update_model(model, pk, _attempt=0, _max_attempts=5, select_for_update=False
|
|||||||
# Attempt to retry the update, assuming we haven't already
|
# Attempt to retry the update, assuming we haven't already
|
||||||
# tried too many times.
|
# tried too many times.
|
||||||
if _attempt < _max_attempts:
|
if _attempt < _max_attempts:
|
||||||
time.sleep(5)
|
for i in range(5):
|
||||||
|
time.sleep(1)
|
||||||
|
if signal_callback():
|
||||||
|
raise RuntimeError(f'Could not fetch {pk} because of receiving abort signal')
|
||||||
return update_model(model, pk, _attempt=_attempt + 1, _max_attempts=_max_attempts, **updates)
|
return update_model(model, pk, _attempt=_attempt + 1, _max_attempts=_max_attempts, **updates)
|
||||||
else:
|
else:
|
||||||
logger.error('Failed to update %s after %d retries.', model._meta.object_name, _attempt)
|
logger.error('Failed to update %s after %d retries.', model._meta.object_name, _attempt)
|
||||||
|
|||||||
391
awx/ui/SEARCH.md
391
awx/ui/SEARCH.md
@@ -2,26 +2,27 @@
|
|||||||
|
|
||||||
## UX Considerations
|
## UX Considerations
|
||||||
|
|
||||||
Historically, the code that powers search in the AngularJS version of the AWX UI is very complex and prone to bugs. In order to reduce that complexity, we've made some UX decisions to help make the code easier to maintain.
|
Historically, the code that powers search in the AngularJS version of the AWX UI is very complex and prone to bugs. In order to reduce that complexity, we've made some UX decisions to help make the code easier to maintain.
|
||||||
|
|
||||||
**ALL query params namespaced and in url bar**
|
**ALL query params namespaced and in url bar**
|
||||||
|
|
||||||
This includes lists that aren't necessarily hyperlinked, like lookup lists. The reason behind this is so we can treat the url bar as the source of truth for queries always. Any params that have both a key AND value that is in the defaultParams section of the qs config are stripped out of the search string (see "Encoding for UI vs. API" for more info on this point)
|
This includes lists that aren't necessarily hyperlinked, like lookup lists. The reason behind this is so we can treat the url bar as the source of truth for queries always. Any params that have both a key AND value that is in the defaultParams section of the qs config are stripped out of the search string (see "Encoding for UI vs. API" for more info on this point)
|
||||||
|
|
||||||
**Django fuzzy search (`?search=`) is not accessible outside of "advanced search"**
|
**Django fuzzy search (`?search=`) is not accessible outside of "advanced search"**
|
||||||
|
|
||||||
In current smart search typing a term with no key utilizes `?search=` i.e. for "foo" tag, `?search=foo` is given. `?search=` looks on a static list of field name "guesses" (such as name, description, etc.), as well as specific fields as defined for each endpoint (for example, the events endpoint looks for a "stdout" field as well). Due to the fact a key will always be present on the left-hand of simple search, it doesn't make sense to use `?search=` as the default.
|
In current smart search typing a term with no key utilizes `?search=` i.e. for "foo" tag, `?search=foo` is given. `?search=` looks on a static list of field name "guesses" (such as name, description, etc.), as well as specific fields as defined for each endpoint (for example, the events endpoint looks for a "stdout" field as well). Due to the fact a key will always be present on the left-hand of simple search, it doesn't make sense to use `?search=` as the default.
|
||||||
|
|
||||||
|
We may allow passing of `?search=` through our future advanced search interface. Some details that were gathered in planning phases about `?search=` that might be helpful in the future:
|
||||||
|
|
||||||
We may allow passing of `?search=` through our future advanced search interface. Some details that were gathered in planning phases about `?search=` that might be helpful in the future:
|
|
||||||
- `?search=` tags are OR'd together (union is returned).
|
- `?search=` tags are OR'd together (union is returned).
|
||||||
- `?search=foo&name=bar` returns items that have a name field of bar (not case insensitive) AND some text field with foo on it
|
- `?search=foo&name=bar` returns items that have a name field of bar (not case insensitive) AND some text field with foo on it
|
||||||
- `?search=foo&search=bar&name=baz` returns (foo in name OR foo in description OR ...) AND (bar in name OR bar in description OR ...) AND (baz in name)
|
- `?search=foo&search=bar&name=baz` returns (foo in name OR foo in description OR ...) AND (bar in name OR bar in description OR ...) AND (baz in name)
|
||||||
- similarly `?related__search=` looks on the static list of "guesses" for models related to the endpoint. The specific fields are not "searched" for `?related__search=`.
|
- similarly `?related__search=` looks on the static list of "guesses" for models related to the endpoint. The specific fields are not "searched" for `?related__search=`.
|
||||||
- `?related__search=` not currently used in awx ui
|
- `?related__search=` not currently used in awx ui
|
||||||
|
|
||||||
**A note on clicking a tag to putting it back into the search bar**
|
**A note on clicking a tag to putting it back into the search bar**
|
||||||
|
|
||||||
This was brought up as a nice to have when we were discussing our initial implementation of search in the new application. Since there isn't a way we would be able to know if the user created the tag from the simple or advanced search interface, we wouldn't know where to put it back. This breaks our idea of using the query params as the exclusive source of truth, so we've decided against implementing it for now.
|
This was brought up as a nice to have when we were discussing our initial implementation of search in the new application. Since there isn't a way we would be able to know if the user created the tag from the simple or advanced search interface, we wouldn't know where to put it back. This breaks our idea of using the query params as the exclusive source of truth, so we've decided against implementing it for now.
|
||||||
|
|
||||||
## Tasklist
|
## Tasklist
|
||||||
|
|
||||||
@@ -50,171 +51,197 @@ This was brought up as a nice to have when we were discussing our initial implem
|
|||||||
- DONE remove button for search tags of duplicate keys are broken, fix that
|
- DONE remove button for search tags of duplicate keys are broken, fix that
|
||||||
|
|
||||||
### TODO pre-holiday break
|
### TODO pre-holiday break
|
||||||
|
|
||||||
- Update COLUMNS to SORT_COLUMNS and SEARCH_COLUMNS
|
- Update COLUMNS to SORT_COLUMNS and SEARCH_COLUMNS
|
||||||
- Update to using new PF Toolbar component (currently an experimental component)
|
- Update to using new PF Toolbar component (currently an experimental component)
|
||||||
- Change the right-hand input based on the type of key selected on the left-hand side. In addition to text input, for our MVP we will support:
|
- Change the right-hand input based on the type of key selected on the left-hand side. In addition to text input, for our MVP we will support:
|
||||||
- number input
|
- number input
|
||||||
- select input (multiple-choice configured from UI or Options)
|
- select input (multiple-choice configured from UI or Options)
|
||||||
- Update the following lists to have the following keys:
|
- Update the following lists to have the following keys:
|
||||||
|
|
||||||
**Jobs list** (signed off earlier in chat)
|
**Jobs list** (signed off earlier in chat)
|
||||||
- Name (which is also the name of the job template) - search is ?name=jt
|
|
||||||
- Job ID - search is ?id=13
|
- Name (which is also the name of the job template) - search is ?name=jt
|
||||||
- Label name - search is ?labels__name=foo
|
- Job ID - search is ?id=13
|
||||||
- Job type (dropdown on right with the different types) ?type = job
|
- Label name - search is ?labels\_\_name=foo
|
||||||
- Created by (username) - search is ?created_by__username=admin
|
- Job type (dropdown on right with the different types) ?type = job
|
||||||
- Status - search (dropdown on right with different statuses) is ?status=successful
|
- Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- Status - search (dropdown on right with different statuses) is ?status=successful
|
||||||
|
|
||||||
Instances of jobs list include:
|
Instances of jobs list include:
|
||||||
- Jobs list
|
|
||||||
- Host completed jobs list
|
- Jobs list
|
||||||
- JT completed jobs list
|
- Host completed jobs list
|
||||||
|
- JT completed jobs list
|
||||||
|
|
||||||
**Organization list**
|
**Organization list**
|
||||||
- Name - search is ?name=org
|
|
||||||
- ? Team name (of a team in the org) - search is ?teams__name=ansible
|
- Name - search is ?name=org
|
||||||
- ? Username (of a user in the org) - search is ?users__username=johndoe
|
- ? Team name (of a team in the org) - search is ?teams\_\_name=ansible
|
||||||
|
- ? Username (of a user in the org) - search is ?users\_\_username=johndoe
|
||||||
|
|
||||||
Instances of orgs list include:
|
Instances of orgs list include:
|
||||||
- Orgs list
|
|
||||||
- User orgs list
|
- Orgs list
|
||||||
- Lookup on Project
|
- User orgs list
|
||||||
- Lookup on Credential
|
- Lookup on Project
|
||||||
- Lookup on Inventory
|
- Lookup on Credential
|
||||||
- User access add wizard list
|
- Lookup on Inventory
|
||||||
- Team access add wizard list
|
- User access add wizard list
|
||||||
|
- Team access add wizard list
|
||||||
|
|
||||||
**Instance Groups list**
|
**Instance Groups list**
|
||||||
- Name - search is ?name=ig
|
|
||||||
- ? is_container_group boolean choice (doesn't work right now in API but will soon) - search is ?is_container_group=true
|
- Name - search is ?name=ig
|
||||||
- ? credential name - search is ?credentials__name=kubey
|
- ? is_container_group boolean choice (doesn't work right now in API but will soon) - search is ?is_container_group=true
|
||||||
|
- ? credential name - search is ?credentials\_\_name=kubey
|
||||||
|
|
||||||
Instance of instance groups list include:
|
Instance of instance groups list include:
|
||||||
- Lookup on Org
|
|
||||||
- Lookup on JT
|
- Lookup on Org
|
||||||
- Lookup on Inventory
|
- Lookup on JT
|
||||||
|
- Lookup on Inventory
|
||||||
|
|
||||||
**Users list**
|
**Users list**
|
||||||
- Username - search is ?username=johndoe
|
|
||||||
- First Name - search is ?first_name=John
|
- Username - search is ?username=johndoe
|
||||||
- Last Name - search is ?last_name=Doe
|
- First Name - search is ?first_name=John
|
||||||
- ? (if not superfluous, would not include on Team users list) Team Name - search is ?teams__name=team_of_john_does (note API issue: User has no field named "teams")
|
- Last Name - search is ?last_name=Doe
|
||||||
- ? (only for access or permissions list) Role Name - search is ?roles__name=Admin (note API issue: Role has no field "name")
|
- ? (if not superfluous, would not include on Team users list) Team Name - search is ?teams\_\_name=team_of_john_does (note API issue: User has no field named "teams")
|
||||||
- ? (if not superfluous, would not include on Organization users list) ORg Name - search is ?organizations__name=org_of_jhn_does
|
- ? (only for access or permissions list) Role Name - search is ?roles\_\_name=Admin (note API issue: Role has no field "name")
|
||||||
|
- ? (if not superfluous, would not include on Organization users list) ORg Name - search is ?organizations\_\_name=org_of_jhn_does
|
||||||
|
|
||||||
Instance of user lists include:
|
Instance of user lists include:
|
||||||
- User list
|
|
||||||
- Org user list
|
- User list
|
||||||
- Access list for Org, JT, Project, Credential, Inventory, User and Team
|
- Org user list
|
||||||
- Access list for JT
|
- Access list for Org, JT, Project, Credential, Inventory, User and Team
|
||||||
- Access list Project
|
- Access list for JT
|
||||||
- Access list for Credential
|
- Access list Project
|
||||||
- Access list for Inventory
|
- Access list for Credential
|
||||||
- Access list for User
|
- Access list for Inventory
|
||||||
- Access list for Team
|
- Access list for User
|
||||||
- Team add users list
|
- Access list for Team
|
||||||
- Users list in access wizard (to add new roles for a particular list) for Org
|
- Team add users list
|
||||||
- Users list in access wizard (to add new roles for a particular list) for JT
|
- Users list in access wizard (to add new roles for a particular list) for Org
|
||||||
- Users list in access wizard (to add new roles for a particular list) for Project
|
- Users list in access wizard (to add new roles for a particular list) for JT
|
||||||
- Users list in access wizard (to add new roles for a particular list) for Credential
|
- Users list in access wizard (to add new roles for a particular list) for Project
|
||||||
- Users list in access wizard (to add new roles for a particular list) for Inventory
|
- Users list in access wizard (to add new roles for a particular list) for Credential
|
||||||
|
- Users list in access wizard (to add new roles for a particular list) for Inventory
|
||||||
|
|
||||||
**Teams list**
|
**Teams list**
|
||||||
- Name - search is ?name=teamname
|
|
||||||
- ? Username (of a user in the team) - search is ?users__username=johndoe
|
- Name - search is ?name=teamname
|
||||||
- ? (if not superfluous, would not include on Organizations teams list) Org Name - search is ?organizations__name=org_of_john_does
|
- ? Username (of a user in the team) - search is ?users\_\_username=johndoe
|
||||||
|
- ? (if not superfluous, would not include on Organizations teams list) Org Name - search is ?organizations\_\_name=org_of_john_does
|
||||||
|
|
||||||
Instance of team lists include:
|
Instance of team lists include:
|
||||||
- Team list
|
|
||||||
- Org team list
|
- Team list
|
||||||
- User team list
|
- Org team list
|
||||||
- Team list in access wizard (to add new roles for a particular list) for Org
|
- User team list
|
||||||
- Team list in access wizard (to add new roles for a particular list) for JT
|
- Team list in access wizard (to add new roles for a particular list) for Org
|
||||||
- Team list in access wizard (to add new roles for a particular list) for Project
|
- Team list in access wizard (to add new roles for a particular list) for JT
|
||||||
- Team list in access wizard (to add new roles for a particular list) for Credential
|
- Team list in access wizard (to add new roles for a particular list) for Project
|
||||||
- Team list in access wizard (to add new roles for a particular list) for Inventory
|
- Team list in access wizard (to add new roles for a particular list) for Credential
|
||||||
|
- Team list in access wizard (to add new roles for a particular list) for Inventory
|
||||||
|
|
||||||
**Credentials list**
|
**Credentials list**
|
||||||
- Name
|
|
||||||
- ? Type (dropdown on right with different types)
|
- Name
|
||||||
- ? Created by (username)
|
- ? Type (dropdown on right with different types)
|
||||||
- ? Modified by (username)
|
- ? Created by (username)
|
||||||
|
- ? Modified by (username)
|
||||||
|
|
||||||
Instance of credential lists include:
|
Instance of credential lists include:
|
||||||
- Credential list
|
|
||||||
- Lookup for JT
|
- Credential list
|
||||||
- Lookup for Project
|
- Lookup for JT
|
||||||
- User access add wizard list
|
- Lookup for Project
|
||||||
- Team access add wizard list
|
- User access add wizard list
|
||||||
|
- Team access add wizard list
|
||||||
|
|
||||||
**Projects list**
|
**Projects list**
|
||||||
- Name - search is ?name=proj
|
|
||||||
- ? Type (dropdown on right with different types) - search is scm_type=git
|
- Name - search is ?name=proj
|
||||||
- ? SCM URL - search is ?scm_url=github.com/ansible/test-playbooks
|
- ? Type (dropdown on right with different types) - search is scm_type=git
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- ? SCM URL - search is ?scm_url=github.com/ansible/test-playbooks
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of project lists include:
|
Instance of project lists include:
|
||||||
- Project list
|
|
||||||
- Lookup for JT
|
- Project list
|
||||||
- User access add wizard list
|
- Lookup for JT
|
||||||
- Team access add wizard list
|
- User access add wizard list
|
||||||
|
- Team access add wizard list
|
||||||
|
|
||||||
**Templates list**
|
**Templates list**
|
||||||
- Name - search is ?name=cleanup
|
|
||||||
- ? Type (dropdown on right with different types) - search is ?type=playbook_run
|
- Name - search is ?name=cleanup
|
||||||
- ? Playbook name - search is ?job_template__playbook=debug.yml
|
- ? Type (dropdown on right with different types) - search is ?type=playbook_run
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- ? Playbook name - search is ?job_template\_\_playbook=debug.yml
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of template lists include:
|
Instance of template lists include:
|
||||||
- Template list
|
|
||||||
- Project Templates list
|
- Template list
|
||||||
|
- Project Templates list
|
||||||
|
|
||||||
**Inventories list**
|
**Inventories list**
|
||||||
- Name - search is ?name=inv
|
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- Name - search is ?name=inv
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of inventory lists include:
|
Instance of inventory lists include:
|
||||||
- Inventory list
|
|
||||||
- Lookup for JT
|
- Inventory list
|
||||||
- User access add wizard list
|
- Lookup for JT
|
||||||
- Team access add wizard list
|
- User access add wizard list
|
||||||
|
- Team access add wizard list
|
||||||
|
|
||||||
**Groups list**
|
**Groups list**
|
||||||
- Name - search is ?name=group_name
|
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- Name - search is ?name=group_name
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of group lists include:
|
Instance of group lists include:
|
||||||
- Group list
|
|
||||||
|
- Group list
|
||||||
|
|
||||||
**Hosts list**
|
**Hosts list**
|
||||||
- Name - search is ?name=hostname
|
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- Name - search is ?name=hostname
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of host lists include:
|
Instance of host lists include:
|
||||||
- Host list
|
|
||||||
|
- Host list
|
||||||
|
|
||||||
**Notifications list**
|
**Notifications list**
|
||||||
- Name - search is ?name=notification_template_name
|
|
||||||
- ? Type (dropdown on right with different types) - search is ?type=slack
|
- Name - search is ?name=notification_template_name
|
||||||
- ? Created by (username) - search is ?created_by__username=admin
|
- ? Type (dropdown on right with different types) - search is ?type=slack
|
||||||
- ? Modified by (username) - search is ?modified_by__username=admin
|
- ? Created by (username) - search is ?created_by\_\_username=admin
|
||||||
|
- ? Modified by (username) - search is ?modified_by\_\_username=admin
|
||||||
|
|
||||||
Instance of notification lists include:
|
Instance of notification lists include:
|
||||||
- Org notification list
|
|
||||||
- JT notification list
|
- Org notification list
|
||||||
- Project notification list
|
- JT notification list
|
||||||
|
- Project notification list
|
||||||
|
|
||||||
### TODO backlog
|
### TODO backlog
|
||||||
- Change the right-hand input based on the type of key selected on the left-hand side. We will eventually want to support:
|
|
||||||
|
- Change the right-hand input based on the type of key selected on the left-hand side. We will eventually want to support:
|
||||||
- lookup input (selection of particular resources, based on API list endpoints)
|
- lookup input (selection of particular resources, based on API list endpoints)
|
||||||
- date picker input
|
- date picker input
|
||||||
- Update the following lists to have the following keys:
|
- Update the following lists to have the following keys:
|
||||||
- Update all __name and __username related field search-based keys to be type-ahead lookup based searches
|
- Update all **name and **username related field search-based keys to be type-ahead lookup based searches
|
||||||
|
|
||||||
## Code Details
|
## Code Details
|
||||||
|
|
||||||
@@ -230,13 +257,13 @@ The component looks like this:
|
|||||||
/>
|
/>
|
||||||
```
|
```
|
||||||
|
|
||||||
**qsConfig** is used to get namespace so that multiple lists can be on the page. When tags are modified they append namespace to query params. The qsConfig is also used to get "type" of fields in order to correctly parse values as int or date as it is translating.
|
**qsConfig** is used to get namespace so that multiple lists can be on the page. When tags are modified they append namespace to query params. The qsConfig is also used to get "type" of fields in order to correctly parse values as int or date as it is translating.
|
||||||
|
|
||||||
**columns** are passed as an array, as defined in the screen where the list is located. You pass a bool `isDefault` to indicate that should be the key that shows up in the left-hand dropdown as default in the UI. If you don't pass any columns, a default of `isDefault=true` will be added to a name column, which is nearly universally shared throughout the models of awx.
|
**columns** are passed as an array, as defined in the screen where the list is located. You pass a bool `isDefault` to indicate that should be the key that shows up in the left-hand dropdown as default in the UI. If you don't pass any columns, a default of `isDefault=true` will be added to a name column, which is nearly universally shared throughout the models of awx.
|
||||||
|
|
||||||
There is a type attribute that can be `'string'`, `'number'` or `'choice'` (and in the future, `'date'` and `'lookup'`), which will change the type of input on the right-hand side of the search bar. For a key that has a set number of choices, you will pass a choices attribute, which is an array in the format choices: [{label: 'Foo', value: 'foo'}]
|
There is a type attribute that can be `'string'`, `'number'` or `'choice'` (and in the future, `'date'` and `'lookup'`), which will change the type of input on the right-hand side of the search bar. For a key that has a set number of choices, you will pass a choices attribute, which is an array in the format choices: [{label: 'Foo', value: 'foo'}]
|
||||||
|
|
||||||
**onSearch** calls the `mergeParams` qs util in order to add new tags to the queryset. mergeParams is used so that we can support duplicate keys (see mergeParams vs. replaceParams for more info).
|
**onSearch** calls the `mergeParams` qs util in order to add new tags to the queryset. mergeParams is used so that we can support duplicate keys (see mergeParams vs. replaceParams for more info).
|
||||||
|
|
||||||
### ListHeader component
|
### ListHeader component
|
||||||
|
|
||||||
@@ -253,15 +280,16 @@ All of these functions act on the react-router history using the `pushHistorySta
|
|||||||
|
|
||||||
**a note on sort_columns and search_columns**
|
**a note on sort_columns and search_columns**
|
||||||
|
|
||||||
We have split out column configuration into separate search and sort column array props--these are passed to the search and sort columns. Both accept an isDefault prop for one of the items in the array to be the default option selected when going to the page. Sort column items can pass an isNumeric boolean in order to chnage the iconography of the sort UI element. Search column items can pass type and if applicable choices, in order to configure the right-hand side of the search bar.
|
We have split out column configuration into separate search and sort column array props--these are passed to the search and sort columns. Both accept an isDefault prop for one of the items in the array to be the default option selected when going to the page. Sort column items can pass an isNumeric boolean in order to chnage the iconography of the sort UI element. Search column items can pass type and if applicable choices, in order to configure the right-hand side of the search bar.
|
||||||
|
|
||||||
### FilterTags component
|
### FilterTags component
|
||||||
|
|
||||||
Similar to the way the list grabs data based on changes to the react-router params, the `FilterTags` component updates when new params are added. This component is a fairly straight-forward map (only slightly complex, because it needed to do a nested map over any values with duplicate keys that were represented by an inner-array). Both key and value are displayed for the tag.
|
Similar to the way the list grabs data based on changes to the react-router params, the `FilterTags` component updates when new params are added. This component is a fairly straight-forward map (only slightly complex, because it needed to do a nested map over any values with duplicate keys that were represented by an inner-array). Both key and value are displayed for the tag.
|
||||||
|
|
||||||
### qs utility
|
### qs utility
|
||||||
|
|
||||||
The qs (queryset) utility is used to make the search speak the language of the REST API. The main functions of the utilities are to:
|
The qs (queryset) utility is used to make the search speak the language of the REST API. The main functions of the utilities are to:
|
||||||
|
|
||||||
- add, replace and remove filters
|
- add, replace and remove filters
|
||||||
- translate filters as url params (for linking and maintaining state), in-memory representation (as JS objects), and params that Django REST Framework understands.
|
- translate filters as url params (for linking and maintaining state), in-memory representation (as JS objects), and params that Django REST Framework understands.
|
||||||
|
|
||||||
@@ -269,7 +297,7 @@ More info in the below sections:
|
|||||||
|
|
||||||
#### Encoding for UI vs. API
|
#### Encoding for UI vs. API
|
||||||
|
|
||||||
For the UI url params, we want to only encode those params that aren't defaults, as the default behavior was defined through configuration and we don't need these in the url as a source of truth. For the API, we need to pass these params so that they are taken into account when the response is built.
|
For the UI url params, we want to only encode those params that aren't defaults, as the default behavior was defined through configuration and we don't need these in the url as a source of truth. For the API, we need to pass these params so that they are taken into account when the response is built.
|
||||||
|
|
||||||
#### mergeParams vs. replaceParams
|
#### mergeParams vs. replaceParams
|
||||||
|
|
||||||
@@ -283,13 +311,13 @@ From a UX perspective, we wanted to be able to support searching on the same key
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Concatenating terms in this way gives you the intersection of both terms (i.e. foo must be "bar" and "baz"). This is helpful for the most-common type of searching, substring (`__icontains`) searches. This will increase filtering, allowing the user to drill-down into the list as terms are added.
|
Concatenating terms in this way gives you the intersection of both terms (i.e. foo must be "bar" and "baz"). This is helpful for the most-common type of searching, substring (`__icontains`) searches. This will increase filtering, allowing the user to drill-down into the list as terms are added.
|
||||||
|
|
||||||
**replaceParams** is used to support sorting, setting page_size, etc. These params only allow one choice, and we need to replace a particular key's value if one is passed.
|
**replaceParams** is used to support sorting, setting page_size, etc. These params only allow one choice, and we need to replace a particular key's value if one is passed.
|
||||||
|
|
||||||
#### Working with REST API
|
#### Working with REST API
|
||||||
|
|
||||||
The REST API is coupled with the qs util through the `paramsSerializer`, due to the fact we need axios to support the array for duplicate key values in the object representation of the params to pass to the get request. This is done where axios is configured in the Base.js file, so all requests and request types should support our array syntax for duplicate keys automatically.
|
The REST API is coupled with the qs util through the `paramsSerializer`, due to the fact we need axios to support the array for duplicate key values in the object representation of the params to pass to the get request. This is done where axios is configured in the Base.js file, so all requests and request types should support our array syntax for duplicate keys automatically.
|
||||||
|
|
||||||
# Advanced Search - this section is a mess, update eventually
|
# Advanced Search - this section is a mess, update eventually
|
||||||
|
|
||||||
@@ -305,85 +333,84 @@ Current thinking is Advanced Search will be post-3.6, or at least late 3.6 after
|
|||||||
|
|
||||||
That being said, we want to plan it out so we make sure the infrastructure of how we set up adding/removing tags, what shows up in the url bar, etc. all doesn't have to be redone.
|
That being said, we want to plan it out so we make sure the infrastructure of how we set up adding/removing tags, what shows up in the url bar, etc. all doesn't have to be redone.
|
||||||
|
|
||||||
Users will get to advanced search with a button to the right of search bar. When selected type-ahead key thing opens, left dropdown of search bar goes away, and x is given to get back to regular search (this is in the mockups)
|
Users will get to advanced search with a button to the right of search bar. When selected type-ahead key thing opens, left dropdown of search bar goes away, and x is given to get back to regular search (this is in the mockups)
|
||||||
|
|
||||||
It is okay to only make this typing representation available initially (i.e. they start doing stuff with the type-ahead and the phases, no more typing in to make a query that way).
|
It is okay to only make this typing representation available initially (i.e. they start doing stuff with the type-ahead and the phases, no more typing in to make a query that way).
|
||||||
|
|
||||||
when you click through or type in the search bar for the various phases of crafting the query ("not", "related resource project", "related resource key name", "value foo") which might be represented in the top bar as a series of tags that can be added and removed before submitting the tag.
|
when you click through or type in the search bar for the various phases of crafting the query ("not", "related resource project", "related resource key name", "value foo") which might be represented in the top bar as a series of tags that can be added and removed before submitting the tag.
|
||||||
|
|
||||||
We will try to form options data from a static file. Because options data is static, we may be able to generate and store as a static file of some sort (that we can use for managing smart search). Alan had ideas around this. If we do this it will mean we don't have to make a ton of requests as we craft smart search filters. It sounds like the cli may start using something similar.
|
We will try to form options data from a static file. Because options data is static, we may be able to generate and store as a static file of some sort (that we can use for managing smart search). Alan had ideas around this. If we do this it will mean we don't have to make a ton of requests as we craft smart search filters. It sounds like the cli may start using something similar.
|
||||||
|
|
||||||
## Smart search flow
|
## Smart search flow
|
||||||
|
|
||||||
Smart search will be able to craft the tag through various states. Note that the phases don't necessarily need to be completed in sequential order.
|
Smart search will be able to craft the tag through various states. Note that the phases don't necessarily need to be completed in sequential order.
|
||||||
|
|
||||||
PHASE 1: prefix operators
|
PHASE 1: prefix operators
|
||||||
|
|
||||||
**TODO: Double check there's no reason we need to include or__ and chain__ and can just do not__**
|
**TODO: Double check there's no reason we need to include or** and chain** and can just do not\_\_**
|
||||||
|
|
||||||
- not__
|
- not\_\_
|
||||||
- or__
|
- or\_\_
|
||||||
- chain__
|
- chain\_\_
|
||||||
|
|
||||||
how these work:
|
how these work:
|
||||||
|
|
||||||
To exclude results matching certain criteria, prefix the field parameter with not__:
|
To exclude results matching certain criteria, prefix the field parameter with not\_\_:
|
||||||
|
|
||||||
?not__field=value
|
?not**field=value
|
||||||
By default, all query string filters are AND'ed together, so only the results matching all filters will be returned. To combine results matching any one of multiple criteria, prefix each query string parameter with or__:
|
By default, all query string filters are AND'ed together, so only the results matching all filters will be returned. To combine results matching any one of multiple criteria, prefix each query string parameter with or**:
|
||||||
|
|
||||||
?or__field=value&or__field=othervalue
|
?or**field=value&or**field=othervalue
|
||||||
?or__not__field=value&or__field=othervalue
|
?or**not**field=value&or**field=othervalue
|
||||||
(Added in Ansible Tower 1.4.5) The default AND filtering applies all filters simultaneously to each related object being filtered across database relationships. The chain filter instead applies filters separately for each related object. To use, prefix the query string parameter with chain__:
|
(Added in Ansible Controller 1.4.5) The default AND filtering applies all filters simultaneously to each related object being filtered across database relationships. The chain filter instead applies filters separately for each related object. To use, prefix the query string parameter with chain**:
|
||||||
|
|
||||||
?chain__related__field=value&chain__related__field2=othervalue
|
?chain**related**field=value&chain**related**field2=othervalue
|
||||||
?chain__not__related__field=value&chain__related__field2=othervalue
|
?chain**not**related**field=value&chain**related**field2=othervalue
|
||||||
If the first query above were written as ?related__field=value&related__field2=othervalue, it would return only the primary objects where the same related object satisfied both conditions. As written using the chain filter, it would return the intersection of primary objects matching each condition.
|
If the first query above were written as ?related**field=value&related\_\_field2=othervalue, it would return only the primary objects where the same related object satisfied both conditions. As written using the chain filter, it would return the intersection of primary objects matching each condition.
|
||||||
|
|
||||||
PHASE 2: related fields, given by array, where __search is appended to them, i.e.
|
PHASE 2: related fields, given by array, where \_\_search is appended to them, i.e.
|
||||||
|
|
||||||
```
|
```
|
||||||
"related_search_fields": [
|
"related_search_fields": [
|
||||||
"credentials__search",
|
"credentials__search",
|
||||||
"labels__search",
|
"labels__search",
|
||||||
"created_by__search",
|
"created_by__search",
|
||||||
"modified_by__search",
|
"modified_by__search",
|
||||||
"notification_templates__search",
|
"notification_templates__search",
|
||||||
"custom_inventory_scripts__search",
|
"custom_inventory_scripts__search",
|
||||||
"notification_templates_error__search",
|
"notification_templates_error__search",
|
||||||
"notification_templates_success__search",
|
"notification_templates_success__search",
|
||||||
"notification_templates_any__search",
|
"notification_templates_any__search",
|
||||||
"teams__search",
|
"teams__search",
|
||||||
"projects__search",
|
"projects__search",
|
||||||
"inventories__search",
|
"inventories__search",
|
||||||
"applications__search",
|
"applications__search",
|
||||||
"workflows__search",
|
"workflows__search",
|
||||||
"instance_groups__search"
|
"instance_groups__search"
|
||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
||||||
PHASE 3: keys, give by object key names for data.actions.GET
|
PHASE 3: keys, give by object key names for data.actions.GET - type is given for each key which we could use to help craft the value
|
||||||
- type is given for each key which we could use to help craft the value
|
|
||||||
|
|
||||||
PHASE 4: after key postfix operators can be
|
PHASE 4: after key postfix operators can be
|
||||||
|
|
||||||
**TODO: will need to figure out which ones we support**
|
**TODO: will need to figure out which ones we support**
|
||||||
|
|
||||||
- exact: Exact match (default lookup if not specified).
|
- exact: Exact match (default lookup if not specified).
|
||||||
- iexact: Case-insensitive version of exact.
|
- iexact: Case-insensitive version of exact.
|
||||||
- contains: Field contains value.
|
- contains: Field contains value.
|
||||||
- icontains: Case-insensitive version of contains.
|
- icontains: Case-insensitive version of contains.
|
||||||
- startswith: Field starts with value.
|
- startswith: Field starts with value.
|
||||||
- istartswith: Case-insensitive version of startswith.
|
- istartswith: Case-insensitive version of startswith.
|
||||||
- endswith: Field ends with value.
|
- endswith: Field ends with value.
|
||||||
- iendswith: Case-insensitive version of endswith.
|
- iendswith: Case-insensitive version of endswith.
|
||||||
- regex: Field matches the given regular expression.
|
- regex: Field matches the given regular expression.
|
||||||
- iregex: Case-insensitive version of regex.
|
- iregex: Case-insensitive version of regex.
|
||||||
- gt: Greater than comparison.
|
- gt: Greater than comparison.
|
||||||
- gte: Greater than or equal to comparison.
|
- gte: Greater than or equal to comparison.
|
||||||
- lt: Less than comparison.
|
- lt: Less than comparison.
|
||||||
- lte: Less than or equal to comparison.
|
- lte: Less than or equal to comparison.
|
||||||
- isnull: Check whether the given field or related object is null; expects a boolean value.
|
- isnull: Check whether the given field or related object is null; expects a boolean value.
|
||||||
- in: Check whether the given field's value is present in the list provided; expects a list of items.
|
- in: Check whether the given field's value is present in the list provided; expects a list of items.
|
||||||
|
|
||||||
PHASE 5: The value. Based on options, we can give hints or validation based on type of value (like number fields don't accept "foo" or whatever)
|
PHASE 5: The value. Based on options, we can give hints or validation based on type of value (like number fields don't accept "foo" or whatever)
|
||||||
|
|||||||
@@ -2,15 +2,39 @@ This document is meant to provide some guidance into the functionality of Job Ou
|
|||||||
|
|
||||||
## Overview of the feature/screen. Summary of what it does/is
|
## Overview of the feature/screen. Summary of what it does/is
|
||||||
|
|
||||||
1. Elapsed time / unfollow button
|
Joboutput is a feature that allows users to see how their job is doing as it is being run.
|
||||||
2. Page up and page down buttons
|
This feature displays data sent to the UI via websockets that are connected to several
|
||||||
3. Unique qualities of the different job types.
|
different endpoints in the API.
|
||||||
|
|
||||||
- Some don’t allow search by event data and thus Event is not an option in the drop down
|
The job output has 2 different states that result in different functionality. One state
|
||||||
- Some don’t have expand, collapse
|
is when, the job is actively running. There is limited functionality because of how the
|
||||||
|
job events are processed when they reach the UI. While the job is running, and
|
||||||
|
output is coming into the UI, the following features turn off:
|
||||||
|
|
||||||
4. Differences in the output from when a job is running and when a job is complete.
|
1. [Search](#Search)- The ability to search the output of a job.
|
||||||
5. Which features are enabled when it’s running and which aren’t.
|
2. [Expand/Collapse](#Expand/Collapse)- The ability to expand and collapse job events, tasks, plays, or even the
|
||||||
|
job itself. The only part of the job ouput that is not collapsable is the playbook summary (only jobs that
|
||||||
|
are executed from a Job Template have Expand/Collapse functionality).
|
||||||
|
|
||||||
|
The following features are enabled:
|
||||||
|
|
||||||
|
1. Follow/unfollow - `Follow` indicates you are streaming the output on the screen
|
||||||
|
as it comes into the UI. If you see some output that you want to examine closer while the job is running
|
||||||
|
scroll to it, and click `Unfollow`, and the output will stop streaming onto the screen. This feature is only
|
||||||
|
enabled when the job is running and is not complete. If the user scrolls up in the output the UI will unfollow.
|
||||||
|
2. Page up and page down buttons- Use these buttons to navigate quickly up and down the output.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
After the job is complete, the Follow/Unfollow button disabled, and Expand/Collapse and Search become enabled.
|
||||||
|

|
||||||
|
|
||||||
|
Not all job types are created equal. Some jobs have a concept of parent-child events. Job events can be inside a Task,
|
||||||
|
a Task can be inside a Play, and a Play inside a Playbook. Leveraging this concept to enable Expand/Collapse for these
|
||||||
|
job types, allows you to collapse and hide the children of a particular line of output. This parent-child event
|
||||||
|
relationship only exists on jobs executed from a job template. All other types of jobs do not
|
||||||
|
have this event concept, and therefore, do not have Expand/Collapse functionality. By default all job
|
||||||
|
events are expanded.
|
||||||
|
|
||||||
## How output works generally.
|
## How output works generally.
|
||||||
|
|
||||||
@@ -26,11 +50,13 @@ This document is meant to provide some guidance into the functionality of Job Ou
|
|||||||
## Non-standard cases
|
## Non-standard cases
|
||||||
|
|
||||||
1. When an event comes into the output that has a parent, but the parent hasn’t arrived yet.
|
1. When an event comes into the output that has a parent, but the parent hasn’t arrived yet.
|
||||||
2. When an event that has children arrives in output, but the children are not present yet
|
2. When an event with children arrives in output, but the children are not yet present.
|
||||||
|
|
||||||
## Expand collapse a single event- how it works and how it changes the state object
|
## Expand/Collapse
|
||||||
|
|
||||||
## Expand collapse all- how it works and how it changes the state object
|
### Expand collapse a single event - how it works and how it changes the state object
|
||||||
|
|
||||||
|
### Expand collapse all - how it works and how it changes the state object
|
||||||
|
|
||||||
## Search
|
## Search
|
||||||
|
|
||||||
|
|||||||
BIN
awx/ui/docs/images/JobOutput-complete.png
Normal file
BIN
awx/ui/docs/images/JobOutput-complete.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
BIN
awx/ui/docs/images/JobOutput-running.png
Normal file
BIN
awx/ui/docs/images/JobOutput-running.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
785
awx/ui/package-lock.json
generated
785
awx/ui/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -6,29 +6,29 @@
|
|||||||
"node": ">=16.13.1"
|
"node": ">=16.13.1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lingui/react": "3.13.3",
|
"@lingui/react": "3.14.0",
|
||||||
"@patternfly/patternfly": "4.196.7",
|
"@patternfly/patternfly": "4.202.1",
|
||||||
"@patternfly/react-core": "^4.201.0",
|
"@patternfly/react-core": "^4.221.3",
|
||||||
"@patternfly/react-icons": "4.49.19",
|
"@patternfly/react-icons": "4.75.1",
|
||||||
"@patternfly/react-table": "4.83.1",
|
"@patternfly/react-table": "4.93.1",
|
||||||
"ace-builds": "^1.6.0",
|
"ace-builds": "^1.6.0",
|
||||||
"ansi-to-html": "0.7.2",
|
"ansi-to-html": "0.7.2",
|
||||||
"axios": "0.22.0",
|
"axios": "0.27.2",
|
||||||
"codemirror": "^5.65.4",
|
"codemirror": "^6.0.1",
|
||||||
"d3": "7.4.4",
|
"d3": "7.4.4",
|
||||||
"dagre": "^0.8.4",
|
"dagre": "^0.8.4",
|
||||||
"dompurify": "2.3.8",
|
"dompurify": "2.3.8",
|
||||||
"formik": "2.2.9",
|
"formik": "2.2.9",
|
||||||
"has-ansi": "5.0.1",
|
"has-ansi": "5.0.1",
|
||||||
"html-entities": "2.3.2",
|
"html-entities": "2.3.2",
|
||||||
"js-yaml": "^3.13.1",
|
"js-yaml": "4.1.0",
|
||||||
"luxon": "^2.4.0",
|
"luxon": "^2.4.0",
|
||||||
"prop-types": "^15.6.2",
|
"prop-types": "^15.6.2",
|
||||||
"react": "17.0.2",
|
"react": "17.0.2",
|
||||||
"react-ace": "^10.1.0",
|
"react-ace": "^10.1.0",
|
||||||
"react-dom": "17.0.2",
|
"react-dom": "17.0.2",
|
||||||
"react-error-boundary": "^3.1.4",
|
"react-error-boundary": "^3.1.4",
|
||||||
"react-router-dom": "^5.1.2",
|
"react-router-dom": "^5.3.3",
|
||||||
"react-virtualized": "^9.21.1",
|
"react-virtualized": "^9.21.1",
|
||||||
"rrule": "2.7.0",
|
"rrule": "2.7.0",
|
||||||
"styled-components": "5.3.5"
|
"styled-components": "5.3.5"
|
||||||
|
|||||||
@@ -26,13 +26,6 @@ function AdHocCommands({
|
|||||||
const [isWizardOpen, setIsWizardOpen] = useState(false);
|
const [isWizardOpen, setIsWizardOpen] = useState(false);
|
||||||
const { isKebabified, onKebabModalChange } = useContext(KebabifiedContext);
|
const { isKebabified, onKebabModalChange } = useContext(KebabifiedContext);
|
||||||
|
|
||||||
const verbosityOptions = [
|
|
||||||
{ value: '0', key: '0', label: t`0 (Normal)` },
|
|
||||||
{ value: '1', key: '1', label: t`1 (Verbose)` },
|
|
||||||
{ value: '2', key: '2', label: t`2 (More Verbose)` },
|
|
||||||
{ value: '3', key: '3', label: t`3 (Debug)` },
|
|
||||||
{ value: '4', key: '4', label: t`4 (Connection Debug)` },
|
|
||||||
];
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isKebabified) {
|
if (isKebabified) {
|
||||||
onKebabModalChange(isWizardOpen);
|
onKebabModalChange(isWizardOpen);
|
||||||
@@ -159,7 +152,6 @@ function AdHocCommands({
|
|||||||
adHocItems={adHocItems}
|
adHocItems={adHocItems}
|
||||||
organizationId={organizationId}
|
organizationId={organizationId}
|
||||||
moduleOptions={moduleOptions}
|
moduleOptions={moduleOptions}
|
||||||
verbosityOptions={verbosityOptions}
|
|
||||||
credentialTypeId={credentialTypeId}
|
credentialTypeId={credentialTypeId}
|
||||||
onCloseWizard={() => setIsWizardOpen(false)}
|
onCloseWizard={() => setIsWizardOpen(false)}
|
||||||
onLaunch={handleSubmit}
|
onLaunch={handleSubmit}
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ import { t } from '@lingui/macro';
|
|||||||
import { withFormik, useFormikContext } from 'formik';
|
import { withFormik, useFormikContext } from 'formik';
|
||||||
import PropTypes from 'prop-types';
|
import PropTypes from 'prop-types';
|
||||||
|
|
||||||
|
import { VERBOSITY } from 'components/VerbositySelectField';
|
||||||
import Wizard from '../Wizard';
|
import Wizard from '../Wizard';
|
||||||
import useAdHocLaunchSteps from './useAdHocLaunchSteps';
|
import useAdHocLaunchSteps from './useAdHocLaunchSteps';
|
||||||
|
|
||||||
function AdHocCommandsWizard({
|
function AdHocCommandsWizard({
|
||||||
onLaunch,
|
onLaunch,
|
||||||
moduleOptions,
|
moduleOptions,
|
||||||
verbosityOptions,
|
|
||||||
onCloseWizard,
|
onCloseWizard,
|
||||||
credentialTypeId,
|
credentialTypeId,
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -18,7 +18,6 @@ function AdHocCommandsWizard({
|
|||||||
|
|
||||||
const { steps, validateStep, visitStep, visitAllSteps } = useAdHocLaunchSteps(
|
const { steps, validateStep, visitStep, visitAllSteps } = useAdHocLaunchSteps(
|
||||||
moduleOptions,
|
moduleOptions,
|
||||||
verbosityOptions,
|
|
||||||
organizationId,
|
organizationId,
|
||||||
credentialTypeId
|
credentialTypeId
|
||||||
);
|
);
|
||||||
@@ -57,13 +56,13 @@ function AdHocCommandsWizard({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const FormikApp = withFormik({
|
const FormikApp = withFormik({
|
||||||
mapPropsToValues({ adHocItems, verbosityOptions }) {
|
mapPropsToValues({ adHocItems }) {
|
||||||
const adHocItemStrings = adHocItems.map((item) => item.name).join(', ');
|
const adHocItemStrings = adHocItems.map((item) => item.name).join(', ');
|
||||||
return {
|
return {
|
||||||
limit: adHocItemStrings || 'all',
|
limit: adHocItemStrings || 'all',
|
||||||
credentials: [],
|
credentials: [],
|
||||||
module_args: '',
|
module_args: '',
|
||||||
verbosity: verbosityOptions[0].value,
|
verbosity: VERBOSITY()[0],
|
||||||
forks: 0,
|
forks: 0,
|
||||||
diff_mode: false,
|
diff_mode: false,
|
||||||
become_enabled: '',
|
become_enabled: '',
|
||||||
@@ -79,7 +78,6 @@ const FormikApp = withFormik({
|
|||||||
FormikApp.propTypes = {
|
FormikApp.propTypes = {
|
||||||
onLaunch: PropTypes.func.isRequired,
|
onLaunch: PropTypes.func.isRequired,
|
||||||
moduleOptions: PropTypes.arrayOf(PropTypes.array).isRequired,
|
moduleOptions: PropTypes.arrayOf(PropTypes.array).isRequired,
|
||||||
verbosityOptions: PropTypes.arrayOf(PropTypes.object).isRequired,
|
|
||||||
onCloseWizard: PropTypes.func.isRequired,
|
onCloseWizard: PropTypes.func.isRequired,
|
||||||
credentialTypeId: PropTypes.number.isRequired,
|
credentialTypeId: PropTypes.number.isRequired,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,13 +13,6 @@ jest.mock('../../api/models/Credentials');
|
|||||||
jest.mock('../../api/models/ExecutionEnvironments');
|
jest.mock('../../api/models/ExecutionEnvironments');
|
||||||
jest.mock('../../api/models/Root');
|
jest.mock('../../api/models/Root');
|
||||||
|
|
||||||
const verbosityOptions = [
|
|
||||||
{ value: '0', key: '0', label: '0 (Normal)' },
|
|
||||||
{ value: '1', key: '1', label: '1 (Verbose)' },
|
|
||||||
{ value: '2', key: '2', label: '2 (More Verbose)' },
|
|
||||||
{ value: '3', key: '3', label: '3 (Debug)' },
|
|
||||||
{ value: '4', key: '4', label: '4 (Connection Debug)' },
|
|
||||||
];
|
|
||||||
const moduleOptions = [
|
const moduleOptions = [
|
||||||
['command', 'command'],
|
['command', 'command'],
|
||||||
['shell', 'shell'],
|
['shell', 'shell'],
|
||||||
@@ -44,7 +37,6 @@ describe('<AdHocCommandsWizard/>', () => {
|
|||||||
adHocItems={adHocItems}
|
adHocItems={adHocItems}
|
||||||
onLaunch={onLaunch}
|
onLaunch={onLaunch}
|
||||||
moduleOptions={moduleOptions}
|
moduleOptions={moduleOptions}
|
||||||
verbosityOptions={verbosityOptions}
|
|
||||||
onCloseWizard={() => {}}
|
onCloseWizard={() => {}}
|
||||||
credentialTypeId={1}
|
credentialTypeId={1}
|
||||||
organizationId={1}
|
organizationId={1}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Form, FormGroup, Switch, Checkbox } from '@patternfly/react-core';
|
|||||||
import styled from 'styled-components';
|
import styled from 'styled-components';
|
||||||
import { required } from 'util/validators';
|
import { required } from 'util/validators';
|
||||||
import useBrandName from 'hooks/useBrandName';
|
import useBrandName from 'hooks/useBrandName';
|
||||||
|
import { VerbositySelectField } from 'components/VerbositySelectField';
|
||||||
import AnsibleSelect from '../AnsibleSelect';
|
import AnsibleSelect from '../AnsibleSelect';
|
||||||
import FormField from '../FormField';
|
import FormField from '../FormField';
|
||||||
import { VariablesField } from '../CodeEditor';
|
import { VariablesField } from '../CodeEditor';
|
||||||
@@ -21,7 +22,7 @@ const TooltipWrapper = styled.div`
|
|||||||
text-align: left;
|
text-align: left;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
function AdHocDetailsStep({ verbosityOptions, moduleOptions }) {
|
function AdHocDetailsStep({ moduleOptions }) {
|
||||||
const brandName = useBrandName();
|
const brandName = useBrandName();
|
||||||
const [moduleNameField, moduleNameMeta, moduleNameHelpers] = useField({
|
const [moduleNameField, moduleNameMeta, moduleNameHelpers] = useField({
|
||||||
name: 'module_name',
|
name: 'module_name',
|
||||||
@@ -32,7 +33,7 @@ function AdHocDetailsStep({ verbosityOptions, moduleOptions }) {
|
|||||||
const [diffModeField, , diffModeHelpers] = useField('diff_mode');
|
const [diffModeField, , diffModeHelpers] = useField('diff_mode');
|
||||||
const [becomeEnabledField, , becomeEnabledHelpers] =
|
const [becomeEnabledField, , becomeEnabledHelpers] =
|
||||||
useField('become_enabled');
|
useField('become_enabled');
|
||||||
const [verbosityField, verbosityMeta, verbosityHelpers] = useField({
|
const [, verbosityMeta] = useField({
|
||||||
name: 'verbosity',
|
name: 'verbosity',
|
||||||
validate: required(null),
|
validate: required(null),
|
||||||
});
|
});
|
||||||
@@ -122,33 +123,16 @@ function AdHocDetailsStep({ verbosityOptions, moduleOptions }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<FormGroup
|
|
||||||
|
<VerbositySelectField
|
||||||
fieldId="verbosity"
|
fieldId="verbosity"
|
||||||
aria-label={t`select verbosity`}
|
tooltip={t`These are the verbosity levels for standard out of the command run that are supported.`}
|
||||||
label={t`Verbosity`}
|
isValid={
|
||||||
isRequired
|
|
||||||
validated={
|
|
||||||
!verbosityMeta.touched || !verbosityMeta.error
|
!verbosityMeta.touched || !verbosityMeta.error
|
||||||
? 'default'
|
? 'default'
|
||||||
: 'error'
|
: 'error'
|
||||||
}
|
}
|
||||||
helperTextInvalid={verbosityMeta.error}
|
/>
|
||||||
labelIcon={
|
|
||||||
<Popover
|
|
||||||
content={t`These are the verbosity levels for standard out of the command run that are supported.`}
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<AnsibleSelect
|
|
||||||
{...verbosityField}
|
|
||||||
isValid={!verbosityMeta.touched || !verbosityMeta.error}
|
|
||||||
id="verbosity"
|
|
||||||
data={verbosityOptions || []}
|
|
||||||
onChange={(event, value) => {
|
|
||||||
verbosityHelpers.setValue(parseInt(value, 10));
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</FormGroup>
|
|
||||||
<FormField
|
<FormField
|
||||||
id="limit"
|
id="limit"
|
||||||
name="limit"
|
name="limit"
|
||||||
@@ -296,7 +280,6 @@ function AdHocDetailsStep({ verbosityOptions, moduleOptions }) {
|
|||||||
|
|
||||||
AdHocDetailsStep.propTypes = {
|
AdHocDetailsStep.propTypes = {
|
||||||
moduleOptions: PropTypes.arrayOf(PropTypes.array).isRequired,
|
moduleOptions: PropTypes.arrayOf(PropTypes.array).isRequired,
|
||||||
verbosityOptions: PropTypes.arrayOf(PropTypes.object).isRequired,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default AdHocDetailsStep;
|
export default AdHocDetailsStep;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { t } from '@lingui/macro';
|
|||||||
import { Tooltip } from '@patternfly/react-core';
|
import { Tooltip } from '@patternfly/react-core';
|
||||||
import { ExclamationCircleIcon as PFExclamationCircleIcon } from '@patternfly/react-icons';
|
import { ExclamationCircleIcon as PFExclamationCircleIcon } from '@patternfly/react-icons';
|
||||||
import styled from 'styled-components';
|
import styled from 'styled-components';
|
||||||
|
import { VERBOSITY } from '../VerbositySelectField';
|
||||||
import { toTitleCase } from '../../util/strings';
|
import { toTitleCase } from '../../util/strings';
|
||||||
import { VariablesDetail } from '../CodeEditor';
|
import { VariablesDetail } from '../CodeEditor';
|
||||||
import { jsonToYaml } from '../../util/yaml';
|
import { jsonToYaml } from '../../util/yaml';
|
||||||
@@ -21,7 +22,7 @@ const ErrorMessageWrapper = styled.div`
|
|||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
`;
|
`;
|
||||||
function AdHocPreviewStep({ hasErrors, values }) {
|
function AdHocPreviewStep({ hasErrors, values }) {
|
||||||
const { credential, execution_environment, extra_vars } = values;
|
const { credential, execution_environment, extra_vars, verbosity } = values;
|
||||||
|
|
||||||
const items = Object.entries(values);
|
const items = Object.entries(values);
|
||||||
return (
|
return (
|
||||||
@@ -44,6 +45,7 @@ function AdHocPreviewStep({ hasErrors, values }) {
|
|||||||
key !== 'extra_vars' &&
|
key !== 'extra_vars' &&
|
||||||
key !== 'execution_environment' &&
|
key !== 'execution_environment' &&
|
||||||
key !== 'credentials' &&
|
key !== 'credentials' &&
|
||||||
|
key !== 'verbosity' &&
|
||||||
!key.startsWith('credential_passwords') && (
|
!key.startsWith('credential_passwords') && (
|
||||||
<Detail key={key} label={toTitleCase(key)} value={value} />
|
<Detail key={key} label={toTitleCase(key)} value={value} />
|
||||||
)
|
)
|
||||||
@@ -57,6 +59,9 @@ function AdHocPreviewStep({ hasErrors, values }) {
|
|||||||
value={execution_environment[0]?.name}
|
value={execution_environment[0]?.name}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{verbosity && (
|
||||||
|
<Detail label={t`Verbosity`} value={VERBOSITY()[values.verbosity]} />
|
||||||
|
)}
|
||||||
{extra_vars && (
|
{extra_vars && (
|
||||||
<VariablesDetail
|
<VariablesDetail
|
||||||
value={jsonToYaml(JSON.stringify(extra_vars))}
|
value={jsonToYaml(JSON.stringify(extra_vars))}
|
||||||
|
|||||||
@@ -5,11 +5,7 @@ import StepName from '../LaunchPrompt/steps/StepName';
|
|||||||
import AdHocDetailsStep from './AdHocDetailsStep';
|
import AdHocDetailsStep from './AdHocDetailsStep';
|
||||||
|
|
||||||
const STEP_ID = 'details';
|
const STEP_ID = 'details';
|
||||||
export default function useAdHocDetailsStep(
|
export default function useAdHocDetailsStep(visited, moduleOptions) {
|
||||||
visited,
|
|
||||||
moduleOptions,
|
|
||||||
verbosityOptions
|
|
||||||
) {
|
|
||||||
const { values, touched, setFieldError } = useFormikContext();
|
const { values, touched, setFieldError } = useFormikContext();
|
||||||
|
|
||||||
const hasError = () => {
|
const hasError = () => {
|
||||||
@@ -39,12 +35,7 @@ export default function useAdHocDetailsStep(
|
|||||||
{t`Details`}
|
{t`Details`}
|
||||||
</StepName>
|
</StepName>
|
||||||
),
|
),
|
||||||
component: (
|
component: <AdHocDetailsStep moduleOptions={moduleOptions} />,
|
||||||
<AdHocDetailsStep
|
|
||||||
moduleOptions={moduleOptions}
|
|
||||||
verbosityOptions={verbosityOptions}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
enableNext: true,
|
enableNext: true,
|
||||||
nextButtonText: t`Next`,
|
nextButtonText: t`Next`,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ function showCredentialPasswordsStep(credential) {
|
|||||||
|
|
||||||
export default function useAdHocLaunchSteps(
|
export default function useAdHocLaunchSteps(
|
||||||
moduleOptions,
|
moduleOptions,
|
||||||
verbosityOptions,
|
|
||||||
organizationId,
|
organizationId,
|
||||||
credentialTypeId
|
credentialTypeId
|
||||||
) {
|
) {
|
||||||
@@ -32,7 +31,7 @@ export default function useAdHocLaunchSteps(
|
|||||||
|
|
||||||
const [visited, setVisited] = useState({});
|
const [visited, setVisited] = useState({});
|
||||||
const steps = [
|
const steps = [
|
||||||
useAdHocDetailsStep(visited, moduleOptions, verbosityOptions),
|
useAdHocDetailsStep(visited, moduleOptions),
|
||||||
useAdHocExecutionEnvironmentStep(organizationId),
|
useAdHocExecutionEnvironmentStep(organizationId),
|
||||||
useAdHocCredentialStep(visited, credentialTypeId),
|
useAdHocCredentialStep(visited, credentialTypeId),
|
||||||
useCredentialPasswordsStep(
|
useCredentialPasswordsStep(
|
||||||
|
|||||||
@@ -46,7 +46,9 @@ function AnsibleSelect({
|
|||||||
value={option.value}
|
value={option.value}
|
||||||
label={option.label}
|
label={option.label}
|
||||||
isDisabled={option.isDisabled}
|
isDisabled={option.isDisabled}
|
||||||
/>
|
>
|
||||||
|
{option.label}
|
||||||
|
</FormSelectOption>
|
||||||
))}
|
))}
|
||||||
</FormSelect>
|
</FormSelect>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -113,48 +113,6 @@ describe('LaunchButton', () => {
|
|||||||
expect(history.location.pathname).toEqual('/jobs/9000/output');
|
expect(history.location.pathname).toEqual('/jobs/9000/output');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should disable button to prevent duplicate clicks', async () => {
|
|
||||||
WorkflowJobTemplatesAPI.readLaunch.mockResolvedValue({
|
|
||||||
data: {
|
|
||||||
can_start_without_user_input: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const history = createMemoryHistory({
|
|
||||||
initialEntries: ['/jobs/9000'],
|
|
||||||
});
|
|
||||||
WorkflowJobTemplatesAPI.launch.mockImplementation(async () => {
|
|
||||||
// return asynchronously so isLaunching isn't set back to false in the
|
|
||||||
// same tick
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
||||||
return {
|
|
||||||
data: {
|
|
||||||
id: 9000,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const wrapper = mountWithContexts(
|
|
||||||
<LaunchButton
|
|
||||||
resource={{
|
|
||||||
id: 1,
|
|
||||||
type: 'workflow_job_template',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{({ handleLaunch, isLaunching }) => (
|
|
||||||
<button type="submit" onClick={handleLaunch} disabled={isLaunching} />
|
|
||||||
)}
|
|
||||||
</LaunchButton>,
|
|
||||||
{
|
|
||||||
context: {
|
|
||||||
router: { history },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const button = wrapper.find('button');
|
|
||||||
await act(() => button.prop('onClick')());
|
|
||||||
wrapper.update();
|
|
||||||
expect(wrapper.find('button').prop('disabled')).toEqual(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('should relaunch job correctly', async () => {
|
test('should relaunch job correctly', async () => {
|
||||||
JobsAPI.readRelaunch.mockResolvedValue({
|
JobsAPI.readRelaunch.mockResolvedValue({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { TagMultiSelect } from '../../MultiSelect';
|
|||||||
import AnsibleSelect from '../../AnsibleSelect';
|
import AnsibleSelect from '../../AnsibleSelect';
|
||||||
import { VariablesField } from '../../CodeEditor';
|
import { VariablesField } from '../../CodeEditor';
|
||||||
import Popover from '../../Popover';
|
import Popover from '../../Popover';
|
||||||
|
import { VerbositySelectField } from '../../VerbositySelectField';
|
||||||
|
|
||||||
const FieldHeader = styled.div`
|
const FieldHeader = styled.div`
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -57,7 +58,7 @@ function OtherPromptsStep({ launchConfig, variablesMode, onVarModeChange }) {
|
|||||||
aria-label={t`Job Tags`}
|
aria-label={t`Job Tags`}
|
||||||
tooltip={t`Tags are useful when you have a large
|
tooltip={t`Tags are useful when you have a large
|
||||||
playbook, and you want to run a specific part of a play or task.
|
playbook, and you want to run a specific part of a play or task.
|
||||||
Use commas to separate multiple tags. Refer to Ansible Tower
|
Use commas to separate multiple tags. Refer to Ansible Controller
|
||||||
documentation for details on the usage of tags.`}
|
documentation for details on the usage of tags.`}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -69,7 +70,7 @@ function OtherPromptsStep({ launchConfig, variablesMode, onVarModeChange }) {
|
|||||||
aria-label={t`Skip Tags`}
|
aria-label={t`Skip Tags`}
|
||||||
tooltip={t`Skip tags are useful when you have a large
|
tooltip={t`Skip tags are useful when you have a large
|
||||||
playbook, and you want to skip specific parts of a play or task.
|
playbook, and you want to skip specific parts of a play or task.
|
||||||
Use commas to separate multiple tags. Refer to Ansible Tower
|
Use commas to separate multiple tags. Refer to Ansible Controller
|
||||||
documentation for details on the usage of tags.`}
|
documentation for details on the usage of tags.`}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -129,36 +130,16 @@ function JobTypeField() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function VerbosityField() {
|
function VerbosityField() {
|
||||||
const [field, meta, helpers] = useField('verbosity');
|
const [, meta] = useField('verbosity');
|
||||||
const options = [
|
|
||||||
{ value: '0', key: '0', label: t`0 (Normal)` },
|
|
||||||
{ value: '1', key: '1', label: t`1 (Verbose)` },
|
|
||||||
{ value: '2', key: '2', label: t`2 (More Verbose)` },
|
|
||||||
{ value: '3', key: '3', label: t`3 (Debug)` },
|
|
||||||
{ value: '4', key: '4', label: t`4 (Connection Debug)` },
|
|
||||||
];
|
|
||||||
|
|
||||||
const isValid = !(meta.touched && meta.error);
|
const isValid = !(meta.touched && meta.error);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FormGroup
|
<VerbositySelectField
|
||||||
fieldId="prompt-verbosity"
|
fieldId="prompt-verbosity"
|
||||||
validated={isValid ? 'default' : 'error'}
|
tooltip={t`Control the level of output ansible
|
||||||
label={t`Verbosity`}
|
|
||||||
labelIcon={
|
|
||||||
<Popover
|
|
||||||
content={t`Control the level of output ansible
|
|
||||||
will produce as the playbook executes.`}
|
will produce as the playbook executes.`}
|
||||||
/>
|
isValid={isValid ? 'default' : 'error'}
|
||||||
}
|
/>
|
||||||
>
|
|
||||||
<AnsibleSelect
|
|
||||||
id="prompt-verbosity"
|
|
||||||
data={options}
|
|
||||||
{...field}
|
|
||||||
onChange={(event, value) => helpers.setValue(value)}
|
|
||||||
/>
|
|
||||||
</FormGroup>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ describe('OtherPromptsStep', () => {
|
|||||||
expect(wrapper.find('VerbosityField')).toHaveLength(1);
|
expect(wrapper.find('VerbosityField')).toHaveLength(1);
|
||||||
expect(
|
expect(
|
||||||
wrapper.find('VerbosityField AnsibleSelect').prop('data')
|
wrapper.find('VerbosityField AnsibleSelect').prop('data')
|
||||||
).toHaveLength(5);
|
).toHaveLength(6);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should render show changes toggle', async () => {
|
test('should render show changes toggle', async () => {
|
||||||
|
|||||||
@@ -40,13 +40,11 @@ function PreviewStep({ resource, launchConfig, surveyConfig, formErrors }) {
|
|||||||
.filter((q) => q.type === 'password')
|
.filter((q) => q.type === 'password')
|
||||||
.map((q) => q.variable);
|
.map((q) => q.variable);
|
||||||
const masked = maskPasswords(surveyValues, passwordFields);
|
const masked = maskPasswords(surveyValues, passwordFields);
|
||||||
overrides.extra_vars = yaml.safeDump(
|
overrides.extra_vars = yaml.dump(
|
||||||
mergeExtraVars(initialExtraVars, masked)
|
mergeExtraVars(initialExtraVars, masked)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
overrides.extra_vars = yaml.safeDump(
|
overrides.extra_vars = yaml.dump(mergeExtraVars(initialExtraVars, {}));
|
||||||
mergeExtraVars(initialExtraVars, {})
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -349,7 +349,7 @@ function HostFilterLookup({
|
|||||||
content={t`Populate the hosts for this inventory by using a search
|
content={t`Populate the hosts for this inventory by using a search
|
||||||
filter. Example: ansible_facts__ansible_distribution:"RedHat".
|
filter. Example: ansible_facts__ansible_distribution:"RedHat".
|
||||||
Refer to the documentation for further syntax and
|
Refer to the documentation for further syntax and
|
||||||
examples. Refer to the Ansible Tower documentation for further syntax and
|
examples. Refer to the Ansible Controller documentation for further syntax and
|
||||||
examples.`}
|
examples.`}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import PromptProjectDetail from './PromptProjectDetail';
|
|||||||
import PromptInventorySourceDetail from './PromptInventorySourceDetail';
|
import PromptInventorySourceDetail from './PromptInventorySourceDetail';
|
||||||
import PromptJobTemplateDetail from './PromptJobTemplateDetail';
|
import PromptJobTemplateDetail from './PromptJobTemplateDetail';
|
||||||
import PromptWFJobTemplateDetail from './PromptWFJobTemplateDetail';
|
import PromptWFJobTemplateDetail from './PromptWFJobTemplateDetail';
|
||||||
|
import { VERBOSITY } from '../VerbositySelectField';
|
||||||
|
|
||||||
const PromptTitle = styled(Title)`
|
const PromptTitle = styled(Title)`
|
||||||
margin-top: var(--pf-global--spacer--xl);
|
margin-top: var(--pf-global--spacer--xl);
|
||||||
@@ -93,14 +94,6 @@ function PromptDetail({
|
|||||||
overrides = {},
|
overrides = {},
|
||||||
workflowNode = false,
|
workflowNode = false,
|
||||||
}) {
|
}) {
|
||||||
const VERBOSITY = {
|
|
||||||
0: t`0 (Normal)`,
|
|
||||||
1: t`1 (Verbose)`,
|
|
||||||
2: t`2 (More Verbose)`,
|
|
||||||
3: t`3 (Debug)`,
|
|
||||||
4: t`4 (Connection Debug)`,
|
|
||||||
};
|
|
||||||
|
|
||||||
const details = omitOverrides(resource, overrides, launchConfig.defaults);
|
const details = omitOverrides(resource, overrides, launchConfig.defaults);
|
||||||
details.type = overrides?.nodeType || details.type;
|
details.type = overrides?.nodeType || details.type;
|
||||||
const hasOverrides = Object.keys(overrides).length > 0;
|
const hasOverrides = Object.keys(overrides).length > 0;
|
||||||
@@ -226,7 +219,7 @@ function PromptDetail({
|
|||||||
launchConfig.ask_verbosity_on_launch ? (
|
launchConfig.ask_verbosity_on_launch ? (
|
||||||
<Detail
|
<Detail
|
||||||
label={t`Verbosity`}
|
label={t`Verbosity`}
|
||||||
value={VERBOSITY[overrides.verbosity]}
|
value={VERBOSITY()[overrides.verbosity]}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{launchConfig.ask_tags_on_launch && (
|
{launchConfig.ask_tags_on_launch && (
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { VariablesDetail } from '../CodeEditor';
|
|||||||
import CredentialChip from '../CredentialChip';
|
import CredentialChip from '../CredentialChip';
|
||||||
import ChipGroup from '../ChipGroup';
|
import ChipGroup from '../ChipGroup';
|
||||||
import ExecutionEnvironmentDetail from '../ExecutionEnvironmentDetail';
|
import ExecutionEnvironmentDetail from '../ExecutionEnvironmentDetail';
|
||||||
|
import { VERBOSITY } from '../VerbositySelectField';
|
||||||
|
|
||||||
function PromptInventorySourceDetail({ resource }) {
|
function PromptInventorySourceDetail({ resource }) {
|
||||||
const {
|
const {
|
||||||
@@ -32,14 +33,6 @@ function PromptInventorySourceDetail({ resource }) {
|
|||||||
verbosity,
|
verbosity,
|
||||||
} = resource;
|
} = resource;
|
||||||
|
|
||||||
const VERBOSITY = {
|
|
||||||
0: t`0 (Normal)`,
|
|
||||||
1: t`1 (Verbose)`,
|
|
||||||
2: t`2 (More Verbose)`,
|
|
||||||
3: t`3 (Debug)`,
|
|
||||||
4: t`4 (Connection Debug)`,
|
|
||||||
};
|
|
||||||
|
|
||||||
let optionsList = '';
|
let optionsList = '';
|
||||||
if (
|
if (
|
||||||
overwrite ||
|
overwrite ||
|
||||||
@@ -115,7 +108,7 @@ function PromptInventorySourceDetail({ resource }) {
|
|||||||
executionEnvironment={summary_fields?.execution_environment}
|
executionEnvironment={summary_fields?.execution_environment}
|
||||||
/>
|
/>
|
||||||
<Detail label={t`Inventory File`} value={source_path} />
|
<Detail label={t`Inventory File`} value={source_path} />
|
||||||
<Detail label={t`Verbosity`} value={VERBOSITY[verbosity]} />
|
<Detail label={t`Verbosity`} value={VERBOSITY()[verbosity]} />
|
||||||
<Detail
|
<Detail
|
||||||
label={t`Cache Timeout`}
|
label={t`Cache Timeout`}
|
||||||
value={`${update_cache_timeout} ${t`Seconds`}`}
|
value={`${update_cache_timeout} ${t`Seconds`}`}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import Sparkline from '../Sparkline';
|
|||||||
import { Detail, DeletedDetail } from '../DetailList';
|
import { Detail, DeletedDetail } from '../DetailList';
|
||||||
import { VariablesDetail } from '../CodeEditor';
|
import { VariablesDetail } from '../CodeEditor';
|
||||||
import ExecutionEnvironmentDetail from '../ExecutionEnvironmentDetail';
|
import ExecutionEnvironmentDetail from '../ExecutionEnvironmentDetail';
|
||||||
|
import { VERBOSITY } from '../VerbositySelectField';
|
||||||
|
|
||||||
function PromptJobTemplateDetail({ resource }) {
|
function PromptJobTemplateDetail({ resource }) {
|
||||||
const {
|
const {
|
||||||
@@ -42,14 +43,6 @@ function PromptJobTemplateDetail({ resource }) {
|
|||||||
custom_virtualenv,
|
custom_virtualenv,
|
||||||
} = resource;
|
} = resource;
|
||||||
|
|
||||||
const VERBOSITY = {
|
|
||||||
0: t`0 (Normal)`,
|
|
||||||
1: t`1 (Verbose)`,
|
|
||||||
2: t`2 (More Verbose)`,
|
|
||||||
3: t`3 (Debug)`,
|
|
||||||
4: t`4 (Connection Debug)`,
|
|
||||||
};
|
|
||||||
|
|
||||||
let optionsList = '';
|
let optionsList = '';
|
||||||
if (
|
if (
|
||||||
become_enabled ||
|
become_enabled ||
|
||||||
@@ -153,7 +146,7 @@ function PromptJobTemplateDetail({ resource }) {
|
|||||||
<Detail label={t`Playbook`} value={playbook} />
|
<Detail label={t`Playbook`} value={playbook} />
|
||||||
<Detail label={t`Forks`} value={forks || '0'} />
|
<Detail label={t`Forks`} value={forks || '0'} />
|
||||||
<Detail label={t`Limit`} value={limit} />
|
<Detail label={t`Limit`} value={limit} />
|
||||||
<Detail label={t`Verbosity`} value={VERBOSITY[verbosity]} />
|
<Detail label={t`Verbosity`} value={VERBOSITY()[verbosity]} />
|
||||||
{typeof diff_mode === 'boolean' && (
|
{typeof diff_mode === 'boolean' && (
|
||||||
<Detail label={t`Show Changes`} value={diff_mode ? t`On` : t`Off`} />
|
<Detail label={t`Show Changes`} value={diff_mode ? t`On` : t`Off`} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -72,9 +72,9 @@ function ScheduleAdd({
|
|||||||
launchConfiguration?.ask_variables_on_launch &&
|
launchConfiguration?.ask_variables_on_launch &&
|
||||||
(values.extra_vars || '---');
|
(values.extra_vars || '---');
|
||||||
if (surveyConfiguration?.spec) {
|
if (surveyConfiguration?.spec) {
|
||||||
extraVars = yaml.safeDump(mergeExtraVars(initialExtraVars, surveyValues));
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, surveyValues));
|
||||||
} else {
|
} else {
|
||||||
extraVars = yaml.safeDump(mergeExtraVars(initialExtraVars, {}));
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, {}));
|
||||||
}
|
}
|
||||||
submitValues.extra_data = extraVars && parseVariableField(extraVars);
|
submitValues.extra_data = extraVars && parseVariableField(extraVars);
|
||||||
delete values.extra_vars;
|
delete values.extra_vars;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { formatDateString } from 'util/dates';
|
|||||||
import useRequest, { useDismissableError } from 'hooks/useRequest';
|
import useRequest, { useDismissableError } from 'hooks/useRequest';
|
||||||
import { JobTemplatesAPI, SchedulesAPI, WorkflowJobTemplatesAPI } from 'api';
|
import { JobTemplatesAPI, SchedulesAPI, WorkflowJobTemplatesAPI } from 'api';
|
||||||
import { parseVariableField, jsonToYaml } from 'util/yaml';
|
import { parseVariableField, jsonToYaml } from 'util/yaml';
|
||||||
|
import { useConfig } from 'contexts/Config';
|
||||||
import AlertModal from '../../AlertModal';
|
import AlertModal from '../../AlertModal';
|
||||||
import { CardBody, CardActionsRow } from '../../Card';
|
import { CardBody, CardActionsRow } from '../../Card';
|
||||||
import ContentError from '../../ContentError';
|
import ContentError from '../../ContentError';
|
||||||
@@ -23,6 +24,8 @@ import DeleteButton from '../../DeleteButton';
|
|||||||
import ErrorDetail from '../../ErrorDetail';
|
import ErrorDetail from '../../ErrorDetail';
|
||||||
import ChipGroup from '../../ChipGroup';
|
import ChipGroup from '../../ChipGroup';
|
||||||
import { VariablesDetail } from '../../CodeEditor';
|
import { VariablesDetail } from '../../CodeEditor';
|
||||||
|
import { VERBOSITY } from '../../VerbositySelectField';
|
||||||
|
import helpText from '../../../screens/Template/shared/JobTemplate.helptext';
|
||||||
|
|
||||||
const PromptDivider = styled(Divider)`
|
const PromptDivider = styled(Divider)`
|
||||||
margin-top: var(--pf-global--spacer--lg);
|
margin-top: var(--pf-global--spacer--lg);
|
||||||
@@ -38,7 +41,6 @@ const PromptTitle = styled(Title)`
|
|||||||
const PromptDetailList = styled(DetailList)`
|
const PromptDetailList = styled(DetailList)`
|
||||||
padding: 0px 20px;
|
padding: 0px 20px;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
||||||
const {
|
const {
|
||||||
id,
|
id,
|
||||||
@@ -66,14 +68,7 @@ function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
|||||||
const history = useHistory();
|
const history = useHistory();
|
||||||
const { pathname } = useLocation();
|
const { pathname } = useLocation();
|
||||||
const pathRoot = pathname.substr(0, pathname.indexOf('schedules'));
|
const pathRoot = pathname.substr(0, pathname.indexOf('schedules'));
|
||||||
|
const config = useConfig();
|
||||||
const VERBOSITY = {
|
|
||||||
0: t`0 (Normal)`,
|
|
||||||
1: t`1 (Verbose)`,
|
|
||||||
2: t`2 (More Verbose)`,
|
|
||||||
3: t`3 (Debug)`,
|
|
||||||
4: t`4 (Connection Debug)`,
|
|
||||||
};
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
request: deleteSchedule,
|
request: deleteSchedule,
|
||||||
@@ -216,7 +211,7 @@ function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
|||||||
const showLimitDetail = ask_limit_on_launch && limit;
|
const showLimitDetail = ask_limit_on_launch && limit;
|
||||||
const showJobTypeDetail = ask_job_type_on_launch && job_type;
|
const showJobTypeDetail = ask_job_type_on_launch && job_type;
|
||||||
const showSCMBranchDetail = ask_scm_branch_on_launch && scm_branch;
|
const showSCMBranchDetail = ask_scm_branch_on_launch && scm_branch;
|
||||||
const showVerbosityDetail = ask_verbosity_on_launch && VERBOSITY[verbosity];
|
const showVerbosityDetail = ask_verbosity_on_launch && VERBOSITY()[verbosity];
|
||||||
|
|
||||||
const showPromptedFields =
|
const showPromptedFields =
|
||||||
showCredentialsDetail ||
|
showCredentialsDetail ||
|
||||||
@@ -267,7 +262,11 @@ function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
|||||||
value={formatDateString(next_run, timezone)}
|
value={formatDateString(next_run, timezone)}
|
||||||
/>
|
/>
|
||||||
<Detail label={t`Last Run`} value={formatDateString(dtend, timezone)} />
|
<Detail label={t`Last Run`} value={formatDateString(dtend, timezone)} />
|
||||||
<Detail label={t`Local Time Zone`} value={timezone} />
|
<Detail
|
||||||
|
label={t`Local Time Zone`}
|
||||||
|
value={timezone}
|
||||||
|
helpText={helpText.localTimeZone(config)}
|
||||||
|
/>
|
||||||
<Detail label={t`Repeat Frequency`} value={repeatFrequency} />
|
<Detail label={t`Repeat Frequency`} value={repeatFrequency} />
|
||||||
{hasDaysToKeepField ? (
|
{hasDaysToKeepField ? (
|
||||||
<Detail label={t`Days of Data to Keep`} value={daysToKeep} />
|
<Detail label={t`Days of Data to Keep`} value={daysToKeep} />
|
||||||
@@ -313,7 +312,7 @@ function ScheduleDetail({ hasDaysToKeepField, schedule, surveyConfig }) {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{ask_verbosity_on_launch && (
|
{ask_verbosity_on_launch && (
|
||||||
<Detail label={t`Verbosity`} value={VERBOSITY[verbosity]} />
|
<Detail label={t`Verbosity`} value={VERBOSITY()[verbosity]} />
|
||||||
)}
|
)}
|
||||||
{ask_scm_branch_on_launch && (
|
{ask_scm_branch_on_launch && (
|
||||||
<Detail label={t`Source Control Branch`} value={scm_branch} />
|
<Detail label={t`Source Control Branch`} value={scm_branch} />
|
||||||
|
|||||||
@@ -164,6 +164,9 @@ describe('<ScheduleDetail />', () => {
|
|||||||
expect(
|
expect(
|
||||||
wrapper.find('Detail[label="Local Time Zone"]').find('dd').text()
|
wrapper.find('Detail[label="Local Time Zone"]').find('dd').text()
|
||||||
).toBe('America/New_York');
|
).toBe('America/New_York');
|
||||||
|
expect(
|
||||||
|
wrapper.find('Detail[label="Local Time Zone"]').prop('helpText')
|
||||||
|
).toBeDefined();
|
||||||
expect(wrapper.find('Detail[label="Repeat Frequency"]').length).toBe(1);
|
expect(wrapper.find('Detail[label="Repeat Frequency"]').length).toBe(1);
|
||||||
expect(wrapper.find('Detail[label="Created"]').length).toBe(1);
|
expect(wrapper.find('Detail[label="Created"]').length).toBe(1);
|
||||||
expect(wrapper.find('Detail[label="Last Modified"]').length).toBe(1);
|
expect(wrapper.find('Detail[label="Last Modified"]').length).toBe(1);
|
||||||
|
|||||||
@@ -73,9 +73,9 @@ function ScheduleEdit({
|
|||||||
launchConfiguration?.ask_variables_on_launch &&
|
launchConfiguration?.ask_variables_on_launch &&
|
||||||
(values.extra_vars || '---');
|
(values.extra_vars || '---');
|
||||||
if (surveyConfiguration?.spec) {
|
if (surveyConfiguration?.spec) {
|
||||||
extraVars = yaml.safeDump(mergeExtraVars(initialExtraVars, surveyValues));
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, surveyValues));
|
||||||
} else {
|
} else {
|
||||||
extraVars = yaml.safeDump(mergeExtraVars(initialExtraVars, {}));
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, {}));
|
||||||
}
|
}
|
||||||
submitValues.extra_data = extraVars && parseVariableField(extraVars);
|
submitValues.extra_data = extraVars && parseVariableField(extraVars);
|
||||||
|
|
||||||
|
|||||||
@@ -14,12 +14,13 @@ import {
|
|||||||
// To be removed once UI completes complex schedules
|
// To be removed once UI completes complex schedules
|
||||||
Alert,
|
Alert,
|
||||||
} from '@patternfly/react-core';
|
} from '@patternfly/react-core';
|
||||||
import { Config } from 'contexts/Config';
|
import { Config, useConfig } from 'contexts/Config';
|
||||||
import { SchedulesAPI } from 'api';
|
import { SchedulesAPI } from 'api';
|
||||||
import { dateToInputDateTime } from 'util/dates';
|
import { dateToInputDateTime } from 'util/dates';
|
||||||
import useRequest from 'hooks/useRequest';
|
import useRequest from 'hooks/useRequest';
|
||||||
import { required } from 'util/validators';
|
import { required } from 'util/validators';
|
||||||
import { parseVariableField } from 'util/yaml';
|
import { parseVariableField } from 'util/yaml';
|
||||||
|
import Popover from '../../Popover';
|
||||||
import AnsibleSelect from '../../AnsibleSelect';
|
import AnsibleSelect from '../../AnsibleSelect';
|
||||||
import ContentError from '../../ContentError';
|
import ContentError from '../../ContentError';
|
||||||
import ContentLoading from '../../ContentLoading';
|
import ContentLoading from '../../ContentLoading';
|
||||||
@@ -33,6 +34,7 @@ import FrequencyDetailSubform from './FrequencyDetailSubform';
|
|||||||
import SchedulePromptableFields from './SchedulePromptableFields';
|
import SchedulePromptableFields from './SchedulePromptableFields';
|
||||||
import DateTimePicker from './DateTimePicker';
|
import DateTimePicker from './DateTimePicker';
|
||||||
import buildRuleObj from './buildRuleObj';
|
import buildRuleObj from './buildRuleObj';
|
||||||
|
import helpText from '../../../screens/Template/shared/JobTemplate.helptext';
|
||||||
|
|
||||||
const NUM_DAYS_PER_FREQUENCY = {
|
const NUM_DAYS_PER_FREQUENCY = {
|
||||||
week: 7,
|
week: 7,
|
||||||
@@ -118,6 +120,9 @@ function ScheduleFormFields({ hasDaysToKeepField, zoneOptions, zoneLinks }) {
|
|||||||
} else if (timezoneMessage) {
|
} else if (timezoneMessage) {
|
||||||
timezoneValidatedStatus = 'warning';
|
timezoneValidatedStatus = 'warning';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const config = useConfig();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<FormField
|
<FormField
|
||||||
@@ -147,6 +152,7 @@ function ScheduleFormFields({ hasDaysToKeepField, zoneOptions, zoneLinks }) {
|
|||||||
validated={timezoneValidatedStatus}
|
validated={timezoneValidatedStatus}
|
||||||
label={t`Local time zone`}
|
label={t`Local time zone`}
|
||||||
helperText={timezoneMessage}
|
helperText={timezoneMessage}
|
||||||
|
labelIcon={<Popover content={helpText.localTimeZone(config)} />}
|
||||||
>
|
>
|
||||||
<AnsibleSelect
|
<AnsibleSelect
|
||||||
id="schedule-timezone"
|
id="schedule-timezone"
|
||||||
|
|||||||
@@ -91,6 +91,9 @@ const defaultFieldsVisible = () => {
|
|||||||
expect(wrapper.find('FormGroup[label="Description"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Description"]').length).toBe(1);
|
||||||
expect(wrapper.find('FormGroup[label="Start date/time"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Start date/time"]').length).toBe(1);
|
||||||
expect(wrapper.find('FormGroup[label="Local time zone"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Local time zone"]').length).toBe(1);
|
||||||
|
expect(
|
||||||
|
wrapper.find('FormGroup[label="Local time zone"]').find('HelpIcon').length
|
||||||
|
).toBe(1);
|
||||||
expect(wrapper.find('FormGroup[label="Run frequency"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Run frequency"]').length).toBe(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { t } from '@lingui/macro';
|
||||||
|
import { useField } from 'formik';
|
||||||
|
import { FormGroup } from '@patternfly/react-core';
|
||||||
|
import Popover from 'components/Popover';
|
||||||
|
import AnsibleSelect from 'components/AnsibleSelect';
|
||||||
|
import FieldWithPrompt from 'components/FieldWithPrompt';
|
||||||
|
|
||||||
|
const VERBOSITY = () => ({
|
||||||
|
0: t`0 (Normal)`,
|
||||||
|
1: t`1 (Verbose)`,
|
||||||
|
2: t`2 (More Verbose)`,
|
||||||
|
3: t`3 (Debug)`,
|
||||||
|
4: t`4 (Connection Debug)`,
|
||||||
|
5: t`5 (WinRM Debug)`,
|
||||||
|
});
|
||||||
|
|
||||||
|
function VerbositySelectField({
|
||||||
|
fieldId,
|
||||||
|
promptId,
|
||||||
|
promptName,
|
||||||
|
tooltip,
|
||||||
|
isValid,
|
||||||
|
}) {
|
||||||
|
const VERBOSE_OPTIONS = Object.entries(VERBOSITY()).map(([k, v]) => ({
|
||||||
|
key: `${k}`,
|
||||||
|
value: `${k}`,
|
||||||
|
label: v,
|
||||||
|
}));
|
||||||
|
const [verbosityField, , verbosityHelpers] = useField('verbosity');
|
||||||
|
return promptId ? (
|
||||||
|
<FieldWithPrompt
|
||||||
|
fieldId={fieldId}
|
||||||
|
label={t`Verbosity`}
|
||||||
|
promptId={promptId}
|
||||||
|
promptName={promptName}
|
||||||
|
tooltip={tooltip}
|
||||||
|
>
|
||||||
|
<AnsibleSelect id={fieldId} data={VERBOSE_OPTIONS} {...verbosityField} />
|
||||||
|
</FieldWithPrompt>
|
||||||
|
) : (
|
||||||
|
<FormGroup
|
||||||
|
fieldId={fieldId}
|
||||||
|
validated={isValid ? 'default' : 'error'}
|
||||||
|
label={t`Verbosity`}
|
||||||
|
labelIcon={<Popover content={tooltip} />}
|
||||||
|
>
|
||||||
|
<AnsibleSelect
|
||||||
|
id={fieldId}
|
||||||
|
data={VERBOSE_OPTIONS}
|
||||||
|
{...verbosityField}
|
||||||
|
onChange={(event, value) => verbosityHelpers.setValue(value)}
|
||||||
|
/>
|
||||||
|
</FormGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { VerbositySelectField, VERBOSITY };
|
||||||
1
awx/ui/src/components/VerbositySelectField/index.js
Normal file
1
awx/ui/src/components/VerbositySelectField/index.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { VERBOSITY, VerbositySelectField } from './VerbositySelectField';
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -418,7 +418,7 @@ describe('<CredentialForm />', () => {
|
|||||||
).toBe(false);
|
).toBe(false);
|
||||||
expect(wrapper.find('FormGroup[label="Credential Type"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Credential Type"]').length).toBe(1);
|
||||||
expect(
|
expect(
|
||||||
wrapper.find('FormGroup[label="Ansible Tower Hostname"]').length
|
wrapper.find('FormGroup[label="Ansible Controller Hostname"]').length
|
||||||
).toBe(1);
|
).toBe(1);
|
||||||
expect(wrapper.find('FormGroup[label="Username"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Username"]').length).toBe(1);
|
||||||
expect(wrapper.find('FormGroup[label="Password"]').length).toBe(1);
|
expect(wrapper.find('FormGroup[label="Password"]').length).toBe(1);
|
||||||
|
|||||||
@@ -61,7 +61,7 @@
|
|||||||
},
|
},
|
||||||
"created": "2020-05-18T21:53:35.334813Z",
|
"created": "2020-05-18T21:53:35.334813Z",
|
||||||
"modified": "2020-05-18T21:54:05.424087Z",
|
"modified": "2020-05-18T21:54:05.424087Z",
|
||||||
"name": "Ansible Tower",
|
"name": "Ansible Controller",
|
||||||
"description": "",
|
"description": "",
|
||||||
"kind": "cloud",
|
"kind": "cloud",
|
||||||
"namespace": "tower",
|
"namespace": "tower",
|
||||||
@@ -70,9 +70,9 @@
|
|||||||
"fields": [
|
"fields": [
|
||||||
{
|
{
|
||||||
"id": "host",
|
"id": "host",
|
||||||
"label": "Ansible Tower Hostname",
|
"label": "Ansible Controller Hostname",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"help_text": "The Ansible Tower base URL to authenticate with."
|
"help_text": "The Ansible Controller base URL to authenticate with."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "username",
|
"id": "username",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"type": "credential",
|
"type": "credential",
|
||||||
"url": "/api/v2/credentials/4/",
|
"url": "/api/v2/credentials/4/",
|
||||||
"related": {
|
"related": {
|
||||||
"named_url": "/api/v2/credentials/Tower cred++Ansible Tower+cloud++/",
|
"named_url": "/api/v2/credentials/Tower cred++Ansible Controller+cloud++/",
|
||||||
"created_by": "/api/v2/users/2/",
|
"created_by": "/api/v2/users/2/",
|
||||||
"modified_by": "/api/v2/users/2/",
|
"modified_by": "/api/v2/users/2/",
|
||||||
"activity_stream": "/api/v2/credentials/4/activity_stream/",
|
"activity_stream": "/api/v2/credentials/4/activity_stream/",
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
"summary_fields": {
|
"summary_fields": {
|
||||||
"credential_type": {
|
"credential_type": {
|
||||||
"id": 16,
|
"id": 16,
|
||||||
"name": "Ansible Tower",
|
"name": "Ansible Controller",
|
||||||
"description": ""
|
"description": ""
|
||||||
},
|
},
|
||||||
"created_by": {
|
"created_by": {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ function CredentialTypeFormFields() {
|
|||||||
/>
|
/>
|
||||||
<FormFullWidthLayout>
|
<FormFullWidthLayout>
|
||||||
<VariablesField
|
<VariablesField
|
||||||
tooltip={t`Enter inputs using either JSON or YAML syntax. Refer to the Ansible Tower documentation for example syntax.`}
|
tooltip={t`Enter inputs using either JSON or YAML syntax. Refer to the Ansible Controller documentation for example syntax.`}
|
||||||
id="credential-type-inputs-configuration"
|
id="credential-type-inputs-configuration"
|
||||||
name="inputs"
|
name="inputs"
|
||||||
label={t`Input configuration`}
|
label={t`Input configuration`}
|
||||||
@@ -40,7 +40,7 @@ function CredentialTypeFormFields() {
|
|||||||
</FormFullWidthLayout>
|
</FormFullWidthLayout>
|
||||||
<FormFullWidthLayout>
|
<FormFullWidthLayout>
|
||||||
<VariablesField
|
<VariablesField
|
||||||
tooltip={t`Enter injectors using either JSON or YAML syntax. Refer to the Ansible Tower documentation for example syntax.`}
|
tooltip={t`Enter injectors using either JSON or YAML syntax. Refer to the Ansible Controller documentation for example syntax.`}
|
||||||
id="credential-type-injectors-configuration"
|
id="credential-type-injectors-configuration"
|
||||||
name="injectors"
|
name="injectors"
|
||||||
label={t`Injector configuration`}
|
label={t`Injector configuration`}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { relatedResourceDeleteRequests } from 'util/getRelatedResourceDeleteDeta
|
|||||||
import useIsMounted from 'hooks/useIsMounted';
|
import useIsMounted from 'hooks/useIsMounted';
|
||||||
import { formatDateString } from 'util/dates';
|
import { formatDateString } from 'util/dates';
|
||||||
import Popover from 'components/Popover';
|
import Popover from 'components/Popover';
|
||||||
|
import { VERBOSITY } from 'components/VerbositySelectField';
|
||||||
import InventorySourceSyncButton from '../shared/InventorySourceSyncButton';
|
import InventorySourceSyncButton from '../shared/InventorySourceSyncButton';
|
||||||
import useWsInventorySourcesDetails from '../InventorySources/useWsInventorySourcesDetails';
|
import useWsInventorySourcesDetails from '../InventorySources/useWsInventorySourcesDetails';
|
||||||
import helpText from '../shared/Inventory.helptext';
|
import helpText from '../shared/Inventory.helptext';
|
||||||
@@ -111,12 +112,6 @@ function InventorySourceDetail({ inventorySource }) {
|
|||||||
inventorySource.id
|
inventorySource.id
|
||||||
);
|
);
|
||||||
|
|
||||||
const VERBOSITY = {
|
|
||||||
0: t`0 (Warning)`,
|
|
||||||
1: t`1 (Info)`,
|
|
||||||
2: t`2 (Debug)`,
|
|
||||||
};
|
|
||||||
|
|
||||||
let optionsList = '';
|
let optionsList = '';
|
||||||
if (
|
if (
|
||||||
overwrite ||
|
overwrite ||
|
||||||
@@ -251,7 +246,7 @@ function InventorySourceDetail({ inventorySource }) {
|
|||||||
<Detail
|
<Detail
|
||||||
label={t`Verbosity`}
|
label={t`Verbosity`}
|
||||||
helpText={helpText.subFormVerbosityFields}
|
helpText={helpText.subFormVerbosityFields}
|
||||||
value={VERBOSITY[verbosity]}
|
value={VERBOSITY()[verbosity]}
|
||||||
/>
|
/>
|
||||||
<Detail
|
<Detail
|
||||||
label={t`Cache timeout`}
|
label={t`Cache timeout`}
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ describe('InventorySourceDetail', () => {
|
|||||||
assertDetail(wrapper, 'Organization', 'Mock Org');
|
assertDetail(wrapper, 'Organization', 'Mock Org');
|
||||||
assertDetail(wrapper, 'Project', 'Mock Project');
|
assertDetail(wrapper, 'Project', 'Mock Project');
|
||||||
assertDetail(wrapper, 'Inventory file', 'foo');
|
assertDetail(wrapper, 'Inventory file', 'foo');
|
||||||
assertDetail(wrapper, 'Verbosity', '2 (Debug)');
|
assertDetail(wrapper, 'Verbosity', '2 (More Verbose)');
|
||||||
assertDetail(wrapper, 'Cache timeout', '2 seconds');
|
assertDetail(wrapper, 'Cache timeout', '2 seconds');
|
||||||
const executionEnvironment = wrapper.find('ExecutionEnvironmentDetail');
|
const executionEnvironment = wrapper.find('ExecutionEnvironmentDetail');
|
||||||
expect(executionEnvironment).toHaveLength(1);
|
expect(executionEnvironment).toHaveLength(1);
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ const SmartInventoryFormFields = ({ inventory }) => {
|
|||||||
label={t`Variables`}
|
label={t`Variables`}
|
||||||
tooltip={t`Enter inventory variables using either JSON or YAML syntax.
|
tooltip={t`Enter inventory variables using either JSON or YAML syntax.
|
||||||
Use the radio button to toggle between the two. Refer to the
|
Use the radio button to toggle between the two. Refer to the
|
||||||
Ansible Tower documentation for example syntax.`}
|
Ansible Controller documentation for example syntax.`}
|
||||||
/>
|
/>
|
||||||
</FormFullWidthLayout>
|
</FormFullWidthLayout>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import { LaunchButton, ReLaunchDropDown } from 'components/LaunchButton';
|
|||||||
import StatusLabel from 'components/StatusLabel';
|
import StatusLabel from 'components/StatusLabel';
|
||||||
import JobCancelButton from 'components/JobCancelButton';
|
import JobCancelButton from 'components/JobCancelButton';
|
||||||
import ExecutionEnvironmentDetail from 'components/ExecutionEnvironmentDetail';
|
import ExecutionEnvironmentDetail from 'components/ExecutionEnvironmentDetail';
|
||||||
|
import { VERBOSITY } from 'components/VerbositySelectField';
|
||||||
import { getJobModel, isJobRunning } from 'util/jobs';
|
import { getJobModel, isJobRunning } from 'util/jobs';
|
||||||
import { formatDateString } from 'util/dates';
|
import { formatDateString } from 'util/dates';
|
||||||
import { Job } from 'types';
|
import { Job } from 'types';
|
||||||
@@ -37,14 +38,6 @@ const StatusDetailValue = styled.div`
|
|||||||
grid-template-columns: auto auto;
|
grid-template-columns: auto auto;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const VERBOSITY = {
|
|
||||||
0: '0 (Normal)',
|
|
||||||
1: '1 (Verbose)',
|
|
||||||
2: '2 (More Verbose)',
|
|
||||||
3: '3 (Debug)',
|
|
||||||
4: '4 (Connection Debug)',
|
|
||||||
};
|
|
||||||
|
|
||||||
function JobDetail({ job, inventorySourceLabels }) {
|
function JobDetail({ job, inventorySourceLabels }) {
|
||||||
const { me } = useConfig();
|
const { me } = useConfig();
|
||||||
const {
|
const {
|
||||||
@@ -332,7 +325,7 @@ function JobDetail({ job, inventorySourceLabels }) {
|
|||||||
dataCy="job-verbosity"
|
dataCy="job-verbosity"
|
||||||
label={t`Verbosity`}
|
label={t`Verbosity`}
|
||||||
helpText={jobHelpText.verbosity}
|
helpText={jobHelpText.verbosity}
|
||||||
value={VERBOSITY[job.verbosity]}
|
value={VERBOSITY()[job.verbosity]}
|
||||||
/>
|
/>
|
||||||
{job.type !== 'workflow_job' && !isJobRunning(job.status) && (
|
{job.type !== 'workflow_job' && !isJobRunning(job.status) && (
|
||||||
<ExecutionEnvironmentDetail
|
<ExecutionEnvironmentDetail
|
||||||
|
|||||||
@@ -1,17 +1,29 @@
|
|||||||
import React, { useEffect } from 'react';
|
import React, { useEffect } from 'react';
|
||||||
|
import { Link, useParams } from 'react-router-dom';
|
||||||
import 'styled-components/macro';
|
import 'styled-components/macro';
|
||||||
import { t } from '@lingui/macro';
|
import { t } from '@lingui/macro';
|
||||||
import { SearchIcon } from '@patternfly/react-icons';
|
import {
|
||||||
|
SearchIcon,
|
||||||
|
ExclamationCircleIcon as PFExclamationCircleIcon,
|
||||||
|
} from '@patternfly/react-icons';
|
||||||
import ContentEmpty from 'components/ContentEmpty';
|
import ContentEmpty from 'components/ContentEmpty';
|
||||||
|
|
||||||
|
import styled from 'styled-components';
|
||||||
|
|
||||||
|
const ExclamationCircleIcon = styled(PFExclamationCircleIcon)`
|
||||||
|
color: var(--pf-global--danger-color--100);
|
||||||
|
`;
|
||||||
|
|
||||||
export default function EmptyOutput({
|
export default function EmptyOutput({
|
||||||
hasQueryParams,
|
hasQueryParams,
|
||||||
isJobRunning,
|
isJobRunning,
|
||||||
onUnmount,
|
onUnmount,
|
||||||
|
job,
|
||||||
}) {
|
}) {
|
||||||
let title;
|
let title;
|
||||||
let message;
|
let message;
|
||||||
let icon;
|
let icon;
|
||||||
|
const { typeSegment, id } = useParams();
|
||||||
|
|
||||||
useEffect(() => onUnmount);
|
useEffect(() => onUnmount);
|
||||||
|
|
||||||
@@ -21,6 +33,21 @@ export default function EmptyOutput({
|
|||||||
icon = SearchIcon;
|
icon = SearchIcon;
|
||||||
} else if (isJobRunning) {
|
} else if (isJobRunning) {
|
||||||
title = t`Waiting for job output…`;
|
title = t`Waiting for job output…`;
|
||||||
|
} else if (job.status === 'failed') {
|
||||||
|
title = t`This job failed and has no output.`;
|
||||||
|
message = (
|
||||||
|
<>
|
||||||
|
{t`Return to `}{' '}
|
||||||
|
<Link to={`/jobs/${typeSegment}/${id}/details`}>{t`details.`}</Link>
|
||||||
|
<br />
|
||||||
|
{job.job_explanation && (
|
||||||
|
<>
|
||||||
|
{t`Failure Explanation:`} {`${job.job_explanation}`}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
icon = ExclamationCircleIcon;
|
||||||
} else {
|
} else {
|
||||||
title = t`No output found for this job.`;
|
title = t`No output found for this job.`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -687,6 +687,7 @@ function JobOutput({ job, eventRelatedSearchableKeys, eventSearchableKeys }) {
|
|||||||
) {
|
) {
|
||||||
return (
|
return (
|
||||||
<EmptyOutput
|
<EmptyOutput
|
||||||
|
job={job}
|
||||||
hasQueryParams={location.search.length > 1}
|
hasQueryParams={location.search.length > 1}
|
||||||
isJobRunning={isJobRunning(jobStatus)}
|
isJobRunning={isJobRunning(jobStatus)}
|
||||||
onUnmount={() => {
|
onUnmount={() => {
|
||||||
|
|||||||
@@ -134,4 +134,20 @@ describe('<JobOutput />', () => {
|
|||||||
});
|
});
|
||||||
await waitForElement(wrapper, 'ContentError', (el) => el.length === 1);
|
await waitForElement(wrapper, 'ContentError', (el) => el.length === 1);
|
||||||
});
|
});
|
||||||
|
test('should show failed empty output screen', async () => {
|
||||||
|
JobsAPI.readEvents.mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
count: 0,
|
||||||
|
next: null,
|
||||||
|
previous: null,
|
||||||
|
results: [],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
wrapper = mountWithContexts(
|
||||||
|
<JobOutput job={{ ...mockJob, status: 'failed' }} />
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await waitForElement(wrapper, 'EmptyOutput', (el) => el.length === 1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ function CustomMessagesSubForm({ defaultMessages, type }) {
|
|||||||
config
|
config
|
||||||
)}/html/userguide/notifications.html#create-custom-notifications`}
|
)}/html/userguide/notifications.html#create-custom-notifications`}
|
||||||
>
|
>
|
||||||
{t`Ansible Tower Documentation.`}
|
{t`Ansible Controller Documentation.`}
|
||||||
</a>
|
</a>
|
||||||
</small>
|
</small>
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const helpText = {
|
|||||||
twilioDestinationNumbers: t`Use one phone number per line to specify where to
|
twilioDestinationNumbers: t`Use one phone number per line to specify where to
|
||||||
route SMS messages. Phone numbers should be formatted +11231231234. For more information see Twilio documentation`,
|
route SMS messages. Phone numbers should be formatted +11231231234. For more information see Twilio documentation`,
|
||||||
webhookHeaders: t`Specify HTTP Headers in JSON format. Refer to
|
webhookHeaders: t`Specify HTTP Headers in JSON format. Refer to
|
||||||
the Ansible Tower documentation for example syntax.`,
|
the Ansible Controller documentation for example syntax.`,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default helpText;
|
export default helpText;
|
||||||
|
|||||||
@@ -35,6 +35,13 @@ function SubscriptionDetail() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const { automated_instances: automatedInstancesCount, automated_since } =
|
||||||
|
license_info;
|
||||||
|
|
||||||
|
const automatedInstancesSinceDateTime = automated_since
|
||||||
|
? formatDateString(new Date(automated_since * 1000).toISOString())
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<RoutedTabs tabsArray={tabsArray} />
|
<RoutedTabs tabsArray={tabsArray} />
|
||||||
@@ -127,19 +134,23 @@ function SubscriptionDetail() {
|
|||||||
label={t`Hosts imported`}
|
label={t`Hosts imported`}
|
||||||
value={license_info.current_instances}
|
value={license_info.current_instances}
|
||||||
/>
|
/>
|
||||||
<Detail
|
{typeof automatedInstancesCount !== 'undefined' &&
|
||||||
dataCy="subscription-hosts-automated"
|
automatedInstancesCount !== null && (
|
||||||
label={t`Hosts automated`}
|
<Detail
|
||||||
value={
|
dataCy="subscription-hosts-automated"
|
||||||
<>
|
label={t`Hosts automated`}
|
||||||
{license_info.automated_instances} <Trans>since</Trans>{' '}
|
value={
|
||||||
{license_info.automated_since &&
|
automated_since ? (
|
||||||
formatDateString(
|
<Trans>
|
||||||
new Date(license_info.automated_since * 1000).toISOString()
|
{automatedInstancesCount} since{' '}
|
||||||
)}
|
{automatedInstancesSinceDateTime}
|
||||||
</>
|
</Trans>
|
||||||
}
|
) : (
|
||||||
/>
|
automatedInstancesCount
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<Detail
|
<Detail
|
||||||
dataCy="subscription-hosts-remaining"
|
dataCy="subscription-hosts-remaining"
|
||||||
label={t`Hosts remaining`}
|
label={t`Hosts remaining`}
|
||||||
|
|||||||
@@ -82,4 +82,17 @@ describe('<SubscriptionDetail />', () => {
|
|||||||
|
|
||||||
expect(wrapper.find('Button[aria-label="edit"]').length).toBe(1);
|
expect(wrapper.find('Button[aria-label="edit"]').length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should not render Hosts Automated Detail if license_info.automated_instances is undefined', () => {
|
||||||
|
wrapper = mountWithContexts(<SubscriptionDetail />, {
|
||||||
|
context: {
|
||||||
|
config: {
|
||||||
|
...config,
|
||||||
|
license_info: { ...config.license_info, automated_instances: null },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(wrapper.find(`Detail[label="Hosts automated"]`).length).toBe(0);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import DeleteButton from 'components/DeleteButton';
|
|||||||
import ErrorDetail from 'components/ErrorDetail';
|
import ErrorDetail from 'components/ErrorDetail';
|
||||||
import { LaunchButton } from 'components/LaunchButton';
|
import { LaunchButton } from 'components/LaunchButton';
|
||||||
import { VariablesDetail } from 'components/CodeEditor';
|
import { VariablesDetail } from 'components/CodeEditor';
|
||||||
|
import { VERBOSITY } from 'components/VerbositySelectField';
|
||||||
import { JobTemplatesAPI } from 'api';
|
import { JobTemplatesAPI } from 'api';
|
||||||
import useRequest, { useDismissableError } from 'hooks/useRequest';
|
import useRequest, { useDismissableError } from 'hooks/useRequest';
|
||||||
import useBrandName from 'hooks/useBrandName';
|
import useBrandName from 'hooks/useBrandName';
|
||||||
@@ -104,17 +105,6 @@ function JobTemplateDetail({ template }) {
|
|||||||
relatedResourceDeleteRequests.template(template);
|
relatedResourceDeleteRequests.template(template);
|
||||||
const canLaunch =
|
const canLaunch =
|
||||||
summary_fields.user_capabilities && summary_fields.user_capabilities.start;
|
summary_fields.user_capabilities && summary_fields.user_capabilities.start;
|
||||||
const verbosityOptions = [
|
|
||||||
{ verbosity: 0, details: t`0 (Normal)` },
|
|
||||||
{ verbosity: 1, details: t`1 (Verbose)` },
|
|
||||||
{ verbosity: 2, details: t`2 (More Verbose)` },
|
|
||||||
{ verbosity: 3, details: t`3 (Debug)` },
|
|
||||||
{ verbosity: 4, details: t`4 (Connection Debug)` },
|
|
||||||
{ verbosity: 5, details: t`5 (WinRM Debug)` },
|
|
||||||
];
|
|
||||||
const verbosityDetails = verbosityOptions.filter(
|
|
||||||
(option) => option.verbosity === verbosity
|
|
||||||
);
|
|
||||||
const generateCallBackUrl = `${window.location.origin + url}callback/`;
|
const generateCallBackUrl = `${window.location.origin + url}callback/`;
|
||||||
const renderOptionsField =
|
const renderOptionsField =
|
||||||
become_enabled ||
|
become_enabled ||
|
||||||
@@ -272,7 +262,7 @@ function JobTemplateDetail({ template }) {
|
|||||||
/>
|
/>
|
||||||
<Detail
|
<Detail
|
||||||
label={t`Verbosity`}
|
label={t`Verbosity`}
|
||||||
value={verbosityDetails[0].details}
|
value={VERBOSITY()[verbosity]}
|
||||||
dataCy="jt-detail-verbosity"
|
dataCy="jt-detail-verbosity"
|
||||||
helpText={helpText.verbosity}
|
helpText={helpText.verbosity}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ function AnswerTypeField() {
|
|||||||
labelIcon={
|
labelIcon={
|
||||||
<Popover
|
<Popover
|
||||||
content={t`Choose an answer type or format you want as the prompt for the user.
|
content={t`Choose an answer type or format you want as the prompt for the user.
|
||||||
Refer to the Ansible Tower Documentation for more additional
|
Refer to the Ansible Controller Documentation for more additional
|
||||||
information about each option.`}
|
information about each option.`}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
@@ -266,8 +266,8 @@ function SurveyQuestionForm({
|
|||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noreferrer"
|
rel="noreferrer"
|
||||||
>
|
>
|
||||||
{t`documentation`}{' '}
|
{t`documentation`}
|
||||||
</a>
|
</a>{' '}
|
||||||
{t`for more information.`}
|
{t`for more information.`}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,11 +87,9 @@ function NodeModalForm({
|
|||||||
const initialExtraVars =
|
const initialExtraVars =
|
||||||
launchConfig.ask_variables_on_launch && (values.extra_vars || '---');
|
launchConfig.ask_variables_on_launch && (values.extra_vars || '---');
|
||||||
if (surveyConfig?.spec) {
|
if (surveyConfig?.spec) {
|
||||||
extraVars = yaml.safeDump(
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, surveyValues));
|
||||||
mergeExtraVars(initialExtraVars, surveyValues)
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
extraVars = yaml.safeDump(mergeExtraVars(initialExtraVars, {}));
|
extraVars = yaml.dump(mergeExtraVars(initialExtraVars, {}));
|
||||||
}
|
}
|
||||||
values.extra_data = extraVars && parseVariableField(extraVars);
|
values.extra_data = extraVars && parseVariableField(extraVars);
|
||||||
delete values.extra_vars;
|
delete values.extra_vars;
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user