From 6b73fb2c277248d60bdab073bc9d7a76175fab7c Mon Sep 17 00:00:00 2001 From: Matthew Jones Date: Thu, 7 Jul 2016 12:40:10 -0400 Subject: [PATCH] Revert "Merge branch 'release_3.0.0' into devel" This reverts commit 3cedfe6c679e5b289bd0a27defb6198d063ba8e8. --- MANIFEST.in | 1 + Makefile | 12 +- awx/api/filters.py | 2 +- awx/api/generics.py | 7 - awx/api/serializers.py | 121 +- .../templates/api/job_template_survey_spec.md | 5 +- .../templates/api/sub_list_create_api_view.md | 2 +- awx/api/urls.py | 18 +- awx/api/views.py | 102 +- awx/main/access.py | 107 +- .../management/commands/inventory_import.py | 2 +- awx/main/migrations/0008_v300_rbac_changes.py | 6 +- .../0017_v300_prompting_migrations.py | 2 - .../0024_v300_jobtemplate_allow_simul.py | 19 - awx/main/migrations/_rbac.py | 85 +- awx/main/models/credential.py | 13 +- awx/main/models/jobs.py | 98 +- awx/main/models/unified_jobs.py | 4 +- awx/main/signals.py | 16 +- awx/main/tasks.py | 46 +- awx/main/tests/conftest.py | 41 - awx/main/tests/factories/README.md | 65 - awx/main/tests/factories/__init__.py | 18 - awx/main/tests/factories/exc.py | 5 - awx/main/tests/factories/fixtures.py | 150 --- awx/main/tests/factories/objects.py | 59 - awx/main/tests/factories/tower.py | 332 ----- .../functional/api/test_activity_streams.py | 21 - awx/main/tests/functional/api/test_adhoc.py | 148 --- .../tests/functional/api/test_credential.py | 3 +- .../functional/api/test_job_runtime_params.py | 87 +- .../tests/functional/api/test_job_template.py | 335 ----- .../tests/functional/api/test_survey_spec.py | 200 --- .../functional/api/test_survey_spec_view.py | 135 ++ awx/main/tests/functional/conftest.py | 82 +- .../functional/test_fixture_factories.py | 106 -- awx/main/tests/functional/test_jobs.py | 13 - awx/main/tests/functional/test_projects.py | 92 +- awx/main/tests/functional/test_rbac_api.py | 8 +- .../tests/functional/test_rbac_credential.py | 8 - awx/main/tests/functional/test_rbac_job.py | 72 -- .../functional/test_rbac_job_templates.py | 26 - awx/main/tests/functional/test_rbac_label.py | 20 +- .../functional/test_rbac_notifications.py | 39 +- awx/main/tests/old/ad_hoc.py | 250 ++++ awx/main/tests/old/inventory.py | 1 - awx/main/tests/old/jobs/jobs_monolithic.py | 2 +- awx/main/tests/unit/api/test_serializers.py | 23 +- .../unit/models/test_job_template_unit.py | 40 - awx/main/tests/unit/models/test_job_unit.py | 39 - awx/plugins/inventory/ec2.py | 209 +--- awx/settings/defaults.py | 1 - awx/sso/backends.py | 19 +- awx/sso/pipeline.py | 6 +- awx/static/api/api.css | 48 +- awx/static/favicon.ico | Bin 15086 -> 6518 bytes awx/ui/client/assets/favicon.ico | Bin 15086 -> 6518 bytes awx/ui/client/legacy-styles/ansible-ui.less | 14 +- awx/ui/client/legacy-styles/forms.less | 63 +- awx/ui/client/legacy-styles/job-details.less | 7 +- .../client/lib/lrInfiniteScroll/.bower.json | 32 - awx/ui/client/lib/lrInfiniteScroll/index.js | 2 - .../lib/lrInfiniteScroll/lrInfiniteScroll.js | 17 +- awx/ui/client/src/about/about.controller.js | 10 +- .../addPermissions.controller.js | 12 +- .../addPermissions.partial.html | 4 +- .../addPermissionsList.directive.js | 18 - .../permissionsTeams.list.js | 6 +- .../permissionsUsers.list.js | 3 +- awx/ui/client/src/access/roleList.block.less | 2 +- .../client/src/access/roleList.directive.js | 2 +- .../activity-stream/activitystream.route.js | 27 +- .../stream-dropdown-nav.directive.js | 2 +- .../manage => }/adhoc/adhoc.controller.js | 24 +- .../manage => }/adhoc/adhoc.form.js | 7 +- .../manage => }/adhoc/adhoc.partial.html | 0 awx/ui/client/src/adhoc/adhoc.route.js | 14 + awx/ui/client/src/adhoc/main.js | 10 + awx/ui/client/src/app.js | 111 +- .../src/bread-crumb/bread-crumb.block.less | 22 +- .../src/bread-crumb/bread-crumb.directive.js | 90 +- .../src/bread-crumb/bread-crumb.partial.html | 7 +- awx/ui/client/src/controllers/Credentials.js | 60 +- awx/ui/client/src/controllers/Jobs.js | 52 +- awx/ui/client/src/controllers/Projects.js | 35 +- awx/ui/client/src/controllers/Teams.js | 3 - awx/ui/client/src/controllers/Users.js | 9 +- awx/ui/client/src/credentials/main.js | 11 - .../src/credentials/ownerList.directive.js | 13 - .../src/credentials/ownerList.partial.html | 5 - .../counts/dashboard-counts.directive.js | 4 +- .../graphs/dashboard-graphs.block.less | 1 - .../dashboard/hosts/dashboard-hosts.form.js | 4 +- .../dashboard/hosts/dashboard-hosts.list.js | 2 +- .../dashboard/hosts/dashboard-hosts.route.js | 3 + .../lists/jobs/jobs-list.partial.html | 11 +- awx/ui/client/src/forms/Credentials.js | 26 +- awx/ui/client/src/forms/Groups.js | 82 +- awx/ui/client/src/forms/Hosts.js | 2 +- awx/ui/client/src/forms/Inventories.js | 6 +- awx/ui/client/src/forms/JobTemplates.js | 104 +- awx/ui/client/src/forms/Organizations.js | 7 +- awx/ui/client/src/forms/Projects.js | 53 +- awx/ui/client/src/forms/Teams.js | 13 +- awx/ui/client/src/forms/Users.js | 3 +- awx/ui/client/src/help/InventoryGroups.js | 4 +- awx/ui/client/src/helpers/ActivityStream.js | 4 +- awx/ui/client/src/helpers/Credentials.js | 2 + awx/ui/client/src/helpers/Groups.js | 1106 ++++++++++++++++- awx/ui/client/src/helpers/Hosts.js | 785 +++++++++++- awx/ui/client/src/helpers/JobDetail.js | 54 +- awx/ui/client/src/helpers/JobTemplates.js | 9 +- awx/ui/client/src/helpers/Jobs.js | 131 +- awx/ui/client/src/helpers/Parse.js | 25 +- awx/ui/client/src/helpers/Schedules.js | 104 +- awx/ui/client/src/helpers/inventory.js | 213 ++++ .../inventories/edit/inventory-edit.route.js | 8 +- .../src/inventories/inventories.partial.html | 10 +- .../list/inventory-list.controller.js | 5 +- .../inventories/list/inventory-list.route.js | 2 +- .../inventories/manage/adhoc/adhoc.route.js | 27 - .../src/inventories/manage/adhoc/main.js | 11 - .../manage/breadcrumbs/breadcrumbs.block.less | 25 - .../breadcrumbs/breadcrumbs.controller.js | 27 - .../breadcrumbs/breadcrumbs.partial.html | 37 - .../copy-move/copy-move-groups.controller.js | 87 -- .../copy-move/copy-move-hosts.controller.js | 65 - .../manage/copy-move/copy-move.partial.html | 21 - .../manage/copy-move/copy-move.route.js | 51 - .../manage/copy/copy-groups.controller.js | 306 +++++ .../manage/copy/copy-groups.partial.html | 22 + .../manage/copy/copy-hosts.controller.js | 239 ++++ .../manage/copy/copy-hosts.partial.html | 23 + .../copy.block.less} | 17 +- .../manage/copy/copy.controller.js | 16 + .../inventories/manage/copy/copy.partial.html | 10 + .../src/inventories/manage/copy/copy.route.js | 54 + .../manage/{copy-move => copy}/main.js | 9 +- .../manage/groups/groups-add.controller.js | 215 ---- .../manage/groups/groups-edit.controller.js | 288 ----- .../manage/groups/groups-list.controller.js | 159 --- .../manage/groups/groups-list.partial.html | 73 -- .../manage/groups/groups.block.less | 19 - .../inventories/manage/groups/groups.route.js | 51 - .../manage/groups/groups.service.js | 113 -- .../src/inventories/manage/groups/main.js | 14 - .../manage/hosts/hosts-list.controller.js | 84 -- .../inventories/manage/hosts/hosts.route.js | 50 - .../inventories/manage/hosts/hosts.service.js | 84 -- .../manage/inventory-manage.block.less | 3 - .../manage/inventory-manage.controller.js | 544 +++++++- .../manage/inventory-manage.partial.html | 150 ++- .../manage/inventory-manage.route.js | 61 +- .../manage/inventory-manage.service.js | 63 - awx/ui/client/src/inventories/manage/main.js | 23 +- .../manage-groups.directive.controller.js | 574 +++++++++ .../directive/manage-groups.directive.js | 25 + .../manage-groups.directive.partial.html | 5 + .../inventories/manage/manage-groups/main.js | 16 + .../manage-groups.partial.html} | 1 + .../manage-groups/manage-groups.route.js | 36 + .../manage/{hosts => manage-hosts}/main.js | 4 +- .../manage-hosts-add.controller.js} | 20 +- .../manage-hosts-edit.controller.js} | 8 +- .../manage-hosts.partial.html} | 0 .../manage/manage-hosts/manage-hosts.route.js | 41 + .../manage-hosts/manage-hosts.service.js | 53 + .../src/inventories/manage/manage.block.less | 18 + .../inventory-scripts/edit/edit.controller.js | 3 +- .../src/inventory-scripts/edit/edit.route.js | 4 - .../inventory-scripts/list/list.controller.js | 7 +- .../host-event-codemirror.partial.html | 2 - .../host-event-details.partial.html | 5 +- .../host-event/host-event-json.partial.html | 2 + .../host-event/host-event-modal.partial.html | 19 +- .../host-event/host-event-stdout.partial.html | 2 + .../host-event/host-event.block.less | 57 +- .../host-event/host-event.controller.js | 76 +- .../job-detail/host-event/host-event.route.js | 24 +- .../client/src/job-detail/host-event/main.js | 5 +- .../host-events/host-events.block.less | 14 +- .../host-events/host-events.partial.html | 8 +- .../host-events/host-events.route.js | 2 +- .../host-summary/host-summary.block.less | 8 +- .../host-summary/host-summary.partial.html | 6 +- .../host-summary/host-summary.route.js | 17 +- .../src/job-detail/job-detail.block.less | 51 +- .../src/job-detail/job-detail.controller.js | 83 +- .../src/job-detail/job-detail.partial.html | 20 +- .../src/job-detail/job-detail.service.js | 29 +- .../launchjob.factory.js | 27 +- .../job-submission/job-submission.block.less | 13 +- .../job-submission.controller.js | 24 +- .../job-submission.partial.html | 4 +- .../add/job-templates-add.controller.js | 63 +- .../copy/job-templates-copy.controller.js | 2 +- .../inventory-job-templates-edit.route.js | 4 +- .../edit/job-templates-edit.controller.js | 141 +-- .../edit/job-templates-edit.route.js | 8 +- .../labels/labelsList.block.less | 41 +- .../labels/labelsList.directive.js | 40 +- .../labels/labelsList.partial.html | 11 +- .../list/job-templates-list.controller.js | 5 +- .../list/job-templates-list.route.js | 5 + .../shared/question-definition.form.js | 22 +- .../survey-maker/survey-maker.block.less | 10 - .../survey-maker/surveys/init.factory.js | 20 +- .../src/license/checkLicense.factory.js | 92 +- awx/ui/client/src/license/license.block.less | 1 + .../client/src/license/license.controller.js | 48 +- .../client/src/license/license.partial.html | 3 +- awx/ui/client/src/license/main.js | 2 +- awx/ui/client/src/lists/AllJobs.js | 2 +- awx/ui/client/src/lists/CompletedJobs.js | 10 +- awx/ui/client/src/lists/Credentials.js | 11 +- awx/ui/client/src/lists/Groups.js | 35 +- awx/ui/client/src/lists/Inventories.js | 12 +- awx/ui/client/src/lists/InventoryGroups.js | 96 +- awx/ui/client/src/lists/InventoryHosts.js | 44 +- awx/ui/client/src/lists/JobTemplates.js | 4 +- awx/ui/client/src/lists/ScheduledJobs.js | 37 +- awx/ui/client/src/lists/Streams.js | 206 ++- .../authentication.service.js | 34 +- .../authenticationServices/pendo.service.js | 6 +- .../authenticationServices/timer.factory.js | 10 +- .../login/loginModal/loginModal.controller.js | 24 +- awx/ui/client/src/login/logout.route.js | 4 +- awx/ui/client/src/lookup/lookup.factory.js | 3 +- .../client/src/main-menu/main-menu.block.less | 24 +- .../src/main-menu/main-menu.directive.js | 3 - .../src/main-menu/main-menu.partial.html | 35 +- .../management-jobs/card/card.controller.js | 12 +- .../management-jobs/card/card.partial.html | 2 +- .../src/management-jobs/card/card.route.js | 2 +- .../management-jobs/card/mgmtcards.block.less | 50 +- .../notifications/notification.route.js | 6 +- .../src/management-jobs/scheduler/main.js | 18 +- .../scheduler/schedulerForm.partial.html | 49 +- .../src/notifications/add/add.controller.js | 46 +- .../client/src/notifications/add/add.route.js | 5 + .../src/notifications/edit/edit.controller.js | 66 +- .../src/notifications/edit/edit.route.js | 2 +- .../list.controller.js | 10 +- .../notificationTemplates.form.js | 38 +- .../src/notifications/notifications.list.js | 3 +- .../shared/type-change.service.js | 3 +- .../add/organizations-add.route.js | 5 + .../edit/organizations-edit.route.js | 2 +- .../linkout/addUsers/addUsers.partial.html | 2 +- .../organizations-admins.controller.js | 100 -- .../organizations-inventories.controller.js | 343 ----- .../organizations-job-templates.controller.js | 91 -- .../organizations-projects.controller.js | 350 ------ .../organizations-teams.controller.js | 93 -- .../organizations-users.controller.js | 99 -- .../organizations-linkout.controller.js | 100 ++ .../linkout/organizations-linkout.route.js | 43 +- .../list/organizations-list.controller.js | 108 +- .../list/organizations-list.partial.html | 7 +- .../src/organizations/orgcards.block.less | 16 - awx/ui/client/src/partials/breadcrumb.html | 4 +- awx/ui/client/src/partials/jobs.html | 2 +- .../src/partials/survey-maker-modal.html | 3 +- .../src/permissions/add/user-add.route.js | 7 +- .../src/permissions/edit/user-edit.route.js | 7 +- .../src/portal-mode/portal-mode.block.less | 1 + .../src/portal-mode/portal-mode.route.js | 9 +- .../client/src/rest/interceptors.service.js | 8 +- awx/ui/client/src/scheduler/main.js | 55 +- .../repeatFrequencyOptions.block.less | 9 - .../src/scheduler/scheduler.controller.js | 12 +- .../src/scheduler/schedulerAdd.controller.js | 5 +- .../src/scheduler/schedulerEdit.controller.js | 10 +- .../src/scheduler/schedulerForm.partial.html | 12 +- awx/ui/client/src/search/tagSearch.block.less | 24 +- .../client/src/search/tagSearch.controller.js | 9 +- .../client/src/search/tagSearch.partial.html | 43 +- awx/ui/client/src/search/tagSearch.service.js | 6 - awx/ui/client/src/setup-menu/setup.route.js | 2 +- awx/ui/client/src/shared/InventoryTree.js | 609 +++++++++ awx/ui/client/src/shared/Modal.js | 2 +- awx/ui/client/src/shared/Socket.js | 10 +- .../src/shared/branding/colors.default.less | 7 +- .../src/shared/config/config.service.js | 59 - awx/ui/client/src/shared/config/main.js | 11 - .../src/shared/features/features.service.js | 46 +- awx/ui/client/src/shared/form-generator.js | 124 +- awx/ui/client/src/shared/generator-helpers.js | 22 +- .../src/shared/layouts/one-plus-one.less | 2 +- .../list-generator/list-generator.factory.js | 37 +- .../select-list-item.directive.js | 16 +- .../shared/pagination/pagination.service.js | 53 +- .../src/shared/stateExtender.provider.js | 20 +- .../adhoc/standard-out-adhoc.partial.html | 15 +- .../standard-out-inventory-sync.partial.html | 15 +- .../log/standard-out-log.controller.js | 80 +- .../log/standard-out-log.directive.js | 1 - .../log/standard-out-log.partial.html | 5 +- .../standard-out-management-jobs.partial.html | 14 +- .../standard-out-scm-update.partial.html | 15 +- .../src/standard-out/standard-out.block.less | 42 +- .../standard-out/standard-out.controller.js | 54 +- .../fact-data-table.block.less | 14 +- .../system-tracking.partial.html | 6 +- awx/ui/client/src/widgets/Stream.js | 102 +- .../tests/adhoc/adhoc.controller-test.js | 2 +- .../tests/features/features.service-test.js | 57 + awx/ui/templates/ui/index.html | 6 +- config/awx-httpd-443.conf | 1 + config/awx-munin-el.conf | 12 + config/awx-munin-ubuntu.conf | 17 + config/awx-munin.conf | 11 + config/awx_munin_tower_jobs | 3 + npm-shrinkwrap.json | 829 ++++++++---- requirements/requirements.txt | 6 +- requirements/requirements_ansible.txt | 4 +- setup.py | 20 +- tools/docker-compose.yml | 63 +- tools/docker-compose/Dockerfile | 5 +- tools/docker-compose/Dockerfile-sync | 10 - .../ansible_tower.egg-info/SOURCES.txt | 15 + 321 files changed, 8400 insertions(+), 8261 deletions(-) delete mode 100644 awx/main/migrations/0024_v300_jobtemplate_allow_simul.py delete mode 100644 awx/main/tests/conftest.py delete mode 100644 awx/main/tests/factories/README.md delete mode 100644 awx/main/tests/factories/__init__.py delete mode 100644 awx/main/tests/factories/exc.py delete mode 100644 awx/main/tests/factories/fixtures.py delete mode 100644 awx/main/tests/factories/objects.py delete mode 100644 awx/main/tests/factories/tower.py delete mode 100644 awx/main/tests/functional/api/test_adhoc.py delete mode 100644 awx/main/tests/functional/api/test_job_template.py delete mode 100644 awx/main/tests/functional/api/test_survey_spec.py create mode 100644 awx/main/tests/functional/api/test_survey_spec_view.py delete mode 100644 awx/main/tests/functional/test_fixture_factories.py delete mode 100644 awx/main/tests/functional/test_rbac_job.py delete mode 100644 awx/main/tests/unit/models/test_job_template_unit.py delete mode 100644 awx/main/tests/unit/models/test_job_unit.py delete mode 100644 awx/ui/client/lib/lrInfiniteScroll/.bower.json delete mode 100644 awx/ui/client/lib/lrInfiniteScroll/index.js rename awx/ui/client/src/{inventories/manage => }/adhoc/adhoc.controller.js (94%) rename awx/ui/client/src/{inventories/manage => }/adhoc/adhoc.form.js (97%) rename awx/ui/client/src/{inventories/manage => }/adhoc/adhoc.partial.html (100%) create mode 100644 awx/ui/client/src/adhoc/adhoc.route.js create mode 100644 awx/ui/client/src/adhoc/main.js delete mode 100644 awx/ui/client/src/credentials/main.js delete mode 100644 awx/ui/client/src/credentials/ownerList.directive.js delete mode 100644 awx/ui/client/src/credentials/ownerList.partial.html delete mode 100644 awx/ui/client/src/inventories/manage/adhoc/adhoc.route.js delete mode 100644 awx/ui/client/src/inventories/manage/adhoc/main.js delete mode 100644 awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.block.less delete mode 100644 awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.partial.html delete mode 100644 awx/ui/client/src/inventories/manage/copy-move/copy-move-groups.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/copy-move/copy-move-hosts.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/copy-move/copy-move.partial.html delete mode 100644 awx/ui/client/src/inventories/manage/copy-move/copy-move.route.js create mode 100644 awx/ui/client/src/inventories/manage/copy/copy-groups.controller.js create mode 100644 awx/ui/client/src/inventories/manage/copy/copy-groups.partial.html create mode 100644 awx/ui/client/src/inventories/manage/copy/copy-hosts.controller.js create mode 100644 awx/ui/client/src/inventories/manage/copy/copy-hosts.partial.html rename awx/ui/client/src/inventories/manage/{copy-move/copy-move.block.less => copy/copy.block.less} (69%) create mode 100644 awx/ui/client/src/inventories/manage/copy/copy.controller.js create mode 100644 awx/ui/client/src/inventories/manage/copy/copy.partial.html create mode 100644 awx/ui/client/src/inventories/manage/copy/copy.route.js rename awx/ui/client/src/inventories/manage/{copy-move => copy}/main.js (53%) delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups-add.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups-edit.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups-list.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups-list.partial.html delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups.block.less delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups.route.js delete mode 100644 awx/ui/client/src/inventories/manage/groups/groups.service.js delete mode 100644 awx/ui/client/src/inventories/manage/groups/main.js delete mode 100644 awx/ui/client/src/inventories/manage/hosts/hosts-list.controller.js delete mode 100644 awx/ui/client/src/inventories/manage/hosts/hosts.route.js delete mode 100644 awx/ui/client/src/inventories/manage/hosts/hosts.service.js delete mode 100644 awx/ui/client/src/inventories/manage/inventory-manage.block.less delete mode 100644 awx/ui/client/src/inventories/manage/inventory-manage.service.js create mode 100644 awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.controller.js create mode 100644 awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.js create mode 100644 awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.partial.html create mode 100644 awx/ui/client/src/inventories/manage/manage-groups/main.js rename awx/ui/client/src/inventories/manage/{groups/groups-form.partial.html => manage-groups/manage-groups.partial.html} (77%) create mode 100644 awx/ui/client/src/inventories/manage/manage-groups/manage-groups.route.js rename awx/ui/client/src/inventories/manage/{hosts => manage-hosts}/main.js (70%) rename awx/ui/client/src/inventories/manage/{hosts/hosts-add.controller.js => manage-hosts/manage-hosts-add.controller.js} (66%) rename awx/ui/client/src/inventories/manage/{hosts/hosts-edit.controller.js => manage-hosts/manage-hosts-edit.controller.js} (88%) rename awx/ui/client/src/inventories/manage/{hosts/hosts-form.partial.html => manage-hosts/manage-hosts.partial.html} (100%) create mode 100644 awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.route.js create mode 100644 awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.service.js create mode 100644 awx/ui/client/src/inventories/manage/manage.block.less delete mode 100644 awx/ui/client/src/job-detail/host-event/host-event-codemirror.partial.html create mode 100644 awx/ui/client/src/job-detail/host-event/host-event-json.partial.html create mode 100644 awx/ui/client/src/job-detail/host-event/host-event-stdout.partial.html delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-admins.controller.js delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-inventories.controller.js delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-job-templates.controller.js delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-projects.controller.js delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-teams.controller.js delete mode 100644 awx/ui/client/src/organizations/linkout/controllers/organizations-users.controller.js create mode 100644 awx/ui/client/src/organizations/linkout/organizations-linkout.controller.js create mode 100644 awx/ui/client/src/shared/InventoryTree.js delete mode 100644 awx/ui/client/src/shared/config/config.service.js delete mode 100644 awx/ui/client/src/shared/config/main.js create mode 100644 awx/ui/client/tests/features/features.service-test.js create mode 100644 config/awx-munin-el.conf create mode 100644 config/awx-munin-ubuntu.conf create mode 100644 config/awx-munin.conf create mode 100644 config/awx_munin_tower_jobs delete mode 100644 tools/docker-compose/Dockerfile-sync diff --git a/MANIFEST.in b/MANIFEST.in index b52764c7e8..f03e71b81d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -18,6 +18,7 @@ include tools/scripts/request_tower_configuration.sh include tools/scripts/request_tower_configuration.ps1 include tools/scripts/ansible-tower-service include tools/scripts/tower-python +include tools/munin_monitors/* include tools/sosreport/* include COPYING include Makefile diff --git a/Makefile b/Makefile index b575007ad1..aafc171594 100644 --- a/Makefile +++ b/Makefile @@ -258,9 +258,7 @@ virtualenv_ansible: mkdir $(VENV_BASE); \ fi; \ if [ ! -d "$(VENV_BASE)/ansible" ]; then \ - virtualenv --system-site-packages --setuptools $(VENV_BASE)/ansible && \ - $(VENV_BASE)/ansible/bin/pip install -I setuptools==23.0.0 && \ - $(VENV_BASE)/ansible/bin/pip install -I pip==8.1.1; \ + virtualenv --system-site-packages $(VENV_BASE)/ansible; \ fi; \ fi @@ -270,17 +268,17 @@ virtualenv_tower: mkdir $(VENV_BASE); \ fi; \ if [ ! -d "$(VENV_BASE)/tower" ]; then \ - virtualenv --system-site-packages --setuptools $(VENV_BASE)/tower && \ - $(VENV_BASE)/tower/bin/pip install -I setuptools==23.0.0 && \ - $(VENV_BASE)/tower/bin/pip install -I pip==8.1.1; \ + virtualenv --system-site-packages $(VENV_BASE)/tower; \ fi; \ fi requirements_ansible: virtualenv_ansible if [ "$(VENV_BASE)" ]; then \ . $(VENV_BASE)/ansible/bin/activate; \ + $(VENV_BASE)/ansible/bin/pip install -U pip==8.1.1; \ $(VENV_BASE)/ansible/bin/pip install -r requirements/requirements_ansible.txt ;\ else \ + pip install -U pip==8.1.1; \ pip install -r requirements/requirements_ansible.txt ; \ fi @@ -288,8 +286,10 @@ requirements_ansible: virtualenv_ansible requirements_tower: virtualenv_tower if [ "$(VENV_BASE)" ]; then \ . $(VENV_BASE)/tower/bin/activate; \ + $(VENV_BASE)/tower/bin/pip install -U pip==8.1.1; \ $(VENV_BASE)/tower/bin/pip install -r requirements/requirements.txt ;\ else \ + pip install -U pip==8.1.1; \ pip install -r requirements/requirements.txt ; \ fi diff --git a/awx/api/filters.py b/awx/api/filters.py index f4e65a8d82..d023b2aa08 100644 --- a/awx/api/filters.py +++ b/awx/api/filters.py @@ -219,7 +219,7 @@ class FieldLookupBackend(BaseFilterBackend): else: q = Q(**{k:v}) queryset = queryset.filter(q) - queryset = queryset.filter(*args).distinct() + queryset = queryset.filter(*args) return queryset except (FieldError, FieldDoesNotExist, ValueError), e: raise ParseError(e.args[0]) diff --git a/awx/api/generics.py b/awx/api/generics.py index 37b4561bc1..fe1ecd5659 100644 --- a/awx/api/generics.py +++ b/awx/api/generics.py @@ -360,13 +360,6 @@ class SubListCreateAttachDetachAPIView(SubListCreateAPIView): # Base class for a sublist view that allows for creating subobjects and # attaching/detaching them from the parent. - def get_description_context(self): - d = super(SubListCreateAttachDetachAPIView, self).get_description_context() - d.update({ - "has_attach": True, - }) - return d - def attach(self, request, *args, **kwargs): created = False parent = self.get_parent_object() diff --git a/awx/api/serializers.py b/awx/api/serializers.py index 3d7508a1fa..0280b0f09f 100644 --- a/awx/api/serializers.py +++ b/awx/api/serializers.py @@ -23,7 +23,6 @@ from django.db import models # from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_text from django.utils.text import capfirst -from django.forms.models import model_to_dict # Django REST Framework from rest_framework.exceptions import ValidationError @@ -40,6 +39,7 @@ from awx.main.constants import SCHEDULEABLE_PROVIDERS from awx.main.models import * # noqa from awx.main.fields import ImplicitRoleField from awx.main.utils import get_type_for_model, get_model_for_type, build_url, timestamp_apiformat, camelcase_to_underscore, getattrd +from awx.main.redact import REPLACE_STR from awx.main.conf import tower_settings from awx.api.license import feature_enabled @@ -331,7 +331,7 @@ class BaseSerializer(serializers.ModelSerializer): 'description': role.description, } if len(roles) > 0: - summary_fields['object_roles'] = roles + summary_fields['roles'] = roles return summary_fields def get_created(self, obj): @@ -679,14 +679,13 @@ class UserSerializer(BaseSerializer): password = serializers.CharField(required=False, default='', write_only=True, help_text='Write-only field used to change the password.') ldap_dn = serializers.CharField(source='profile.ldap_dn', read_only=True) - external_account = serializers.SerializerMethodField(help_text='Set if the account is managed by an external service') is_system_auditor = serializers.BooleanField(default=False) class Meta: model = User fields = ('*', '-name', '-description', '-modified', '-summary_fields', 'username', 'first_name', 'last_name', - 'email', 'is_superuser', 'is_system_auditor', 'password', 'ldap_dn', 'external_account') + 'email', 'is_superuser', 'is_system_auditor', 'password', 'ldap_dn') def to_representation(self, obj): ret = super(UserSerializer, self).to_representation(obj) @@ -720,8 +719,6 @@ class UserSerializer(BaseSerializer): getattr(settings, 'SOCIAL_AUTH_GITHUB_TEAM_KEY', None) or getattr(settings, 'SOCIAL_AUTH_SAML_ENABLED_IDPS', None)) and obj.social_auth.all(): new_password = None - if obj.pk and getattr(settings, 'RADIUS_SERVER', '') and not obj.has_usable_password(): - new_password = None if new_password: obj.set_password(new_password) obj.save(update_fields=['password']) @@ -729,24 +726,6 @@ class UserSerializer(BaseSerializer): obj.set_unusable_password() obj.save(update_fields=['password']) - def get_external_account(self, obj): - account_type = None - if getattr(settings, 'AUTH_LDAP_SERVER_URI', None) and feature_enabled('ldap'): - try: - if obj.pk and obj.profile.ldap_dn and not obj.has_usable_password(): - account_type = "ldap" - except AttributeError: - pass - if (getattr(settings, 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', None) or - getattr(settings, 'SOCIAL_AUTH_GITHUB_KEY', None) or - getattr(settings, 'SOCIAL_AUTH_GITHUB_ORG_KEY', None) or - getattr(settings, 'SOCIAL_AUTH_GITHUB_TEAM_KEY', None) or - getattr(settings, 'SOCIAL_AUTH_SAML_ENABLED_IDPS', None)) and obj.social_auth.all(): - account_type = "social" - if obj.pk and getattr(settings, 'RADIUS_SERVER', '') and not obj.has_usable_password(): - account_type = "radius" - return account_type - def create(self, validated_data): new_password = validated_data.pop('password', None) obj = super(UserSerializer, self).create(validated_data) @@ -768,7 +747,6 @@ class UserSerializer(BaseSerializer): projects = reverse('api:user_projects_list', args=(obj.pk,)), credentials = reverse('api:user_credentials_list', args=(obj.pk,)), roles = reverse('api:user_roles_list', args=(obj.pk,)), - object_roles = reverse('api:user_object_roles_list', args=(obj.pk,)), activity_stream = reverse('api:user_activity_stream_list', args=(obj.pk,)), access_list = reverse('api:user_access_list', args=(obj.pk,)), )) @@ -826,7 +804,7 @@ class OrganizationSerializer(BaseSerializer): notification_templates_any = reverse('api:organization_notification_templates_any_list', args=(obj.pk,)), notification_templates_success = reverse('api:organization_notification_templates_success_list', args=(obj.pk,)), notification_templates_error = reverse('api:organization_notification_templates_error_list', args=(obj.pk,)), - object_roles = reverse('api:organization_object_roles_list', args=(obj.pk,)), + roles = reverse('api:organization_roles_list', args=(obj.pk,)), access_list = reverse('api:organization_access_list', args=(obj.pk,)), )) return res @@ -912,7 +890,7 @@ class ProjectSerializer(UnifiedJobTemplateSerializer, ProjectOptionsSerializer): notification_templates_success = reverse('api:project_notification_templates_success_list', args=(obj.pk,)), notification_templates_error = reverse('api:project_notification_templates_error_list', args=(obj.pk,)), access_list = reverse('api:project_access_list', args=(obj.pk,)), - object_roles = reverse('api:project_object_roles_list', args=(obj.pk,)), + roles = reverse('api:project_roles_list', args=(obj.pk,)), )) if obj.organization: res['organization'] = reverse('api:organization_detail', @@ -1016,7 +994,7 @@ class InventorySerializer(BaseSerializerWithVariables): scan_job_templates = reverse('api:inventory_scan_job_template_list', args=(obj.pk,)), ad_hoc_commands = reverse('api:inventory_ad_hoc_commands_list', args=(obj.pk,)), access_list = reverse('api:inventory_access_list', args=(obj.pk,)), - object_roles = reverse('api:inventory_object_roles_list', args=(obj.pk,)), + roles = reverse('api:inventory_roles_list', args=(obj.pk,)), #single_fact = reverse('api:inventory_single_fact_view', args=(obj.pk,)), )) if obj.organization: @@ -1188,7 +1166,7 @@ class GroupSerializer(BaseSerializerWithVariables): inventory_sources = reverse('api:group_inventory_sources_list', args=(obj.pk,)), ad_hoc_commands = reverse('api:group_ad_hoc_commands_list', args=(obj.pk,)), access_list = reverse('api:group_access_list', args=(obj.pk,)), - object_roles = reverse('api:group_object_roles_list', args=(obj.pk,)), + roles = reverse('api:group_roles_list', args=(obj.pk,)), #single_fact = reverse('api:group_single_fact_view', args=(obj.pk,)), )) if obj.inventory: @@ -1211,7 +1189,7 @@ class GroupSerializer(BaseSerializerWithVariables): class GroupTreeSerializer(GroupSerializer): - children = serializers.SerializerMethodField() + children = serializers.SerializerMethodField('get_children') class Meta: model = Group @@ -1287,7 +1265,7 @@ class CustomInventoryScriptSerializer(BaseSerializer): def get_related(self, obj): res = super(CustomInventoryScriptSerializer, self).get_related(obj) res.update(dict( - object_roles = reverse('api:inventory_script_object_roles_list', args=(obj.pk,)), + roles = reverse('api:inventory_script_roles_list', args=(obj.pk,)), )) if obj.organization: @@ -1456,7 +1434,6 @@ class TeamSerializer(BaseSerializer): users = reverse('api:team_users_list', args=(obj.pk,)), credentials = reverse('api:team_credentials_list', args=(obj.pk,)), roles = reverse('api:team_roles_list', args=(obj.pk,)), - object_roles = reverse('api:team_object_roles_list', args=(obj.pk,)), activity_stream = reverse('api:team_activity_stream_list', args=(obj.pk,)), access_list = reverse('api:team_access_list', args=(obj.pk,)), )) @@ -1611,6 +1588,8 @@ class ResourceAccessListElementSerializer(UserSerializer): return ret + + class CredentialSerializer(BaseSerializer): # FIXME: may want to make some fields filtered based on user accessing @@ -1619,7 +1598,7 @@ class CredentialSerializer(BaseSerializer): model = Credential fields = ('*', 'kind', 'cloud', 'host', 'username', 'password', 'security_token', 'project', 'domain', - 'ssh_key_data', 'ssh_key_unlock', 'organization', + 'ssh_key_data', 'ssh_key_unlock', 'become_method', 'become_username', 'become_password', 'vault_password', 'subscription', 'tenant', 'secret', 'client', 'authorize', 'authorize_password') @@ -1634,16 +1613,10 @@ class CredentialSerializer(BaseSerializer): def get_related(self, obj): res = super(CredentialSerializer, self).get_related(obj) - - if obj.organization: - res['organization'] = reverse('api:organization_detail', args=(obj.organization.pk,)) - res.update(dict( activity_stream = reverse('api:credential_activity_stream_list', args=(obj.pk,)), access_list = reverse('api:credential_access_list', args=(obj.pk,)), - object_roles = reverse('api:credential_object_roles_list', args=(obj.pk,)), - owner_users = reverse('api:credential_owner_users_list', args=(obj.pk,)), - owner_teams = reverse('api:credential_owner_teams_list', args=(obj.pk,)), + roles = reverse('api:credential_roles_list', args=(obj.pk,)), )) parents = obj.owner_role.parents.exclude(object_id__isnull=True) @@ -1662,7 +1635,6 @@ class CredentialSerializer(BaseSerializer): for user in obj.owner_role.members.all(): summary_dict['owners'].append({ 'id': user.pk, - 'type': 'user', 'name': user.username, 'description': ' '.join([user.first_name, user.last_name]), 'url': reverse('api:user_detail', args=(user.pk,)), @@ -1671,7 +1643,6 @@ class CredentialSerializer(BaseSerializer): for parent in obj.owner_role.parents.exclude(object_id__isnull=True).all(): summary_dict['owners'].append({ 'id': parent.content_object.pk, - 'type': camelcase_to_underscore(parent.content_object.__class__.__name__), 'name': parent.content_object.name, 'description': parent.content_object.description, 'url': parent.content_object.get_absolute_url(), @@ -1783,7 +1754,7 @@ class JobTemplateSerializer(UnifiedJobTemplateSerializer, JobOptionsSerializer): model = JobTemplate fields = ('*', 'host_config_key', 'ask_variables_on_launch', 'ask_limit_on_launch', 'ask_tags_on_launch', 'ask_job_type_on_launch', 'ask_inventory_on_launch', - 'ask_credential_on_launch', 'survey_enabled', 'become_enabled', 'allow_simultaneous') + 'ask_credential_on_launch', 'survey_enabled', 'become_enabled') def get_related(self, obj): res = super(JobTemplateSerializer, self).get_related(obj) @@ -1795,10 +1766,10 @@ class JobTemplateSerializer(UnifiedJobTemplateSerializer, JobOptionsSerializer): notification_templates_any = reverse('api:job_template_notification_templates_any_list', args=(obj.pk,)), notification_templates_success = reverse('api:job_template_notification_templates_success_list', args=(obj.pk,)), notification_templates_error = reverse('api:job_template_notification_templates_error_list', args=(obj.pk,)), - access_list = reverse('api:job_template_access_list', args=(obj.pk,)), + access_list = reverse('api:job_template_access_list', args=(obj.pk,)), survey_spec = reverse('api:job_template_survey_spec', args=(obj.pk,)), labels = reverse('api:job_template_label_list', args=(obj.pk,)), - object_roles = reverse('api:job_template_object_roles_list', args=(obj.pk,)), + roles = reverse('api:job_template_roles_list', args=(obj.pk,)), )) if obj.host_config_key: res['callback'] = reverse('api:job_template_callback', args=(obj.pk,)) @@ -1812,36 +1783,25 @@ class JobTemplateSerializer(UnifiedJobTemplateSerializer, JobOptionsSerializer): if obj.survey_spec is not None and ('name' in obj.survey_spec and 'description' in obj.survey_spec): d['survey'] = dict(title=obj.survey_spec['name'], description=obj.survey_spec['description']) request = self.context.get('request', None) - - # Check for conditions that would create a validation error if coppied - validation_errors, resources_needed_to_start = obj.resource_validation_data() - - if request is None or request.user is None: - d['can_copy'] = False - d['can_edit'] = False - elif request.user.is_superuser: - d['can_copy'] = not validation_errors + if request is not None and request.user is not None and obj.inventory is not None and obj.project is not None: + d['can_copy'] = request.user.can_access(JobTemplate, 'add', + {'inventory': obj.inventory.pk, + 'project': obj.project.pk}) + d['can_edit'] = request.user.can_access(JobTemplate, 'change', obj, + {'inventory': obj.inventory.pk, + 'project': obj.project.pk}) + elif request is not None and request.user is not None and request.user.is_superuser: + d['can_copy'] = True d['can_edit'] = True else: - jt_data = model_to_dict(obj) - d['can_copy'] = (not validation_errors) and request.user.can_access(JobTemplate, 'add', jt_data) - d['can_edit'] = request.user.can_access(JobTemplate, 'change', obj, jt_data) - + d['can_copy'] = False + d['can_edit'] = False d['recent_jobs'] = self._recent_jobs(obj) return d def validate(self, attrs): survey_enabled = attrs.get('survey_enabled', self.instance and self.instance.survey_enabled or False) job_type = attrs.get('job_type', self.instance and self.instance.job_type or None) - inventory = attrs.get('inventory', self.instance and self.instance.inventory or None) - project = attrs.get('project', self.instance and self.instance.project or None) - - if job_type == "scan": - if inventory is None or attrs.get('ask_inventory_on_launch', False): - raise serializers.ValidationError({'inventory': 'Scan jobs must be assigned a fixed inventory.'}) - elif project is None: - raise serializers.ValidationError({'project': "Job types 'run' and 'check' must have assigned a project."}) - if survey_enabled and job_type == PERM_INVENTORY_SCAN: raise serializers.ValidationError({'survey_enabled': 'Survey Enabled can not be used with scan jobs.'}) @@ -1939,8 +1899,17 @@ class JobSerializer(UnifiedJobSerializer, JobOptionsSerializer): return ret if 'job_template' in ret and not obj.job_template: ret['job_template'] = None - if obj.job_template and obj.job_template.survey_enabled and 'extra_vars' in ret: - ret['extra_vars'] = obj.display_extra_vars() + + if obj.job_template and obj.job_template.survey_enabled: + if 'extra_vars' in ret: + try: + extra_vars = json.loads(ret['extra_vars']) + for key in obj.job_template.survey_password_variables(): + if key in extra_vars: + extra_vars[key] = REPLACE_STR + ret['extra_vars'] = json.dumps(extra_vars) + except ValueError: + pass return ret @@ -2290,14 +2259,12 @@ class JobLaunchSerializer(BaseSerializer): obj = self.context.get('obj') data = self.context.get('data') - for field in obj.resources_needed_to_start: - if not (field in attrs and obj._ask_for_vars_dict().get(field, False)): - errors[field] = "Job Template '%s' is missing or undefined." % field - if (not obj.ask_credential_on_launch) or (not attrs.get('credential', None)): credential = obj.credential else: credential = attrs.get('credential', None) + if not credential: + errors['credential'] = 'Credential not provided' # fill passwords dict with request data passwords if credential and credential.passwords_needed: @@ -2328,6 +2295,11 @@ class JobLaunchSerializer(BaseSerializer): if validation_errors: errors['variables_needed_to_start'] = validation_errors + if obj.job_type != PERM_INVENTORY_SCAN and (obj.project is None): + errors['project'] = 'Job Template Project is missing or undefined.' + if (obj.inventory is None) and not attrs.get('inventory', None): + errors['inventory'] = 'Job Template Inventory is missing or undefined.' + # Special prohibited cases for scan jobs if 'job_type' in data and obj.ask_job_type_on_launch: if ((obj.job_type == PERM_INVENTORY_SCAN and not data['job_type'] == PERM_INVENTORY_SCAN) or @@ -2397,13 +2369,12 @@ class NotificationTemplateSerializer(BaseSerializer): return d def validate(self, attrs): - from awx.api.views import NotificationTemplateDetail notification_class = NotificationTemplate.CLASS_FOR_NOTIFICATION_TYPE[attrs['notification_type']] missing_fields = [] incorrect_type_fields = [] if 'notification_configuration' not in attrs: return attrs - if self.context['view'].kwargs and isinstance(self.context['view'], NotificationTemplateDetail): + if self.context['view'].kwargs: object_actual = self.context['view'].get_object() else: object_actual = None diff --git a/awx/api/templates/api/job_template_survey_spec.md b/awx/api/templates/api/job_template_survey_spec.md index d1a222b31f..be73c0b1f4 100644 --- a/awx/api/templates/api/job_template_survey_spec.md +++ b/awx/api/templates/api/job_template_survey_spec.md @@ -3,7 +3,7 @@ POST requests to this resource should include the full specification for a Job T Here is an example survey specification: { - "name": "Simple Survey", + "name": "Simple Surveny", "description": "Description of the simple survey", "spec": [ { @@ -23,7 +23,6 @@ list of survey items. Within each survey item `type` must be one of: * text: For survey questions expecting a textual answer -* password: For survey questions expecting a password or other sensitive information * integer: For survey questions expecting a whole number answer * float: For survey questions expecting a decimal number * multiplechoice: For survey questions where one option from a list is required @@ -117,4 +116,4 @@ Here is a more comprehensive example showing the various question types and thei "default": "" } ] - } + } \ No newline at end of file diff --git a/awx/api/templates/api/sub_list_create_api_view.md b/awx/api/templates/api/sub_list_create_api_view.md index 75c5940f4d..23677f649b 100644 --- a/awx/api/templates/api/sub_list_create_api_view.md +++ b/awx/api/templates/api/sub_list_create_api_view.md @@ -12,7 +12,7 @@ fields to create a new {{ model_verbose_name }} associated with this {% block post_create %}{% endblock %} -{% if has_attach|default:False %} +{% if view.attach %} {% if parent_key %} # Remove {{ parent_model_verbose_name|title }} {{ model_verbose_name_plural|title }}: diff --git a/awx/api/urls.py b/awx/api/urls.py index e22bc61e63..9ed4af3c70 100644 --- a/awx/api/urls.py +++ b/awx/api/urls.py @@ -25,7 +25,7 @@ organization_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/notification_templates_any/$', 'organization_notification_templates_any_list'), url(r'^(?P[0-9]+)/notification_templates_error/$', 'organization_notification_templates_error_list'), url(r'^(?P[0-9]+)/notification_templates_success/$', 'organization_notification_templates_success_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'organization_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'organization_roles_list'), url(r'^(?P[0-9]+)/access_list/$', 'organization_access_list'), ) @@ -38,7 +38,6 @@ user_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/projects/$', 'user_projects_list'), url(r'^(?P[0-9]+)/credentials/$', 'user_credentials_list'), url(r'^(?P[0-9]+)/roles/$', 'user_roles_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'user_object_roles_list'), url(r'^(?P[0-9]+)/activity_stream/$', 'user_activity_stream_list'), url(r'^(?P[0-9]+)/access_list/$', 'user_access_list'), @@ -56,7 +55,7 @@ project_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/notification_templates_any/$', 'project_notification_templates_any_list'), url(r'^(?P[0-9]+)/notification_templates_error/$', 'project_notification_templates_error_list'), url(r'^(?P[0-9]+)/notification_templates_success/$', 'project_notification_templates_success_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'project_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'project_roles_list'), url(r'^(?P[0-9]+)/access_list/$', 'project_access_list'), ) @@ -74,7 +73,6 @@ team_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/users/$', 'team_users_list'), url(r'^(?P[0-9]+)/credentials/$', 'team_credentials_list'), url(r'^(?P[0-9]+)/roles/$', 'team_roles_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'team_object_roles_list'), url(r'^(?P[0-9]+)/activity_stream/$', 'team_activity_stream_list'), url(r'^(?P[0-9]+)/access_list/$', 'team_access_list'), ) @@ -94,7 +92,7 @@ inventory_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/scan_job_templates/$', 'inventory_scan_job_template_list'), url(r'^(?P[0-9]+)/ad_hoc_commands/$', 'inventory_ad_hoc_commands_list'), url(r'^(?P[0-9]+)/access_list/$', 'inventory_access_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'inventory_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'inventory_roles_list'), #url(r'^(?P[0-9]+)/single_fact/$', 'inventory_single_fact_view'), ) @@ -129,7 +127,7 @@ group_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/inventory_sources/$', 'group_inventory_sources_list'), url(r'^(?P[0-9]+)/ad_hoc_commands/$', 'group_ad_hoc_commands_list'), url(r'^(?P[0-9]+)/access_list/$', 'group_access_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'group_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'group_roles_list'), #url(r'^(?P[0-9]+)/single_fact/$', 'group_single_fact_view'), ) @@ -157,7 +155,7 @@ inventory_update_urls = patterns('awx.api.views', inventory_script_urls = patterns('awx.api.views', url(r'^$', 'inventory_script_list'), url(r'^(?P[0-9]+)/$', 'inventory_script_detail'), - url(r'^(?P[0-9]+)/object_roles/$', 'inventory_script_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'inventory_script_roles_list'), ) credential_urls = patterns('awx.api.views', @@ -165,9 +163,7 @@ credential_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/activity_stream/$', 'credential_activity_stream_list'), url(r'^(?P[0-9]+)/$', 'credential_detail'), url(r'^(?P[0-9]+)/access_list/$', 'credential_access_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'credential_object_roles_list'), - url(r'^(?P[0-9]+)/owner/users/$', 'credential_owner_users_list'), - url(r'^(?P[0-9]+)/owner/teams/$', 'credential_owner_teams_list'), + url(r'^(?P[0-9]+)/roles/$', 'credential_roles_list'), # See also credentials resources on users/teams. ) @@ -193,7 +189,7 @@ job_template_urls = patterns('awx.api.views', url(r'^(?P[0-9]+)/notification_templates_error/$', 'job_template_notification_templates_error_list'), url(r'^(?P[0-9]+)/notification_templates_success/$', 'job_template_notification_templates_success_list'), url(r'^(?P[0-9]+)/access_list/$', 'job_template_access_list'), - url(r'^(?P[0-9]+)/object_roles/$', 'job_template_object_roles_list'), + url(r'^(?P[0-9]+)/roles/$', 'job_template_roles_list'), url(r'^(?P[0-9]+)/labels/$', 'job_template_label_list'), ) diff --git a/awx/api/views.py b/awx/api/views.py index 4cdf4363f3..98a292b9c5 100644 --- a/awx/api/views.py +++ b/awx/api/views.py @@ -820,7 +820,7 @@ class OrganizationAccessList(ResourceAccessList): resource_model = Organization new_in_300 = True -class OrganizationObjectRolesList(SubListAPIView): +class OrganizationRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -877,18 +877,6 @@ class TeamRolesList(SubListCreateAttachDetachAPIView): return Response(data, status=status.HTTP_400_BAD_REQUEST) return super(TeamRolesList, self).post(request, *args, **kwargs) -class TeamObjectRolesList(SubListAPIView): - - model = Role - serializer_class = RoleSerializer - parent_model = Team - new_in_300 = True - - def get_queryset(self): - po = self.get_parent_object() - content_type = ContentType.objects.get_for_model(self.parent_model) - return Role.objects.filter(content_type=content_type, object_id=po.pk) - class TeamProjectsList(SubListAPIView): model = Project @@ -979,19 +967,12 @@ class ProjectPlaybooks(RetrieveAPIView): model = Project serializer_class = ProjectPlaybooksSerializer -class ProjectTeamsList(ListAPIView): +class ProjectTeamsList(SubListCreateAttachDetachAPIView): model = Team serializer_class = TeamSerializer - - def get_queryset(self): - p = get_object_or_404(Project, pk=self.kwargs['pk']) - if not self.request.user.can_access(Project, 'read', p): - raise PermissionDenied() - project_ct = ContentType.objects.get_for_model(Project) - team_ct = ContentType.objects.get_for_model(self.model) - all_roles = Role.objects.filter(Q(descendents__content_type=project_ct) & Q(descendents__object_id=p.pk), content_type=team_ct) - return self.model.accessible_objects(self.request.user, 'read_role').filter(pk__in=[t.content_object.pk for t in all_roles]) + parent_model = Project + relationship = 'teams' class ProjectSchedulesList(SubListCreateAttachDetachAPIView): @@ -1116,7 +1097,7 @@ class ProjectAccessList(ResourceAccessList): resource_model = Project new_in_300 = True -class ProjectObjectRolesList(SubListAPIView): +class ProjectRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -1201,17 +1182,6 @@ class UserRolesList(SubListCreateAttachDetachAPIView): # We hide roles that shouldn't be seen in our queryset return True -class UserObjectRolesList(SubListAPIView): - - model = Role - serializer_class = RoleSerializer - parent_model = User - new_in_300 = True - - def get_queryset(self): - po = self.get_parent_object() - content_type = ContentType.objects.get_for_model(self.parent_model) - return Role.objects.filter(content_type=content_type, object_id=po.pk) class UserProjectsList(SubListAPIView): @@ -1365,37 +1335,10 @@ class CredentialList(ListCreateAPIView): if 'team' in request.data: credential.owner_role.parents.add(team.member_role) if 'organization' in request.data: - credential.organization = organization - credential.save() + credential.owner_role.parents.add(organization.admin_role) return ret - -class CredentialOwnerUsersList(SubListAPIView): - model = User - serializer_class = UserSerializer - parent_model = Credential - relationship = 'owner_role.members' - new_in_300 = True - - -class CredentialOwnerTeamsList(SubListAPIView): - model = Team - serializer_class = TeamSerializer - parent_model = Credential - new_in_300 = True - - def get_queryset(self): - credential = get_object_or_404(self.parent_model, pk=self.kwargs['pk']) - if not self.request.user.can_access(Credential, 'read', None): - raise PermissionDenied() - - content_type = ContentType.objects.get_for_model(self.model) - teams = [c.content_object.pk for c in credential.owner_role.parents.filter(content_type=content_type)] - - return self.model.objects.filter(pk__in=teams) - - class UserCredentialsList(CredentialList): model = Credential @@ -1489,7 +1432,7 @@ class CredentialAccessList(ResourceAccessList): resource_model = Credential new_in_300 = True -class CredentialObjectRolesList(SubListAPIView): +class CredentialRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -1521,7 +1464,7 @@ class InventoryScriptDetail(RetrieveUpdateDestroyAPIView): inv_src.save() return super(InventoryScriptDetail, self).destroy(request, *args, **kwargs) -class InventoryScriptObjectRolesList(SubListAPIView): +class InventoryScriptRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -1583,7 +1526,7 @@ class InventoryAccessList(ResourceAccessList): resource_model = Inventory new_in_300 = True -class InventoryObjectRolesList(SubListAPIView): +class InventoryRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -1930,7 +1873,7 @@ class GroupAccessList(ResourceAccessList): resource_model = Group new_in_300 = True -class GroupObjectRolesList(SubListAPIView): +class GroupRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -2269,13 +2212,6 @@ class JobTemplateList(ListCreateAPIView): serializer_class = JobTemplateSerializer always_allow_superuser = False - def post(self, request, *args, **kwargs): - ret = super(JobTemplateList, self).post(request, *args, **kwargs) - if ret.status_code == 201: - job_template = JobTemplate.objects.get(id=ret.data['id']) - job_template.admin_role.members.add(request.user) - return ret - class JobTemplateDetail(RetrieveUpdateDestroyAPIView): model = JobTemplate @@ -2382,6 +2318,8 @@ class JobTemplateSurveySpec(GenericAPIView): def get(self, request, *args, **kwargs): obj = self.get_object() + # Sanity check: Are surveys available on this license? + # If not, do not allow them to be used. if not feature_enabled('surveys'): raise LicenseForbids('Your license does not allow ' 'adding surveys.') @@ -2487,18 +2425,7 @@ class JobTemplateLabelList(SubListCreateAttachDetachAPIView, DeleteLastUnattachL serializer_class = LabelSerializer parent_model = JobTemplate relationship = 'labels' - - def post(self, request, *args, **kwargs): - # If a label already exists in the database, attach it instead of erroring out - # that it already exists - if 'id' not in request.data and 'name' in request.data and 'organization' in request.data: - existing = Label.objects.filter(name=request.data['name'], organization_id=request.data['organization']) - if existing.exists(): - existing = existing[0] - request.data['id'] = existing.id - del request.data['name'] - del request.data['organization'] - return super(JobTemplateLabelList, self).post(request, *args, **kwargs) + parent_key = 'job_template' class JobTemplateCallback(GenericAPIView): @@ -2676,7 +2603,7 @@ class JobTemplateAccessList(ResourceAccessList): resource_model = JobTemplate new_in_300 = True -class JobTemplateObjectRolesList(SubListAPIView): +class JobTemplateRolesList(SubListAPIView): model = Role serializer_class = RoleSerializer @@ -3818,6 +3745,7 @@ class RoleChildrenList(SubListAPIView): + # Create view functions for all of the class-based views to simplify inclusion # in URL patterns and reverse URL lookups, converting CamelCase names to # lowercase_with_underscore (e.g. MyView.as_view() becomes my_view). diff --git a/awx/main/access.py b/awx/main/access.py index 91c8917514..cec0b7c2bf 100644 --- a/awx/main/access.py +++ b/awx/main/access.py @@ -588,22 +588,15 @@ class CredentialAccess(BaseAccess): return check_user_access(self.user, Organization, 'change', organization_obj, None) return False + @check_superuser def can_use(self, obj): return self.user in obj.use_role @check_superuser def can_change(self, obj, data): - if data is not None: - keys = data.keys() - if 'user' in keys or 'team' in keys or 'organization' in keys: - if not self.can_add(data): - return False - - if obj.organization: - if self.user in obj.organization.admin_role: - return True - + if not self.can_add(data): + return False return self.user in obj.owner_role def can_delete(self, obj): @@ -780,9 +773,7 @@ class JobTemplateAccess(BaseAccess): inventory_pk = get_pk_from_dict(data, 'inventory') inventory = Inventory.objects.filter(id=inventory_pk) if not inventory.exists() and not data.get('ask_inventory_on_launch', False): - return False - if inventory.exists() and self.user not in inventory[0].use_role: - return False + return False # Does this make sense? Maybe should check read access project_pk = get_pk_from_dict(data, 'project') if 'job_type' in data and data['job_type'] == PERM_INVENTORY_SCAN: @@ -795,8 +786,10 @@ class JobTemplateAccess(BaseAccess): # If the user has admin access to the project (as an org admin), should # be able to proceed without additional checks. project = get_object_or_400(Project, pk=project_pk) + if self.user in project.admin_role: + return True - return self.user in project.use_role + return self.user in project.admin_role and self.user in inventory.read_role def can_start(self, obj, validate_license=True): # Check license. @@ -821,80 +814,20 @@ class JobTemplateAccess(BaseAccess): def can_change(self, obj, data): data_for_change = data - if self.user not in obj.admin_role and not self.user.is_superuser: + if self.user not in obj.admin_role: return False if data is not None: - data = dict(data) - - if self.changes_are_non_sensitive(obj, data): - if 'job_type' in data and obj.job_type != data['job_type'] and data['job_type'] == PERM_INVENTORY_SCAN: - self.check_license(feature='system_tracking') - - if 'survey_enabled' in data and obj.survey_enabled != data['survey_enabled'] and data['survey_enabled']: - self.check_license(feature='surveys') - return True - + data_for_change = dict(data) for required_field in ('credential', 'cloud_credential', 'inventory', 'project'): required_obj = getattr(obj, required_field, None) if required_field not in data_for_change and required_obj is not None: data_for_change[required_field] = required_obj.pk return self.can_read(obj) and self.can_add(data_for_change) - def changes_are_non_sensitive(self, obj, data): - ''' - Returne true if the changes being made are considered nonsensitive, and - thus can be made by a job template administrator which may not have access - to the any inventory, project, or credentials associated with the template. - ''' - # We are white listing fields that can - field_whitelist = [ - 'name', 'description', 'forks', 'limit', 'verbosity', 'extra_vars', - 'job_tags', 'force_handlers', 'skip_tags', 'ask_variables_on_launch', - 'ask_tags_on_launch', 'ask_job_type_on_launch', 'ask_inventory_on_launch', - 'ask_credential_on_launch', 'survey_enabled' - ] - - for k, v in data.items(): - if hasattr(obj, k) and getattr(obj, k) != v: - if k not in field_whitelist: - return False - return True - - def can_update_sensitive_fields(self, obj, data): - project_id = data.get('project', obj.project.id if obj.project else None) - inventory_id = data.get('inventory', obj.inventory.id if obj.inventory else None) - credential_id = data.get('credential', obj.credential.id if obj.credential else None) - cloud_credential_id = data.get('cloud_credential', obj.cloud_credential.id if obj.cloud_credential else None) - network_credential_id = data.get('network_credential', obj.network_credential.id if obj.network_credential else None) - - if project_id and self.user not in Project.objects.get(pk=project_id).use_role: - return False - if inventory_id and self.user not in Inventory.objects.get(pk=inventory_id).use_role: - return False - if credential_id and self.user not in Credential.objects.get(pk=credential_id).use_role: - return False - if cloud_credential_id and self.user not in Credential.objects.get(pk=cloud_credential_id).use_role: - return False - if network_credential_id and self.user not in Credential.objects.get(pk=network_credential_id).use_role: - return False - - return True - - @check_superuser def can_delete(self, obj): return self.user in obj.admin_role class JobAccess(BaseAccess): - ''' - I can see jobs when: - - I am a superuser. - - I can see its job template - - I am an admin or auditor of the organization which contains its inventory - - I am an admin or auditor of the organization which contains its project - I can delete jobs when: - - I am an admin of the organization which contains its inventory - - I am an admin of the organization which contains its project - ''' model = Job @@ -906,20 +839,10 @@ class JobAccess(BaseAccess): if self.user.is_superuser: return qs.all() - qs_jt = qs.filter( + return qs.filter( job_template__in=JobTemplate.accessible_objects(self.user, 'read_role') ) - org_access_qs = Organization.objects.filter( - Q(admin_role__members=self.user) | Q(auditor_role__members=self.user)) - if not org_access_qs.exists(): - return qs_jt - - return qs.filter( - Q(job_template__in=JobTemplate.accessible_objects(self.user, 'read_role')) | - Q(inventory__organization__in=org_access_qs) | - Q(project__organization__in=org_access_qs)).distinct() - def can_add(self, data): if not data or '_method' in data: # So the browseable API will work? return True @@ -948,11 +871,7 @@ class JobAccess(BaseAccess): @check_superuser def can_delete(self, obj): - if obj.inventory is not None and self.user in obj.inventory.organization.admin_role: - return True - if obj.project is not None and self.user in obj.project.organization.admin_role: - return True - return False + return self.user in obj.inventory.admin_role def can_start(self, obj): self.check_license() @@ -1474,10 +1393,6 @@ class CustomInventoryScriptAccess(BaseAccess): def can_admin(self, obj): return self.user in obj.admin_role - @check_superuser - def can_change(self, obj, data): - return self.can_admin(obj) - @check_superuser def can_read(self, obj): return self.user in obj.read_role diff --git a/awx/main/management/commands/inventory_import.py b/awx/main/management/commands/inventory_import.py index e32c924538..d5b2bcdcd3 100644 --- a/awx/main/management/commands/inventory_import.py +++ b/awx/main/management/commands/inventory_import.py @@ -857,7 +857,7 @@ class Command(NoArgsCommand): del_pks = del_host_pks[offset:(offset + self._batch_size)] for db_host in db_hosts.filter(pk__in=del_pks): group_host_count += 1 - if db_host not in db_group.hosts.all(): + if db_host not in db_group.hosts: continue db_group.hosts.remove(db_host) self.logger.info('Host "%s" removed from group "%s"', diff --git a/awx/main/migrations/0008_v300_rbac_changes.py b/awx/main/migrations/0008_v300_rbac_changes.py index 50ce375f5f..9c4b193d47 100644 --- a/awx/main/migrations/0008_v300_rbac_changes.py +++ b/awx/main/migrations/0008_v300_rbac_changes.py @@ -86,11 +86,7 @@ class Migration(migrations.Migration): name='credential', unique_together=set([]), ), - migrations.AddField( - model_name='credential', - name='organization', - field=models.ForeignKey(related_name='credentials', default=None, blank=True, to='main.Organization', null=True), - ), + # # New RBAC models and fields diff --git a/awx/main/migrations/0017_v300_prompting_migrations.py b/awx/main/migrations/0017_v300_prompting_migrations.py index 6bec778956..c5a1df0eb9 100644 --- a/awx/main/migrations/0017_v300_prompting_migrations.py +++ b/awx/main/migrations/0017_v300_prompting_migrations.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from awx.main.migrations import _rbac as rbac from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations @@ -16,5 +15,4 @@ class Migration(migrations.Migration): operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), - migrations.RunPython(rbac.rebuild_role_hierarchy), ] diff --git a/awx/main/migrations/0024_v300_jobtemplate_allow_simul.py b/awx/main/migrations/0024_v300_jobtemplate_allow_simul.py deleted file mode 100644 index ef67525e4b..0000000000 --- a/awx/main/migrations/0024_v300_jobtemplate_allow_simul.py +++ /dev/null @@ -1,19 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('main', '0023_v300_activity_stream_ordering'), - ] - - operations = [ - migrations.AddField( - model_name='jobtemplate', - name='allow_simultaneous', - field=models.BooleanField(default=False), - ), - ] diff --git a/awx/main/migrations/_rbac.py b/awx/main/migrations/_rbac.py index 0b3c3ccc37..e16b3575d3 100644 --- a/awx/main/migrations/_rbac.py +++ b/awx/main/migrations/_rbac.py @@ -123,7 +123,7 @@ def attrfunc(attr_path): return attr def _update_credential_parents(org, cred): - cred.organization = org + org.admin_role.children.add(cred.owner_role) cred.save() def _discover_credentials(instances, cred, orgfunc): @@ -164,12 +164,13 @@ def _discover_credentials(instances, cred, orgfunc): cred.pk = None cred.save() - cred.owner_role, cred.use_role, cred.organization = None, None, None + # Unlink the old information from the new credential + cred.owner_role, cred.use_role = None, None + cred.save() for i in orgs[org]: i.credential = cred i.save() - _update_credential_parents(org, cred) @log_migration @@ -214,7 +215,7 @@ def migrate_inventory(apps, schema_editor): Inventory = apps.get_model('main', 'Inventory') Permission = apps.get_model('main', 'Permission') - def role_from_permission(perm): + def role_from_permission(): if perm.permission_type == 'admin': return inventory.admin_role elif perm.permission_type == 'read': @@ -232,7 +233,7 @@ def migrate_inventory(apps, schema_editor): role = None execrole = None - role = role_from_permission(perm) + role = role_from_permission() if role is None: raise Exception(smart_text(u'Unhandled permission type for inventory: {}'.format( perm.permission_type))) @@ -291,13 +292,10 @@ def migrate_projects(apps, schema_editor): else: new_prj = Project.objects.create( created = project.created, - modified = project.modified, - polymorphic_ctype_id = project.polymorphic_ctype_id, description = project.description, name = smart_text(u'{} - {}'.format(org.name, original_project_name)), old_pk = project.old_pk, created_by_id = project.created_by_id, - modified_by_id = project.modified_by_id, scm_type = project.scm_type, scm_url = project.scm_url, scm_branch = project.scm_branch, @@ -309,31 +307,11 @@ def migrate_projects(apps, schema_editor): credential = project.credential, organization = org ) - if project.scm_type == "": - new_prj.local_path = project.local_path - new_prj.save() - for team in project.deprecated_teams.iterator(): - new_prj.deprecated_teams.add(team) logger.warning(smart_text(u'cloning Project({}) onto {} as Project({})'.format(original_project_name, org, new_prj))) - job_templates = JobTemplate.objects.filter(project=project, inventory__organization=org).all() + job_templates = JobTemplate.objects.filter(inventory__organization=org).all() for jt in job_templates: jt.project = new_prj jt.save() - for perm in Permission.objects.filter(project=project): - Permission.objects.create( - created = perm.created, - modified = perm.modified, - created_by = perm.created_by, - modified_by = perm.modified_by, - description = perm.description, - name = perm.name, - user = perm.user, - team = perm.team, - project = new_prj, - inventory = perm.inventory, - permission_type = perm.permission_type, - run_ad_hoc_commands = perm.run_ad_hoc_commands, - ) # Migrate permissions for project in Project.objects.iterator(): @@ -342,29 +320,23 @@ def migrate_projects(apps, schema_editor): logger.warn(smart_text(u'adding Project({}) admin: {}'.format(project.name, project.created_by.username))) for team in project.deprecated_teams.all(): - team.member_role.children.add(project.read_role) + team.member_role.children.add(project.use_role) logger.info(smart_text(u'adding Team({}) access for Project({})'.format(team.name, project.name))) - for perm in Permission.objects.filter(project=project): - if perm.permission_type == 'create': - role = project.use_role - else: - role = project.read_role - - if perm.team: - perm.team.member_role.children.add(role) - logger.info(smart_text(u'adding Team({}) access for Project({})'.format(perm.team.name, project.name))) - - if perm.user: - role.members.add(perm.user) - logger.info(smart_text(u'adding User({}) access for Project({})'.format(perm.user.username, project.name))) - if project.organization is not None: for user in project.organization.deprecated_users.all(): - if not (project.use_role.members.filter(pk=user.id).exists() or project.admin_role.members.filter(pk=user.id).exists()): - project.read_role.members.add(user) - logger.info(smart_text(u'adding Organization({}) member access to Project({})'.format(project.organization.name, project.name))) + project.use_role.members.add(user) + logger.info(smart_text(u'adding Organization({}) member access to Project({})'.format(project.organization.name, project.name))) + for perm in Permission.objects.filter(project=project): + # All perms at this level just imply a user or team can read + if perm.team: + perm.team.member_role.children.add(project.use_role) + logger.info(smart_text(u'adding Team({}) access for Project({})'.format(perm.team.name, project.name))) + + if perm.user: + project.use_role.members.add(perm.user) + logger.info(smart_text(u'adding User({}) access for Project({})'.format(perm.user.username, project.name))) @log_migration @@ -431,7 +403,7 @@ def migrate_job_templates(apps, schema_editor): team_create_permissions = set( jt_permission_qs - .filter(permission_type__in=['create']) + .filter(permission_type__in=['create'] if jt.job_type == 'check' else ['create']) .values_list('team__id', flat=True) ) team_run_permissions = set( @@ -441,12 +413,12 @@ def migrate_job_templates(apps, schema_editor): ) user_create_permissions = set( jt_permission_qs - .filter(permission_type__in=['create']) + .filter(permission_type__in=['create'] if jt.job_type == 'check' else ['run']) .values_list('user__id', flat=True) ) user_run_permissions = set( jt_permission_qs - .filter(permission_type__in=['check', 'run'] if jt.job_type == 'check' else ['run']) + .filter(permission_type__in=['check', 'run'] if jt.job_type == 'check' else ['create']) .values_list('user__id', flat=True) ) @@ -474,20 +446,17 @@ def migrate_job_templates(apps, schema_editor): logger.info(smart_text(u'transfering execute access on JobTemplate({}) to Team({})'.format(jt.name, team.name))) for user in User.objects.filter(id__in=user_create_permissions).iterator(): - cred = jt.credential or jt.cloud_credential if (jt.inventory.id in user_inv_permissions[user.id] or any([jt.inventory.id in team_inv_permissions[team.id] for team in user.deprecated_teams.all()])) and \ - (not cred or cred.deprecated_user == user or - (cred.deprecated_team and cred.deprecated_team.deprecated_users.filter(pk=user.id).exists())): + ((not jt.credential and not jt.cloud_credential) or + Credential.objects.filter(Q(deprecated_user=user) | Q(deprecated_team__deprecated_users=user), jobtemplates=jt).exists()): jt.admin_role.members.add(user) logger.info(smart_text(u'transfering admin access on JobTemplate({}) to User({})'.format(jt.name, user.username))) for user in User.objects.filter(id__in=user_run_permissions).iterator(): - cred = jt.credential or jt.cloud_credential - if (jt.inventory.id in user_inv_permissions[user.id] or any([jt.inventory.id in team_inv_permissions[team.id] for team in user.deprecated_teams.all()])) and \ - (not cred or cred.deprecated_user == user or - (cred.deprecated_team and cred.deprecated_team.deprecated_users.filter(pk=user.id).exists())): + ((not jt.credential and not jt.cloud_credential) or + Credential.objects.filter(Q(deprecated_user=user) | Q(deprecated_team__deprecated_users=user), jobtemplates=jt).exists()): jt.execute_role.members.add(user) logger.info(smart_text(u'transfering execute access on JobTemplate({}) to User({})'.format(jt.name, user.username))) @@ -499,6 +468,8 @@ def rebuild_role_hierarchy(apps, schema_editor): start = time() roots = Role.objects \ .all() \ + .exclude(pk__in=Role.parents.through.objects.all() + .values_list('from_role_id', flat=True).distinct()) \ .values_list('id', flat=True) stop = time() logger.info('Found %d roots in %f seconds, rebuilding ancestry map' % (len(roots), stop - start)) diff --git a/awx/main/models/credential.py b/awx/main/models/credential.py index 07cf77e97d..d1e6e91d93 100644 --- a/awx/main/models/credential.py +++ b/awx/main/models/credential.py @@ -78,14 +78,6 @@ class Credential(PasswordFieldsModel, CommonModelNameNotUnique, ResourceMixin): on_delete=models.CASCADE, related_name='deprecated_credentials', ) - organization = models.ForeignKey( - 'Organization', - null=True, - default=None, - blank=True, - on_delete=models.CASCADE, - related_name='credentials', - ) kind = models.CharField( max_length=32, choices=KIND_CHOICES, @@ -217,10 +209,7 @@ class Credential(PasswordFieldsModel, CommonModelNameNotUnique, ResourceMixin): ], ) use_role = ImplicitRoleField( - parent_role=[ - 'organization.admin_role', - 'owner_role', - ] + parent_role=['owner_role'] ) read_role = ImplicitRoleField(parent_role=[ 'singleton:' + ROLE_SINGLETON_SYSTEM_AUDITOR, diff --git a/awx/main/models/jobs.py b/awx/main/models/jobs.py index 2431e3df4a..7e5f7fc905 100644 --- a/awx/main/models/jobs.py +++ b/awx/main/models/jobs.py @@ -26,7 +26,7 @@ from awx.main.models.unified_jobs import * # noqa from awx.main.models.notifications import NotificationTemplate from awx.main.utils import decrypt_field, ignore_inventory_computed_fields from awx.main.utils import emit_websocket_notification -from awx.main.redact import PlainTextCleaner, REPLACE_STR +from awx.main.redact import PlainTextCleaner from awx.main.conf import tower_settings from awx.main.fields import ImplicitRoleField from awx.main.models.mixins import ResourceMixin @@ -229,10 +229,6 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): read_role = ImplicitRoleField( parent_role=['project.organization.auditor_role', 'inventory.organization.auditor_role', 'execute_role', 'admin_role'], ) - allow_simultaneous = models.BooleanField( - default=False, - ) - @classmethod def _get_unified_job_class(cls): @@ -246,37 +242,14 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): 'force_handlers', 'skip_tags', 'start_at_task', 'become_enabled', 'labels',] - def resource_validation_data(self): - ''' - Process consistency errors and need-for-launch related fields. - ''' - resources_needed_to_start = [] - validation_errors = {} - - # Inventory and Credential related checks - if self.inventory is None: - resources_needed_to_start.append('inventory') - if not self.ask_inventory_on_launch: - validation_errors['inventory'] = ["Job Template must provide 'inventory' or allow prompting for it.",] - if self.credential is None: - resources_needed_to_start.append('credential') - if not self.ask_credential_on_launch: - validation_errors['credential'] = ["Job Template must provide 'credential' or allow prompting for it.",] - - # Job type dependent checks - if self.job_type == 'scan': - if self.inventory is None or self.ask_inventory_on_launch: - validation_errors['inventory'] = ["Scan jobs must be assigned a fixed inventory.",] - elif self.project is None: - resources_needed_to_start.append('project') - validation_errors['project'] = ["Job types 'run' and 'check' must have assigned a project.",] - - return (validation_errors, resources_needed_to_start) - - @property - def resources_needed_to_start(self): - validation_errors, resources_needed_to_start = self.resource_validation_data() - return resources_needed_to_start + def clean(self): + if self.job_type == 'scan' and (self.inventory is None or self.ask_inventory_on_launch): + raise ValidationError({"inventory": ["Scan jobs must be assigned a fixed inventory.",]}) + if (not self.ask_inventory_on_launch) and self.inventory is None: + raise ValidationError({"inventory": ["Job Template must provide 'inventory' or allow prompting for it.",]}) + if (not self.ask_credential_on_launch) and self.credential is None: + raise ValidationError({"credential": ["Job Template must provide 'credential' or allow prompting for it.",]}) + return super(JobTemplate, self).clean() def create_job(self, **kwargs): ''' @@ -292,9 +265,9 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): Return whether job template can be used to start a new job without requiring any user input. ''' - return (not self.resources_needed_to_start and - not self.passwords_needed_to_start and - not self.variables_needed_to_start) + return bool(self.credential and not len(self.passwords_needed_to_start) and + not len(self.variables_needed_to_start) and + self.inventory) @property def variables_needed_to_start(self): @@ -328,20 +301,20 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): errors.append("'%s' value missing" % survey_element['variable']) elif survey_element['type'] in ["textarea", "text", "password"]: if survey_element['variable'] in data: - if 'min' in survey_element and survey_element['min'] not in ["", None] and len(data[survey_element['variable']]) < int(survey_element['min']): - errors.append("'%s' value %s is too small (length is %s must be at least %s)." % - (survey_element['variable'], data[survey_element['variable']], len(data[survey_element['variable']]), survey_element['min'])) - if 'max' in survey_element and survey_element['max'] not in ["", None] and len(data[survey_element['variable']]) > int(survey_element['max']): + if 'min' in survey_element and survey_element['min'] not in ["", None] and len(data[survey_element['variable']]) < survey_element['min']: + errors.append("'%s' value %s is too small (must be at least %s)." % + (survey_element['variable'], data[survey_element['variable']], survey_element['min'])) + if 'max' in survey_element and survey_element['max'] not in ["", None] and len(data[survey_element['variable']]) > survey_element['max']: errors.append("'%s' value %s is too large (must be no more than %s)." % (survey_element['variable'], data[survey_element['variable']], survey_element['max'])) elif survey_element['type'] == 'integer': if survey_element['variable'] in data: if 'min' in survey_element and survey_element['min'] not in ["", None] and survey_element['variable'] in data and \ - data[survey_element['variable']] < int(survey_element['min']): + data[survey_element['variable']] < survey_element['min']: errors.append("'%s' value %s is too small (must be at least %s)." % (survey_element['variable'], data[survey_element['variable']], survey_element['min'])) if 'max' in survey_element and survey_element['max'] not in ["", None] and survey_element['variable'] in data and \ - data[survey_element['variable']] > int(survey_element['max']): + data[survey_element['variable']] > survey_element['max']: errors.append("'%s' value %s is too large (must be no more than %s)." % (survey_element['variable'], data[survey_element['variable']], survey_element['max'])) if type(data[survey_element['variable']]) != int: @@ -349,10 +322,10 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): survey_element['variable'])) elif survey_element['type'] == 'float': if survey_element['variable'] in data: - if 'min' in survey_element and survey_element['min'] not in ["", None] and data[survey_element['variable']] < float(survey_element['min']): + if 'min' in survey_element and survey_element['min'] not in ["", None] and data[survey_element['variable']] < survey_element['min']: errors.append("'%s' value %s is too small (must be at least %s)." % (survey_element['variable'], data[survey_element['variable']], survey_element['min'])) - if 'max' in survey_element and survey_element['max'] not in ["", None] and data[survey_element['variable']] > float(survey_element['max']): + if 'max' in survey_element and survey_element['max'] not in ["", None] and data[survey_element['variable']] > survey_element['max']: errors.append("'%s' value %s is too large (must be no more than %s)." % (survey_element['variable'], data[survey_element['variable']], survey_element['max'])) if type(data[survey_element['variable']]) not in (float, int): @@ -435,9 +408,9 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin): if ask_for_vars_dict[field]: prompted_fields[field] = kwargs[field] else: - if field == 'extra_vars' and self.survey_enabled and self.survey_spec: + if field == 'extra_vars' and self.survey_enabled: # Accept vars defined in the survey and no others - survey_vars = [question['variable'] for question in self.survey_spec.get('spec', [])] + survey_vars = [question['variable'] for question in self.survey_spec['spec']] for key in kwargs[field]: if key in survey_vars: prompted_fields[field][key] = kwargs[field][key] @@ -578,8 +551,6 @@ class Job(UnifiedJob, JobOptions): if obj.job_template is not None and obj.inventory is not None: if obj.job_template == self.job_template and \ obj.inventory == self.inventory: - if self.job_template.allow_simultaneous: - return False if obj.launch_type == 'callback' and self.launch_type == 'callback' and \ obj.limit != self.limit: return False @@ -635,12 +606,14 @@ class Job(UnifiedJob, JobOptions): def generate_dependencies(self, active_tasks): from awx.main.models import InventoryUpdate, ProjectUpdate - inventory_sources = self.inventory.inventory_sources.filter(update_on_launch=True) + if self.inventory is None or self.project is None: + return [] + inventory_sources = self.inventory.inventory_sources.filter( update_on_launch=True) project_found = False inventory_sources_found = [] dependencies = [] for obj in active_tasks: - if type(obj) == ProjectUpdate and self.project is not None: + if type(obj) == ProjectUpdate: if obj.project == self.project: project_found = True if type(obj) == InventoryUpdate: @@ -658,7 +631,7 @@ class Job(UnifiedJob, JobOptions): for source in inventory_sources.filter(pk__in=inventory_sources_already_updated): if source not in inventory_sources_found: inventory_sources_found.append(source) - if not project_found and self.project is not None and self.project.needs_update_on_launch: + if not project_found and self.project.needs_update_on_launch: dependencies.append(self.project.create_project_update(launch_type='dependency')) if inventory_sources.count(): # and not has_setup_failures? Probably handled as an error scenario in the task runner for source in inventory_sources: @@ -678,7 +651,7 @@ class Job(UnifiedJob, JobOptions): processed=h.processed, skipped=h.skipped) data.update(dict(inventory=self.inventory.name, - project=self.project.name if self.project else None, + project=self.project.name, playbook=self.playbook, credential=self.credential.name, limit=self.limit, @@ -703,21 +676,6 @@ class Job(UnifiedJob, JobOptions): evars.update(extra_vars) self.update_fields(extra_vars=json.dumps(evars)) - def display_extra_vars(self): - ''' - Hides fields marked as passwords in survey. - ''' - if self.extra_vars and self.job_template and self.job_template.survey_enabled: - try: - extra_vars = json.loads(self.extra_vars) - for key in self.job_template.survey_password_variables(): - if key in extra_vars: - extra_vars[key] = REPLACE_STR - return json.dumps(extra_vars) - except ValueError: - pass - return self.extra_vars - def _survey_search_and_replace(self, content): # Use job template survey spec to identify password fields. # Then lookup password fields in extra_vars and save the values diff --git a/awx/main/models/unified_jobs.py b/awx/main/models/unified_jobs.py index 766db6718e..752dbff5a6 100644 --- a/awx/main/models/unified_jobs.py +++ b/awx/main/models/unified_jobs.py @@ -754,8 +754,8 @@ class UnifiedJob(PolymorphicModel, PasswordFieldsModel, CommonModelNameNotUnique name=self.name, url=self.get_ui_url(), created_by=smart_text(self.created_by), - started=self.started.isoformat() if self.started is not None else None, - finished=self.finished.isoformat() if self.finished is not None else None, + started=self.started.isoformat(), + finished=self.finished.isoformat(), status=self.status, traceback=self.result_traceback) diff --git a/awx/main/signals.py b/awx/main/signals.py index 40382c98b4..64402953a0 100644 --- a/awx/main/signals.py +++ b/awx/main/signals.py @@ -318,15 +318,10 @@ def activity_stream_create(sender, instance, created, **kwargs): return # TODO: Rethink details of the new instance object1 = camelcase_to_underscore(instance.__class__.__name__) - changes = model_to_dict(instance, model_serializer_mapping) - # Special case where Job survey password variables need to be hidden - if type(instance) == Job: - if 'extra_vars' in changes: - changes['extra_vars'] = instance.display_extra_vars() activity_entry = ActivityStream( operation='create', object1=object1, - changes=json.dumps(changes)) + changes=json.dumps(model_to_dict(instance, model_serializer_mapping))) activity_entry.save() #TODO: Weird situation where cascade SETNULL doesn't work # it might actually be a good idea to remove all of these FK references since @@ -384,16 +379,11 @@ def activity_stream_associate(sender, instance, **kwargs): obj1 = instance object1=camelcase_to_underscore(obj1.__class__.__name__) obj_rel = sender.__module__ + "." + sender.__name__ - for entity_acted in kwargs['pk_set']: obj2 = kwargs['model'] obj2_id = entity_acted obj2_actual = obj2.objects.get(id=obj2_id) - if isinstance(obj2_actual, Role) and obj2_actual.content_object is not None: - obj2_actual = obj2_actual.content_object - object2 = camelcase_to_underscore(obj2_actual.__class__.__name__) - else: - object2 = camelcase_to_underscore(obj2.__name__) + object2 = camelcase_to_underscore(obj2.__name__) # Skip recording any inventory source, or system job template changes here. if isinstance(obj1, InventorySource) or isinstance(obj2_actual, InventorySource): continue @@ -419,7 +409,7 @@ def activity_stream_associate(sender, instance, **kwargs): # If the m2m is from the User side we need to # set the content_object of the Role for our entry. if type(instance) == User and role.content_object is not None: - getattr(activity_entry, role.content_type.name.replace(' ', '_')).add(role.content_object) + getattr(activity_entry, role.content_type.name).add(role.content_object) activity_entry.role.add(role) activity_entry.object_relationship_type = obj_rel diff --git a/awx/main/tasks.py b/awx/main/tasks.py index 41d8b04c91..50ba05a2e5 100644 --- a/awx/main/tasks.py +++ b/awx/main/tasks.py @@ -423,24 +423,6 @@ class BaseTask(Task): '': '', } - def add_ansible_venv(self, env): - if settings.ANSIBLE_USE_VENV: - env['VIRTUAL_ENV'] = settings.ANSIBLE_VENV_PATH - env['PATH'] = os.path.join(settings.ANSIBLE_VENV_PATH, "bin") + ":" + env['PATH'] - venv_libdir = os.path.join(settings.ANSIBLE_VENV_PATH, "lib") - env.pop('PYTHONPATH', None) # default to none if no python_ver matches - for python_ver in ["python2.7", "python2.6"]: - if os.path.isdir(os.path.join(venv_libdir, python_ver)): - env['PYTHONPATH'] = os.path.join(venv_libdir, python_ver, "site-packages") + ":" - break - return env - - def add_tower_venv(self, env): - if settings.TOWER_USE_VENV: - env['VIRTUAL_ENV'] = settings.TOWER_VENV_PATH - env['PATH'] = os.path.join(settings.TOWER_VENV_PATH, "bin") + ":" + env['PATH'] - return env - def build_env(self, instance, **kwargs): ''' Build environment dictionary for ansible-playbook. @@ -456,8 +438,10 @@ class BaseTask(Task): # Set environment variables needed for inventory and job event # callbacks to work. # Update PYTHONPATH to use local site-packages. - # NOTE: - # Derived class should call add_ansible_venv() or add_tower_venv() + if settings.ANSIBLE_USE_VENV: + env['VIRTUAL_ENV'] = settings.ANSIBLE_VENV_PATH + env['PATH'] = os.path.join(settings.ANSIBLE_VENV_PATH, "bin") + ":" + env['PATH'] + env['PYTHONPATH'] = os.path.join(settings.ANSIBLE_VENV_PATH, "lib/python2.7/site-packages/") + ":" if self.should_use_proot(instance, **kwargs): env['PROOT_TMP_DIR'] = tower_settings.AWX_PROOT_BASE_PATH return env @@ -772,7 +756,6 @@ class RunJob(BaseTask): plugin_dirs.append(tower_settings.AWX_ANSIBLE_CALLBACK_PLUGINS) plugin_path = ':'.join(plugin_dirs) env = super(RunJob, self).build_env(job, **kwargs) - env = self.add_ansible_venv(env) # Set environment variables needed for inventory and job event # callbacks to work. env['JOB_ID'] = str(job.pk) @@ -807,7 +790,6 @@ class RunJob(BaseTask): elif cloud_cred and cloud_cred.kind == 'rax': env['RAX_USERNAME'] = cloud_cred.username env['RAX_API_KEY'] = decrypt_field(cloud_cred, 'password') - env['CLOUD_VERIFY_SSL'] = str(True) elif cloud_cred and cloud_cred.kind == 'gce': env['GCE_EMAIL'] = cloud_cred.username env['GCE_PROJECT'] = cloud_cred.project @@ -933,10 +915,7 @@ class RunJob(BaseTask): 'tower_user_name': job.created_by.username, }) if job.extra_vars_dict: - if kwargs.get('display', False) and job.job_template and job.job_template.survey_enabled: - extra_vars.update(json.loads(job.display_extra_vars())) - else: - extra_vars.update(job.extra_vars_dict) + extra_vars.update(job.extra_vars_dict) args.extend(['-e', json.dumps(extra_vars)]) # Add path to playbook (relative to project.local_path). @@ -946,9 +925,6 @@ class RunJob(BaseTask): args.append(job.playbook) return args - def build_safe_args(self, job, **kwargs): - return self.build_args(job, display=True, **kwargs) - def build_cwd(self, job, **kwargs): if job.project is None and job.job_type == PERM_INVENTORY_SCAN: return self.get_path_to('..', 'playbooks') @@ -1050,7 +1026,6 @@ class RunProjectUpdate(BaseTask): Build environment dictionary for ansible-playbook. ''' env = super(RunProjectUpdate, self).build_env(project_update, **kwargs) - env = self.add_ansible_venv(env) env['ANSIBLE_ASK_PASS'] = str(False) env['ANSIBLE_ASK_SUDO_PASS'] = str(False) env['DISPLAY'] = '' # Prevent stupid password popup when running tests. @@ -1351,7 +1326,9 @@ class RunInventoryUpdate(BaseTask): """ env = super(RunInventoryUpdate, self).build_env(inventory_update, **kwargs) - env = self.add_tower_venv(env) + if settings.TOWER_USE_VENV: + env['VIRTUAL_ENV'] = settings.TOWER_VENV_PATH + env['PATH'] = os.path.join(settings.TOWER_VENV_PATH, "bin") + ":" + env['PATH'] # Pass inventory source ID to inventory script. env['INVENTORY_SOURCE_ID'] = str(inventory_update.inventory_source_id) env['INVENTORY_UPDATE_ID'] = str(inventory_update.pk) @@ -1554,7 +1531,6 @@ class RunAdHocCommand(BaseTask): ''' plugin_dir = self.get_path_to('..', 'plugins', 'callback') env = super(RunAdHocCommand, self).build_env(ad_hoc_command, **kwargs) - env = self.add_ansible_venv(env) # Set environment variables needed for inventory and ad hoc event # callbacks to work. env['AD_HOC_COMMAND_ID'] = str(ad_hoc_command.pk) @@ -1711,11 +1687,5 @@ class RunSystemJob(BaseTask): logger.error("Failed to parse system job: " + str(e)) return args - def build_env(self, instance, **kwargs): - env = super(RunSystemJob, self).build_env(instance, - **kwargs) - env = self.add_tower_venv(env) - return env - def build_cwd(self, instance, **kwargs): return settings.BASE_DIR diff --git a/awx/main/tests/conftest.py b/awx/main/tests/conftest.py deleted file mode 100644 index 470f43e661..0000000000 --- a/awx/main/tests/conftest.py +++ /dev/null @@ -1,41 +0,0 @@ - -# Python -import pytest - -from awx.main.tests.factories import ( - create_organization, - create_job_template, - create_notification_template, - create_survey_spec, -) - -@pytest.fixture -def job_template_factory(): - return create_job_template - -@pytest.fixture -def organization_factory(): - return create_organization - -@pytest.fixture -def notification_template_factory(): - return create_notification_template - -@pytest.fixture -def survey_spec_factory(): - return create_survey_spec - -@pytest.fixture -def job_with_secret_key_factory(job_template_factory): - def rf(persisted): - "Returns job with linked JT survey with password survey questions" - objects = job_template_factory('jt', organization='org1', survey=[ - {'variable': 'submitter_email', 'type': 'text', 'default': 'foobar@redhat.com'}, - {'variable': 'secret_key', 'default': '6kQngg3h8lgiSTvIEb21', 'type': 'password'}, - {'variable': 'SSN', 'type': 'password'}], jobs=[1], persisted=persisted) - return objects.jobs[1] - return rf - -@pytest.fixture -def job_with_secret_key_unit(job_with_secret_key_factory): - return job_with_secret_key_factory(persisted=False) diff --git a/awx/main/tests/factories/README.md b/awx/main/tests/factories/README.md deleted file mode 100644 index c451c02598..0000000000 --- a/awx/main/tests/factories/README.md +++ /dev/null @@ -1,65 +0,0 @@ -factories -========= - -This is a module for defining stand-alone factories and fixtures. Ideally a fixture will implement a single item. -DO NOT decorate fixtures in this module with the @pytest.fixture. These fixtures are to be combined -with fixture factories and composition using the `conftest.py` convention. Those composed fixtures -will be decorated for usage and discovery. - -Use the fixtures directly in factory methods to build up the desired set of components and relationships. -Each fixture should create exactly one object and should support the option for that object to be persisted -or not. - -A factory should create at a minimum a single object for that factory type. The creation of any -associated objects should be explicit. For example, the `create_organization` factory when given only -a `name` parameter will create an Organization but it will not implicitly create any other objects. - -teams ------ - -There is some special handling for users when adding teams. There is a short hand that allows you to -assign a user to the member\_role of a team using the string notation of `team_name:user_name`. There is -no shortcut for adding a user to the admin\_role of a team. See the roles section for more information -about how to do that. - -roles ------ - -The roles helper allows you pass in roles to a factory. These roles assignments will happen after -the objects are created. Using the roles parameter required that persisted=True (default). - -You can use a string notation of `object_name.role_name:user` OR `object_name.role_name:object_name.child_role` - - obj.parent_role:user # This will make the user a member of parent_role - obj1.role:obj2.role # This will make obj2 a child role of obj1 - - team1.admin_role:joe - team1.admin_role:project1.admin_role - -examples --------- - - objects = create_organization('test-org') - assert objects.organization.name == 'test-org' - - objects = create_organization('test-org', projects=['test-proj']) - assert objects.projects.test-proj.organization == objects.organization - - objects = create_organization('test-org', persisted=False) - assert not objects.organization.pk - -patterns --------- - -`mk` functions are single object fixtures. They should create only a single object with the minimum deps. -They should also accept a `persited` flag, if they must be persisted to work, they raise an error if persisted=False - -`generate` and `apply` functions are helpers that build up the various parts of a `create` functions objects. These -should be useful for more than one create function to use and should explicitly accept all of the values needed -to execute. These functions should also be robust and have very speciifc error reporting about constraints and/or -bad values. - -`create` functions compose many of the `mk` and `generate` functions to make different object -factories. These functions when giving the minimum set of arguments should only produce a -single artifact (or the minimum needed for that object). These should be wrapped by discoverable -fixtures in various conftest.py files. diff --git a/awx/main/tests/factories/__init__.py b/awx/main/tests/factories/__init__.py deleted file mode 100644 index 81a1144a52..0000000000 --- a/awx/main/tests/factories/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -from .tower import ( - create_organization, - create_job_template, - create_notification_template, - create_survey_spec, -) - -from .exc import ( - NotUnique, -) - -__all__ = [ - 'create_organization', - 'create_job_template', - 'create_notification_template', - 'create_survey_spec', - 'NotUnique', -] diff --git a/awx/main/tests/factories/exc.py b/awx/main/tests/factories/exc.py deleted file mode 100644 index aa51de5bd3..0000000000 --- a/awx/main/tests/factories/exc.py +++ /dev/null @@ -1,5 +0,0 @@ -class NotUnique(Exception): - def __init__(self, name, objects): - msg = '{} is not a unique key, found {}={}'.format(name, name, objects[name]) - super(Exception, self).__init__(msg) - diff --git a/awx/main/tests/factories/fixtures.py b/awx/main/tests/factories/fixtures.py deleted file mode 100644 index 008f3fca4b..0000000000 --- a/awx/main/tests/factories/fixtures.py +++ /dev/null @@ -1,150 +0,0 @@ -import json - -from django.contrib.auth.models import User - -from awx.main.models import ( - Organization, - Project, - Team, - Instance, - JobTemplate, - Job, - NotificationTemplate, - Credential, - Inventory, - Label, -) - -# mk methods should create only a single object of a single type. -# they should also have the option of being persisted or not. -# if the object must be persisted an error should be raised when -# persisted=False -# - -def mk_instance(persisted=True): - if not persisted: - raise RuntimeError('creating an Instance requires persisted=True') - from django.conf import settings - return Instance.objects.get_or_create(uuid=settings.SYSTEM_UUID, primary=True, hostname="instance.example.org") - - -def mk_organization(name, description=None, persisted=True): - description = description or '{}-description'.format(name) - org = Organization(name=name, description=description) - if persisted: - mk_instance(persisted) - org.save() - return org - - -def mk_label(name, organization=None, description=None, persisted=True): - description = description or '{}-description'.format(name) - label = Label(name=name, description=description) - if organization is not None: - label.organization = organization - if persisted: - label.save() - return label - - -def mk_team(name, organization=None, persisted=True): - team = Team(name=name) - if organization is not None: - team.organization = organization - if persisted: - mk_instance(persisted) - team.save() - return team - - -def mk_user(name, is_superuser=False, organization=None, team=None, persisted=True): - user = User(username=name, is_superuser=is_superuser) - if persisted: - user.save() - if organization is not None: - organization.member_role.members.add(user) - if team is not None: - team.member_role.members.add(user) - return user - - -def mk_project(name, organization=None, description=None, persisted=True): - description = description or '{}-description'.format(name) - project = Project(name=name, description=description) - if organization is not None: - project.organization = organization - if persisted: - project.save() - return project - - -def mk_credential(name, cloud=False, kind='ssh', persisted=True): - cred = Credential(name=name, cloud=cloud, kind=kind) - if persisted: - cred.save() - return cred - - -def mk_notification_template(name, notification_type='webhook', configuration=None, organization=None, persisted=True): - nt = NotificationTemplate(name=name) - nt.notification_type = notification_type - nt.notification_configuration = configuration or dict(url="http://localhost", headers={"Test": "Header"}) - - if organization is not None: - nt.organization = organization - if persisted: - nt.save() - return nt - - -def mk_inventory(name, organization=None, persisted=True): - inv = Inventory(name=name) - if organization is not None: - inv.organization = organization - if persisted: - inv.save() - return inv - - -def mk_job(job_type='run', status='new', job_template=None, inventory=None, - credential=None, project=None, extra_vars={}, - persisted=True): - job = Job(job_type=job_type, status=status, extra_vars=json.dumps(extra_vars)) - - job.job_template = job_template - job.inventory = inventory - job.credential = credential - job.project = project - - if persisted: - job.save() - return job - - -def mk_job_template(name, job_type='run', - organization=None, inventory=None, - credential=None, persisted=True, extra_vars='', - project=None, spec=None): - if extra_vars: - extra_vars = json.dumps(extra_vars) - - jt = JobTemplate(name=name, job_type=job_type, extra_vars=extra_vars, - playbook='mocked') - - jt.inventory = inventory - if jt.inventory is None: - jt.ask_inventory_on_launch = True - - jt.credential = credential - if jt.credential is None: - jt.ask_credential_on_launch = True - - jt.project = project - - jt.survey_spec = spec - if jt.survey_spec is not None: - jt.survey_enabled = True - - if persisted: - jt.save() - return jt diff --git a/awx/main/tests/factories/objects.py b/awx/main/tests/factories/objects.py deleted file mode 100644 index 9f739cc9cf..0000000000 --- a/awx/main/tests/factories/objects.py +++ /dev/null @@ -1,59 +0,0 @@ -from collections import namedtuple - -from .exc import NotUnique - -def generate_objects(artifacts, kwargs): - '''generate_objects takes a list of artifacts that are supported by - a create function and compares it to the kwargs passed in to the create - function. If a kwarg is found that is not in the artifacts list a RuntimeError - is raised. - ''' - for k in kwargs.keys(): - if k not in artifacts: - raise RuntimeError('{} is not a valid argument'.format(k)) - return namedtuple("Objects", ",".join(artifacts)) - - -def generate_role_objects(objects): - '''generate_role_objects assembles a dictionary of all possible objects by name. - It will raise an exception if any of the objects share a name due to the fact that - it is to be used with apply_roles, which expects unique object names. - - roles share a common name e.g. admin_role, member_role. This ensures that the - roles short hand used for mapping Roles and Users in apply_roles will function as desired. - ''' - combined_objects = {} - for o in objects: - if type(o) is dict: - for k,v in o.iteritems(): - if combined_objects.get(k) is not None: - raise NotUnique(k, combined_objects) - combined_objects[k] = v - elif hasattr(o, 'name'): - if combined_objects.get(o.name) is not None: - raise NotUnique(o.name, combined_objects) - combined_objects[o.name] = o - else: - if o is not None: - raise RuntimeError('expected a list of dict or list of list, got a type {}'.format(type(o))) - return combined_objects - - -class _Mapped(object): - '''_Mapped is a helper class that replaces spaces and dashes - in the name of an object and assigns the object as an attribute - - input: {'my org': Organization} - output: instance.my_org = Organization - ''' - def __init__(self, d): - self.d = d - for k,v in d.items(): - k = k.replace(' ', '_') - k = k.replace('-', '_') - - setattr(self, k.replace(' ','_'), v) - - def all(self): - return self.d.values() - diff --git a/awx/main/tests/factories/tower.py b/awx/main/tests/factories/tower.py deleted file mode 100644 index 5247f4195a..0000000000 --- a/awx/main/tests/factories/tower.py +++ /dev/null @@ -1,332 +0,0 @@ -from django.contrib.auth.models import User - -from awx.main.models import ( - Organization, - Project, - Team, - NotificationTemplate, - Credential, - Inventory, - Job, - Label, -) - -from .objects import ( - generate_objects, - generate_role_objects, - _Mapped, -) - -from .fixtures import ( - mk_organization, - mk_team, - mk_user, - mk_job_template, - mk_job, - mk_credential, - mk_inventory, - mk_project, - mk_label, - mk_notification_template, -) - - -def apply_roles(roles, objects, persisted): - '''apply_roles evaluates a list of Role relationships represented as strings. - The format of this string is 'role:[user|role]'. When a user is provided, they will be - made a member of the role on the LHS. When a role is provided that role will be added to - the children of the role on the LHS. - - This function assumes that objects is a dictionary that contains a unique set of key to value - mappings for all possible "Role objects". See the example below: - - Mapping Users - ------------- - roles = ['org1.admin_role:user1', 'team1.admin_role:user1'] - objects = {'org1': Organization, 'team1': Team, 'user1': User] - - Mapping Roles - ------------- - roles = ['org1.admin_role:team1.admin_role'] - objects = {'org1': Organization, 'team1': Team} - - Invalid Mapping - --------------- - roles = ['org1.admin_role:team1.admin_role'] - objects = {'org1': Organization', 'user1': User} # Exception, no team1 entry - ''' - if roles is None: - return None - - if not persisted: - raise RuntimeError('roles can not be used when persisted=False') - - for role in roles: - obj_role, sep, member_role = role.partition(':') - if not member_role: - raise RuntimeError('you must provide an assignment role, got None') - - obj_str, o_role_str = obj_role.split('.') - member_str, m_sep, m_role_str = member_role.partition('.') - - obj = objects[obj_str] - obj_role = getattr(obj, o_role_str) - - member = objects[member_str] - if m_role_str: - if hasattr(member, m_role_str): - member_role = getattr(member, m_role_str) - obj_role.children.add(member_role) - else: - raise RuntimeError('unable to find {} role for {}'.format(m_role_str, member_str)) - else: - if type(member) is User: - obj_role.members.add(member) - else: - raise RuntimeError('unable to add non-user {} for members list of {}'.format(member_str, obj_str)) - -def generate_users(organization, teams, superuser, persisted, **kwargs): - '''generate_users evaluates a mixed list of User objects and strings. - If a string is encountered a user with that username is created and added to the lookup dict. - If a User object is encountered the User.username is used as a key for the lookup dict. - - A short hand for assigning a user to a team is available in the following format: "team_name:username". - If a string in that format is encounted an attempt to lookup the team by the key team_name from the teams - argumnent is made, a KeyError will be thrown if the team does not exist in the dict. The teams argument should - be a dict of {Team.name:Team} - ''' - users = {} - key = 'superusers' if superuser else 'users' - if key in kwargs and kwargs.get(key) is not None: - for u in kwargs[key]: - if type(u) is User: - users[u.username] = u - else: - p1, sep, p2 = u.partition(':') - if p2: - t = teams[p1] - users[p2] = mk_user(p2, organization=organization, team=t, is_superuser=superuser, persisted=persisted) - else: - users[p1] = mk_user(p1, organization=organization, team=None, is_superuser=superuser, persisted=persisted) - return users - -def generate_teams(organization, persisted, **kwargs): - '''generate_teams evalutes a mixed list of Team objects and strings. - If a string is encountered a team with that string name is created and added to the lookup dict. - If a Team object is encounted the Team.name is used as a key for the lookup dict. - ''' - teams = {} - if 'teams' in kwargs and kwargs.get('teams') is not None: - for t in kwargs['teams']: - if type(t) is Team: - teams[t.name] = t - else: - teams[t] = mk_team(t, organization=organization, persisted=persisted) - return teams - -def create_survey_spec(variables=None, default_type='integer', required=True): - ''' - Returns a valid survey spec for a job template, based on the input - argument specifying variable name(s) - ''' - if isinstance(variables, list): - name = "%s survey" % variables[0] - description = "A survey that starts with %s." % variables[0] - vars_list = variables - else: - name = "%s survey" % variables - description = "A survey about %s." % variables - vars_list = [variables] - - spec = [] - index = 0 - for var in vars_list: - spec_item = {} - spec_item['index'] = index - index += 1 - spec_item['required'] = required - spec_item['choices'] = '' - spec_item['type'] = default_type - if isinstance(var, dict): - spec_item.update(var) - var_name = spec_item.get('variable', 'variable') - else: - var_name = var - spec_item.setdefault('variable', var_name) - spec_item.setdefault('question_name', "Enter a value for %s." % var_name) - spec_item.setdefault('question_description', "A question about %s." % var_name) - if spec_item['type'] == 'integer': - spec_item.setdefault('default', 0) - spec_item.setdefault('max', spec_item['default'] + 100) - spec_item.setdefault('min', spec_item['default'] - 100) - else: - spec_item.setdefault('default', '') - spec.append(spec_item) - - survey_spec = {} - survey_spec['spec'] = spec - survey_spec['name'] = name - survey_spec['description'] = description - return survey_spec - - -# create methods are intended to be called directly as needed -# or encapsulated by specific factory fixtures in a conftest -# - -def create_job_template(name, roles=None, persisted=True, **kwargs): - Objects = generate_objects(["job_template", "jobs", - "organization", - "inventory", - "project", - "credential", - "job_type", - "survey",], kwargs) - - org = None - proj = None - inv = None - cred = None - spec = None - jobs = {} - job_type = kwargs.get('job_type', 'run') - extra_vars = kwargs.get('extra_vars', '') - - if 'organization' in kwargs: - org = kwargs['organization'] - if type(org) is not Organization: - org = mk_organization(org, '%s-desc'.format(org), persisted=persisted) - - if 'credential' in kwargs: - cred = kwargs['credential'] - if type(cred) is not Credential: - cred = mk_credential(cred, persisted=persisted) - - if 'project' in kwargs: - proj = kwargs['project'] - if type(proj) is not Project: - proj = mk_project(proj, organization=org, persisted=persisted) - - if 'inventory' in kwargs: - inv = kwargs['inventory'] - if type(inv) is not Inventory: - inv = mk_inventory(inv, organization=org, persisted=persisted) - - if 'survey' in kwargs: - spec = create_survey_spec(kwargs['survey']) - - jt = mk_job_template(name, project=proj, - inventory=inv, credential=cred, - job_type=job_type, spec=spec, extra_vars=extra_vars, - persisted=persisted) - - if 'jobs' in kwargs: - for i in kwargs['jobs']: - if type(i) is Job: - jobs[i.pk] = i - else: - # Fill in default survey answers - job_extra_vars = {} - for question in spec['spec']: - job_extra_vars[question['variable']] = question['default'] - jobs[i] = mk_job(job_template=jt, project=proj, inventory=inv, credential=cred, - extra_vars=job_extra_vars, - job_type=job_type, persisted=persisted) - - role_objects = generate_role_objects([org, proj, inv, cred]) - apply_roles(roles, role_objects, persisted) - - return Objects(job_template=jt, - jobs=jobs, - project=proj, - inventory=inv, - credential=cred, - job_type=job_type, - organization=org, - survey=spec,) - -def create_organization(name, roles=None, persisted=True, **kwargs): - Objects = generate_objects(["organization", - "teams", "users", - "superusers", - "projects", - "labels", - "notification_templates", - "inventories",], kwargs) - - projects = {} - inventories = {} - labels = {} - notification_templates = {} - - org = mk_organization(name, '%s-desc'.format(name), persisted=persisted) - - if 'inventories' in kwargs: - for i in kwargs['inventories']: - if type(i) is Inventory: - inventories[i.name] = i - else: - inventories[i] = mk_inventory(i, organization=org, persisted=persisted) - - if 'projects' in kwargs: - for p in kwargs['projects']: - if type(p) is Project: - projects[p.name] = p - else: - projects[p] = mk_project(p, organization=org, persisted=persisted) - - teams = generate_teams(org, persisted, teams=kwargs.get('teams')) - superusers = generate_users(org, teams, True, persisted, superusers=kwargs.get('superusers')) - users = generate_users(org, teams, False, persisted, users=kwargs.get('users')) - - if 'labels' in kwargs: - for l in kwargs['labels']: - if type(l) is Label: - labels[l.name] = l - else: - labels[l] = mk_label(l, organization=org, persisted=persisted) - - if 'notification_templates' in kwargs: - for nt in kwargs['notification_templates']: - if type(nt) is NotificationTemplate: - notification_templates[nt.name] = nt - else: - notification_templates[nt] = mk_notification_template(nt, organization=org, persisted=persisted) - - role_objects = generate_role_objects([org, superusers, users, teams, projects, labels, notification_templates]) - apply_roles(roles, role_objects, persisted) - return Objects(organization=org, - superusers=_Mapped(superusers), - users=_Mapped(users), - teams=_Mapped(teams), - projects=_Mapped(projects), - labels=_Mapped(labels), - notification_templates=_Mapped(notification_templates), - inventories=_Mapped(inventories)) - -def create_notification_template(name, roles=None, persisted=True, **kwargs): - Objects = generate_objects(["notification_template", - "organization", - "users", - "superusers", - "teams",], kwargs) - - organization = None - - if 'organization' in kwargs: - org = kwargs['organization'] - organization = mk_organization(org, '{}-desc'.format(org), persisted=persisted) - - notification_template = mk_notification_template(name, organization=organization, persisted=persisted) - - teams = generate_teams(organization, persisted, teams=kwargs.get('teams')) - superusers = generate_users(organization, teams, True, persisted, superusers=kwargs.get('superusers')) - users = generate_users(organization, teams, False, persisted, users=kwargs.get('users')) - - role_objects = generate_role_objects([organization, notification_template]) - apply_roles(roles, role_objects, persisted) - return Objects(notification_template=notification_template, - organization=organization, - users=_Mapped(users), - superusers=_Mapped(superusers), - teams=teams) diff --git a/awx/main/tests/functional/api/test_activity_streams.py b/awx/main/tests/functional/api/test_activity_streams.py index 39990064d7..43e809afb9 100644 --- a/awx/main/tests/functional/api/test_activity_streams.py +++ b/awx/main/tests/functional/api/test_activity_streams.py @@ -131,24 +131,3 @@ def test_stream_queryset_hides_shows_items( assert queryset.filter(host__pk=host.pk, operation='create').count() == 1 assert queryset.filter(team__pk=team.pk, operation='create').count() == 1 assert queryset.filter(notification_template__pk=notification_template.pk, operation='create').count() == 1 - -@pytest.mark.django_db -@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled) -def test_stream_user_direct_role_updates(get, post, organization_factory): - objects = organization_factory('test_org', - superusers=['admin'], - users=['test'], - inventories=['inv1']) - - url = reverse('api:user_roles_list', args=(objects.users.test.pk,)) - post(url, dict(id=objects.inventories.inv1.read_role.pk), objects.superusers.admin) - - activity_stream = ActivityStream.objects.filter( - inventory__pk=objects.inventories.inv1.pk, - user__pk=objects.users.test.pk, - role__pk=objects.inventories.inv1.read_role.pk).first() - url = reverse('api:activity_stream_detail', args=(activity_stream.pk,)) - response = get(url, objects.users.test) - - assert response.data['object1'] == 'user' - assert response.data['object2'] == 'inventory' diff --git a/awx/main/tests/functional/api/test_adhoc.py b/awx/main/tests/functional/api/test_adhoc.py deleted file mode 100644 index 43326afcb4..0000000000 --- a/awx/main/tests/functional/api/test_adhoc.py +++ /dev/null @@ -1,148 +0,0 @@ -import mock # noqa -import pytest - -from django.core.urlresolvers import reverse - - - -""" - def run_test_ad_hoc_command(self, **kwargs): - # Post to list to start a new ad hoc command. - expect = kwargs.pop('expect', 201) - url = kwargs.pop('url', reverse('api:ad_hoc_command_list')) - data = { - 'inventory': self.inventory.pk, - 'credential': self.credential.pk, - 'module_name': 'command', - 'module_args': 'uptime', - } - data.update(kwargs) - for k,v in data.items(): - if v is None: - del data[k] - return self.post(url, data, expect=expect) -""" - -@pytest.fixture -def post_adhoc(post, inventory, machine_credential): - def f(url, data, user, expect=201): - if not url: - url = reverse('api:ad_hoc_command_list') - - if 'module_name' not in data: - data['module_name'] = 'command' - if 'module_args' not in data: - data['module_args'] = 'uptime' - if 'inventory' not in data: - data['inventory'] = inventory.id - if 'credential' not in data: - data['credential'] = machine_credential.id - - for k,v in data.items(): - if v is None: - del data[k] - - return post(url, data, user, expect=expect) - return f - - - -@pytest.mark.django_db -def test_admin_post_ad_hoc_command_list(admin, post_adhoc, inventory, machine_credential): - res = post_adhoc(reverse('api:ad_hoc_command_list'), {}, admin, expect=201) - assert res.data['job_type'] == 'run' - assert res.data['inventory'], inventory.id - assert res.data['credential'] == machine_credential.id - assert res.data['module_name'] == 'command' - assert res.data['module_args'] == 'uptime' - assert res.data['limit'] == '' - assert res.data['forks'] == 0 - assert res.data['verbosity'] == 0 - assert res.data['become_enabled'] is False - - -@pytest.mark.django_db -def test_empty_post_403(admin, post): - post(reverse('api:ad_hoc_command_list'), {}, admin, expect=400) - -@pytest.mark.django_db -def test_empty_put_405(admin, put): - put(reverse('api:ad_hoc_command_list'), {}, admin, expect=405) - -@pytest.mark.django_db -def test_empty_patch_405(admin, patch): - patch(reverse('api:ad_hoc_command_list'), {}, admin, expect=405) - -@pytest.mark.django_db -def test_empty_delete_405(admin, delete): - delete(reverse('api:ad_hoc_command_list'), admin, expect=405) - -@pytest.mark.django_db -def test_user_post_ad_hoc_command_list(alice, post_adhoc, inventory, machine_credential): - inventory.adhoc_role.members.add(alice) - machine_credential.use_role.members.add(alice) - post_adhoc(reverse('api:ad_hoc_command_list'), {}, alice, expect=201) - -@pytest.mark.django_db -def test_user_post_ad_hoc_command_list_xfail(alice, post_adhoc, inventory, machine_credential): - inventory.read_role.members.add(alice) # just read access? no dice. - machine_credential.use_role.members.add(alice) - post_adhoc(reverse('api:ad_hoc_command_list'), {}, alice, expect=403) - -@pytest.mark.django_db -def test_user_post_ad_hoc_command_list_without_creds(alice, post_adhoc, inventory, machine_credential): - inventory.adhoc_role.members.add(alice) - post_adhoc(reverse('api:ad_hoc_command_list'), {}, alice, expect=403) - -@pytest.mark.django_db -def test_user_post_ad_hoc_command_list_without_inventory(alice, post_adhoc, inventory, machine_credential): - machine_credential.use_role.members.add(alice) - post_adhoc(reverse('api:ad_hoc_command_list'), {}, alice, expect=403) - - -@pytest.mark.django_db -def test_admin_post_inventory_ad_hoc_command_list(admin, post_adhoc, inventory): - post_adhoc(reverse('api:inventory_ad_hoc_commands_list', args=(inventory.id,)), {'inventory': None}, admin, expect=201) - post_adhoc(reverse('api:inventory_ad_hoc_commands_list', args=(inventory.id,)), {}, admin, expect=201) - - -@pytest.mark.django_db -def test_get_inventory_ad_hoc_command_list(admin, alice, post_adhoc, get, inventory_factory, machine_credential): - inv1 = inventory_factory('inv1') - inv2 = inventory_factory('inv2') - - post_adhoc(reverse('api:ad_hoc_command_list'), {'inventory': inv1.id}, admin, expect=201) - post_adhoc(reverse('api:ad_hoc_command_list'), {'inventory': inv2.id}, admin, expect=201) - res = get(reverse('api:ad_hoc_command_list'), admin, expect=200) - assert res.data['count'] == 2 - res = get(reverse('api:inventory_ad_hoc_commands_list', args=(inv1.id,)), admin, expect=200) - assert res.data['count'] == 1 - res = get(reverse('api:inventory_ad_hoc_commands_list', args=(inv2.id,)), admin, expect=200) - assert res.data['count'] == 1 - - inv1.adhoc_role.members.add(alice) - res = get(reverse('api:inventory_ad_hoc_commands_list', args=(inv1.id,)), alice, expect=200) - assert res.data['count'] == 0 - - machine_credential.use_role.members.add(alice) - res = get(reverse('api:inventory_ad_hoc_commands_list', args=(inv1.id,)), alice, expect=200) - assert res.data['count'] == 1 - res = get(reverse('api:inventory_ad_hoc_commands_list', args=(inv2.id,)), alice, expect=403) - - -@pytest.mark.django_db -def test_bad_data1(admin, post_adhoc): - post_adhoc(reverse('api:ad_hoc_command_list'), {'module_name': 'command', 'module_args': None}, admin, expect=400) - -@pytest.mark.django_db -def test_bad_data2(admin, post_adhoc): - post_adhoc(reverse('api:ad_hoc_command_list'), {'job_type': 'baddata'}, admin, expect=400) - -@pytest.mark.django_db -def test_bad_data3(admin, post_adhoc): - post_adhoc(reverse('api:ad_hoc_command_list'), {'verbosity': -1}, admin, expect=400) - -@pytest.mark.django_db -def test_bad_data4(admin, post_adhoc): - post_adhoc(reverse('api:ad_hoc_command_list'), {'forks': -1}, admin, expect=400) - diff --git a/awx/main/tests/functional/api/test_credential.py b/awx/main/tests/functional/api/test_credential.py index e594c95c1d..afe3bb7f29 100644 --- a/awx/main/tests/functional/api/test_credential.py +++ b/awx/main/tests/functional/api/test_credential.py @@ -147,7 +147,8 @@ def test_credential_detail(post, get, organization, org_admin): response = get(reverse('api:credential_detail', args=(response.data['id'],)), org_admin) assert response.status_code == 200 summary_fields = response.data['summary_fields'] - assert 'organization' in summary_fields + assert 'owners' in summary_fields + assert summary_fields['owners'][0]['id'] == organization.id related_fields = response.data['related'] assert 'organization' in related_fields diff --git a/awx/main/tests/functional/api/test_job_runtime_params.py b/awx/main/tests/functional/api/test_job_runtime_params.py index 46aeadb6d0..cfda95213a 100644 --- a/awx/main/tests/functional/api/test_job_runtime_params.py +++ b/awx/main/tests/functional/api/test_job_runtime_params.py @@ -70,7 +70,7 @@ def bad_scan_JT(job_template_prompts): # End of setup, tests start here @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_ignore_unprompted_vars(runtime_data, job_template_prompts, post, admin_user, mocker): +def test_job_ignore_unprompted_vars(runtime_data, job_template_prompts, post, user, mocker): job_template = job_template_prompts(False) mock_job = mocker.MagicMock(spec=Job, id=968, **runtime_data) @@ -78,7 +78,8 @@ def test_job_ignore_unprompted_vars(runtime_data, job_template_prompts, post, ad with mocker.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', return_value=mock_job): with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): response = post(reverse('api:job_template_launch', args=[job_template.pk]), - runtime_data, admin_user, expect=201) + runtime_data, user('admin', True)) + assert response.status_code == 201 # Check that job is serialized correctly job_id = response.data['job'] @@ -98,7 +99,7 @@ def test_job_ignore_unprompted_vars(runtime_data, job_template_prompts, post, ad @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_accept_prompted_vars(runtime_data, job_template_prompts, post, admin_user, mocker): +def test_job_accept_prompted_vars(runtime_data, job_template_prompts, post, user, mocker): job_template = job_template_prompts(True) mock_job = mocker.MagicMock(spec=Job, id=968, **runtime_data) @@ -106,8 +107,9 @@ def test_job_accept_prompted_vars(runtime_data, job_template_prompts, post, admi with mocker.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', return_value=mock_job): with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): response = post(reverse('api:job_template_launch', args=[job_template.pk]), - runtime_data, admin_user, expect=201) + runtime_data, user('admin', True)) + assert response.status_code == 201 job_id = response.data['job'] assert job_id == 968 @@ -132,47 +134,51 @@ def test_job_accept_prompted_vars_null(runtime_data, job_template_prompts_null, with mocker.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', return_value=mock_job): with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): response = post(reverse('api:job_template_launch', args=[job_template.pk]), - runtime_data, rando, expect=201) + runtime_data, rando) + assert response.status_code == 201 job_id = response.data['job'] assert job_id == 968 mock_job.signal_start.assert_called_once_with(**runtime_data) @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_reject_invalid_prompted_vars(runtime_data, job_template_prompts, post, admin_user): +def test_job_reject_invalid_prompted_vars(runtime_data, job_template_prompts, post, user): job_template = job_template_prompts(True) response = post( reverse('api:job_template_launch', args=[job_template.pk]), dict(job_type='foobicate', # foobicate is not a valid job type - inventory=87865, credential=48474), admin_user, expect=400) + inventory=87865, credential=48474), user('admin', True)) + assert response.status_code == 400 assert response.data['job_type'] == [u'"foobicate" is not a valid choice.'] assert response.data['inventory'] == [u'Invalid pk "87865" - object does not exist.'] assert response.data['credential'] == [u'Invalid pk "48474" - object does not exist.'] @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_reject_invalid_prompted_extra_vars(runtime_data, job_template_prompts, post, admin_user): +def test_job_reject_invalid_prompted_extra_vars(runtime_data, job_template_prompts, post, user): job_template = job_template_prompts(True) response = post( reverse('api:job_template_launch', args=[job_template.pk]), - dict(extra_vars='{"unbalanced brackets":'), admin_user, expect=400) + dict(extra_vars='{"unbalanced brackets":'), user('admin', True)) + assert response.status_code == 400 assert response.data['extra_vars'] == ['Must be a valid JSON or YAML dictionary.'] @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_launch_fails_without_inventory(deploy_jobtemplate, post, admin_user): +def test_job_launch_fails_without_inventory(deploy_jobtemplate, post, user): deploy_jobtemplate.inventory = None deploy_jobtemplate.save() response = post(reverse('api:job_template_launch', - args=[deploy_jobtemplate.pk]), {}, admin_user, expect=400) + args=[deploy_jobtemplate.pk]), {}, user('admin', True)) - assert response.data['inventory'] == ["Job Template 'inventory' is missing or undefined."] + assert response.status_code == 400 + assert response.data['inventory'] == ['Job Template Inventory is missing or undefined.'] @pytest.mark.django_db @pytest.mark.job_runtime_vars @@ -182,8 +188,9 @@ def test_job_launch_fails_without_inventory_access(job_template_prompts, runtime # Assure that giving an inventory without access to the inventory blocks the launch response = post(reverse('api:job_template_launch', args=[job_template.pk]), - dict(inventory=runtime_data['inventory']), rando, expect=403) + dict(inventory=runtime_data['inventory']), rando) + assert response.status_code == 403 assert response.data['detail'] == u'You do not have permission to perform this action.' @pytest.mark.django_db @@ -194,8 +201,9 @@ def test_job_launch_fails_without_credential_access(job_template_prompts, runtim # Assure that giving a credential without access blocks the launch response = post(reverse('api:job_template_launch', args=[job_template.pk]), - dict(credential=runtime_data['credential']), rando, expect=403) + dict(credential=runtime_data['credential']), rando) + assert response.status_code == 403 assert response.data['detail'] == u'You do not have permission to perform this action.' @pytest.mark.django_db @@ -205,19 +213,20 @@ def test_job_block_scan_job_type_change(job_template_prompts, post, admin_user): # Assure that changing the type of a scan job blocks the launch response = post(reverse('api:job_template_launch', args=[job_template.pk]), - dict(job_type='scan'), admin_user, expect=400) + dict(job_type='scan'), admin_user) + assert response.status_code == 400 assert 'job_type' in response.data @pytest.mark.django_db @pytest.mark.job_runtime_vars def test_job_block_scan_job_inv_change(mocker, bad_scan_JT, runtime_data, post, admin_user): # Assure that giving a new inventory for a scan job blocks the launch - with mocker.patch('awx.main.access.BaseAccess.check_license'): + with mocker.patch('awx.main.access.BaseAccess.check_license', return_value=True): response = post(reverse('api:job_template_launch', args=[bad_scan_JT.pk]), - dict(inventory=runtime_data['inventory']), admin_user, - expect=400) + dict(inventory=runtime_data['inventory']), admin_user) + assert response.status_code == 400 assert 'inventory' in response.data @pytest.mark.django_db @@ -277,23 +286,41 @@ def test_job_launch_JT_with_validation(machine_credential, deploy_jobtemplate): @pytest.mark.django_db @pytest.mark.job_runtime_vars -def test_job_launch_unprompted_vars_with_survey(mocker, survey_spec_factory, job_template_prompts, post, admin_user): - job_template = job_template_prompts(False) - job_template.survey_enabled = True - job_template.survey_spec = survey_spec_factory('survey_var') - job_template.save() +def test_job_launch_unprompted_vars_with_survey(mocker, job_template_prompts, post, user): + with mocker.patch('awx.main.access.BaseAccess.check_license', return_value=False): + job_template = job_template_prompts(False) + job_template.survey_enabled = True + job_template.survey_spec = { + "spec": [ + { + "index": 0, + "question_name": "survey_var", + "min": 0, + "default": "", + "max": 100, + "question_description": "A survey question", + "required": True, + "variable": "survey_var", + "choices": "", + "type": "integer" + } + ], + "description": "", + "name": "" + } + job_template.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) with mocker.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}): + with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): response = post( reverse('api:job_template_launch', args=[job_template.pk]), dict(extra_vars={"job_launch_var": 3, "survey_var": 4}), - admin_user, expect=201) + user('admin', True)) + assert response.status_code == 201 - job_id = response.data['job'] - assert job_id == 968 + job_id = response.data['job'] + assert job_id == 968 - # Check that the survey variable is accepted and the job variable isn't - mock_job.signal_start.assert_called_once_with(extra_vars={"survey_var": 4}) + # Check that the survey variable is accepted and the job variable isn't + mock_job.signal_start.assert_called_once_with(extra_vars={"survey_var": 4}) diff --git a/awx/main/tests/functional/api/test_job_template.py b/awx/main/tests/functional/api/test_job_template.py deleted file mode 100644 index 64f0ad2197..0000000000 --- a/awx/main/tests/functional/api/test_job_template.py +++ /dev/null @@ -1,335 +0,0 @@ -import pytest -import mock - -# AWX -from awx.api.serializers import JobTemplateSerializer, JobLaunchSerializer -from awx.main.models.jobs import JobTemplate -from awx.main.models.projects import ProjectOptions - -# Django -from django.test.client import RequestFactory -from django.core.urlresolvers import reverse - -@property -def project_playbooks(self): - return ['mocked', 'mocked.yml', 'alt-mocked.yml'] - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -@pytest.mark.parametrize( - "grant_project, grant_credential, grant_inventory, expect", [ - (True, True, True, 201), - (True, True, False, 403), - (True, False, True, 403), - (False, True, True, 403), - ] -) -def test_create(post, project, machine_credential, inventory, alice, grant_project, grant_credential, grant_inventory, expect): - if grant_project: - project.use_role.members.add(alice) - if grant_credential: - machine_credential.use_role.members.add(alice) - if grant_inventory: - inventory.use_role.members.add(alice) - - post(reverse('api:job_template_list'), { - 'name': 'Some name', - 'project': project.id, - 'credential': machine_credential.id, - 'inventory': inventory.id, - 'playbook': 'mocked.yml', - }, alice, expect=expect) - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -@pytest.mark.parametrize( - "grant_project, grant_credential, grant_inventory, expect", [ - (True, True, True, 200), - (True, True, False, 403), - (True, False, True, 403), - (False, True, True, 403), - ] -) -def test_edit_sensitive_fields(patch, job_template_factory, alice, grant_project, grant_credential, grant_inventory, expect): - objs = job_template_factory('jt', organization='org1', project='prj', inventory='inv', credential='cred') - objs.job_template.admin_role.members.add(alice) - - if grant_project: - objs.project.use_role.members.add(alice) - if grant_credential: - objs.credential.use_role.members.add(alice) - if grant_inventory: - objs.inventory.use_role.members.add(alice) - - patch(reverse('api:job_template_detail', args=(objs.job_template.id,)), { - 'name': 'Some name', - 'project': objs.project.id, - 'credential': objs.credential.id, - 'inventory': objs.inventory.id, - 'playbook': 'alt-mocked.yml', - }, alice, expect=expect) - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -def test_edit_playbook(patch, job_template_factory, alice): - objs = job_template_factory('jt', organization='org1', project='prj', inventory='inv', credential='cred') - objs.job_template.admin_role.members.add(alice) - objs.project.use_role.members.add(alice) - objs.credential.use_role.members.add(alice) - objs.inventory.use_role.members.add(alice) - - patch(reverse('api:job_template_detail', args=(objs.job_template.id,)), { - 'playbook': 'alt-mocked.yml', - }, alice, expect=200) - - objs.inventory.use_role.members.remove(alice) - patch(reverse('api:job_template_detail', args=(objs.job_template.id,)), { - 'playbook': 'mocked.yml', - }, alice, expect=403) - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -def test_edit_nonsenstive(patch, job_template_factory, alice): - objs = job_template_factory('jt', organization='org1', project='prj', inventory='inv', credential='cred') - jt = objs.job_template - jt.admin_role.members.add(alice) - - res = patch(reverse('api:job_template_detail', args=(jt.id,)), { - 'name': 'updated', - 'description': 'bar', - 'forks': 14, - 'limit': 'something', - 'verbosity': 5, - 'extra_vars': '--', - 'job_tags': 'sometags', - 'force_handlers': True, - 'skip_tags': True, - 'ask_variables_on_launch':True, - 'ask_tags_on_launch':True, - 'ask_job_type_on_launch':True, - 'ask_inventory_on_launch':True, - 'ask_credential_on_launch': True, - }, alice, expect=200) - print(res.data) - assert res.data['name'] == 'updated' -@pytest.fixture -def jt_copy_edit(job_template_factory, project): - objects = job_template_factory( - 'copy-edit-job-template', - project=project) - return objects.job_template - -@property -def project_playbooks(self): - return ['mocked', 'mocked.yml', 'alt-mocked.yml'] - -@pytest.mark.django_db -def test_job_template_role_user(post, organization_factory, job_template_factory): - objects = organization_factory("org", - superusers=['admin'], - users=['test']) - - jt_objects = job_template_factory("jt", - organization=objects.organization, - inventory='test_inv', - project='test_proj') - - url = reverse('api:user_roles_list', args=(objects.users.test.pk,)) - response = post(url, dict(id=jt_objects.job_template.execute_role.pk), objects.superusers.admin) - assert response.status_code == 204 - -# Test protection against limited set of validation problems - -@pytest.mark.django_db -def test_bad_data_copy_edit(admin_user, project): - """ - If a required resource (inventory here) was deleted, copying not allowed - because doing so would caues a validation error - """ - - jt_res = JobTemplate.objects.create( - job_type='run', - project=project, - inventory=None, ask_inventory_on_launch=False, # not allowed - credential=None, ask_credential_on_launch=True, - name='deploy-job-template' - ) - serializer = JobTemplateSerializer(jt_res) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = admin_user - serializer.context['request'] = request - response = serializer.to_representation(jt_res) - assert not response['summary_fields']['can_copy'] - assert response['summary_fields']['can_edit'] - -# Tests for correspondence between view info and actual access - -@pytest.mark.django_db -def test_admin_copy_edit(jt_copy_edit, admin_user): - "Absent a validation error, system admins can do everything" - - # Serializer can_copy/can_edit fields - serializer = JobTemplateSerializer(jt_copy_edit) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = admin_user - serializer.context['request'] = request - response = serializer.to_representation(jt_copy_edit) - assert response['summary_fields']['can_copy'] - assert response['summary_fields']['can_edit'] - -@pytest.mark.django_db -def test_org_admin_copy_edit(jt_copy_edit, org_admin): - "Organization admins SHOULD be able to copy a JT firmly in their org" - - # Serializer can_copy/can_edit fields - serializer = JobTemplateSerializer(jt_copy_edit) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = org_admin - serializer.context['request'] = request - response = serializer.to_representation(jt_copy_edit) - assert response['summary_fields']['can_copy'] - assert response['summary_fields']['can_edit'] - -@pytest.mark.django_db -def test_org_admin_foreign_cred_no_copy_edit(jt_copy_edit, org_admin, machine_credential): - """ - Organization admins without access to the 3 related resources: - SHOULD NOT be able to copy JT - SHOULD NOT be able to edit that job template - """ - - # Attach credential to JT that org admin can not use - jt_copy_edit.credential = machine_credential - jt_copy_edit.save() - - # Serializer can_copy/can_edit fields - serializer = JobTemplateSerializer(jt_copy_edit) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = org_admin - serializer.context['request'] = request - response = serializer.to_representation(jt_copy_edit) - assert not response['summary_fields']['can_copy'] - assert not response['summary_fields']['can_edit'] - -@pytest.mark.django_db -def test_jt_admin_copy_edit(jt_copy_edit, rando): - "JT admins wihout access to associated resources SHOULD NOT be able to copy" - - # random user given JT admin access only - jt_copy_edit.admin_role.members.add(rando) - jt_copy_edit.save() - - # Serializer can_copy/can_edit fields - serializer = JobTemplateSerializer(jt_copy_edit) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = rando - serializer.context['request'] = request - response = serializer.to_representation(jt_copy_edit) - assert not response['summary_fields']['can_copy'] - assert not response['summary_fields']['can_edit'] - -@pytest.mark.django_db -def test_proj_jt_admin_copy_edit(jt_copy_edit, rando): - "JT admins with access to associated resources SHOULD be able to copy" - - # random user given JT and project admin abilities - jt_copy_edit.admin_role.members.add(rando) - jt_copy_edit.save() - jt_copy_edit.project.admin_role.members.add(rando) - jt_copy_edit.project.save() - - # Serializer can_copy/can_edit fields - serializer = JobTemplateSerializer(jt_copy_edit) - request = RequestFactory().get('/api/v1/job_templates/12/') - request.user = rando - serializer.context['request'] = request - response = serializer.to_representation(jt_copy_edit) - assert response['summary_fields']['can_copy'] - assert response['summary_fields']['can_edit'] - -# Functional tests - create new JT with all returned fields, as the UI does - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -def test_org_admin_copy_edit_functional(jt_copy_edit, org_admin, get, post): - get_response = get(reverse('api:job_template_detail', args=[jt_copy_edit.pk]), user=org_admin) - assert get_response.status_code == 200 - assert get_response.data['summary_fields']['can_copy'] - - post_data = get_response.data - post_data['name'] = '%s @ 12:19:47 pm' % post_data['name'] - post_response = post(reverse('api:job_template_list', args=[]), user=org_admin, data=post_data) - assert post_response.status_code == 201 - assert post_response.data['name'] == 'copy-edit-job-template @ 12:19:47 pm' - -@pytest.mark.django_db -@mock.patch.object(ProjectOptions, "playbooks", project_playbooks) -def test_jt_admin_copy_edit_functional(jt_copy_edit, rando, get, post): - - # Grant random user JT admin access only - jt_copy_edit.admin_role.members.add(rando) - jt_copy_edit.save() - - get_response = get(reverse('api:job_template_detail', args=[jt_copy_edit.pk]), user=rando) - assert get_response.status_code == 200 - assert not get_response.data['summary_fields']['can_copy'] - - post_data = get_response.data - post_data['name'] = '%s @ 12:19:47 pm' % post_data['name'] - post_response = post(reverse('api:job_template_list', args=[]), user=rando, data=post_data) - assert post_response.status_code == 403 - -@pytest.mark.django_db -def test_scan_jt_no_inventory(job_template_factory): - # A user should be able to create a scan job without a project, but an inventory is required - objects = job_template_factory('jt', - credential='c', - job_type="scan", - project='p', - inventory='i', - organization='o') - serializer = JobTemplateSerializer(data={"name": "Test", "job_type": "scan", - "project": None, "inventory": objects.inventory.pk}) - assert serializer.is_valid() - serializer = JobTemplateSerializer(data={"name": "Test", "job_type": "scan", - "project": None, "inventory": None}) - assert not serializer.is_valid() - assert "inventory" in serializer.errors - serializer = JobTemplateSerializer(data={"name": "Test", "job_type": "scan", - "project": None, "inventory": None, - "ask_inventory_on_launch": True}) - assert not serializer.is_valid() - assert "inventory" in serializer.errors - - # A user shouldn't be able to launch a scan job template which is missing an inventory - obj_jt = objects.job_template - obj_jt.inventory = None - serializer = JobLaunchSerializer(instance=obj_jt, - context={'obj': obj_jt, - "data": {}}, - data={}) - assert not serializer.is_valid() - assert 'inventory' in serializer.errors - -@pytest.mark.django_db -def test_scan_jt_surveys(inventory): - serializer = JobTemplateSerializer(data={"name": "Test", "job_type": "scan", - "project": None, "inventory": inventory.pk, - "survey_enabled": True}) - assert not serializer.is_valid() - assert "survey_enabled" in serializer.errors - -@pytest.mark.django_db -def test_jt_without_project(inventory): - data = dict(name="Test", job_type="run", - inventory=inventory.pk, project=None) - serializer = JobTemplateSerializer(data=data) - assert not serializer.is_valid() - assert "project" in serializer.errors - data["job_type"] = "check" - serializer = JobTemplateSerializer(data=data) - assert not serializer.is_valid() - assert "project" in serializer.errors - data["job_type"] = "scan" - serializer = JobTemplateSerializer(data=data) - assert serializer.is_valid() diff --git a/awx/main/tests/functional/api/test_survey_spec.py b/awx/main/tests/functional/api/test_survey_spec.py deleted file mode 100644 index dc7071fc11..0000000000 --- a/awx/main/tests/functional/api/test_survey_spec.py +++ /dev/null @@ -1,200 +0,0 @@ -import mock -import pytest -import json - -from django.core.urlresolvers import reverse - -from awx.main.models.jobs import JobTemplate, Job -from awx.main.models.activity_stream import ActivityStream -from awx.api.license import LicenseForbids -from awx.main.access import JobTemplateAccess - - -def mock_no_surveys(self, add_host=False, feature=None, check_expiration=True): - if feature == 'surveys': - raise LicenseForbids("Feature %s is not enabled in the active license." % feature) - else: - pass - -@pytest.fixture -def job_template_with_survey(job_template_factory): - objects = job_template_factory('jt', project='prj', survey='submitted_email') - return objects.job_template - -# Survey license-based denial tests -@mock.patch('awx.api.views.feature_enabled', lambda feature: False) -@pytest.mark.django_db -@pytest.mark.survey -def test_survey_spec_view_denied(job_template_with_survey, get, admin_user): - # TODO: Test non-enterprise license - response = get(reverse('api:job_template_survey_spec', - args=(job_template_with_survey.id,)), admin_user, expect=402) - assert response.data['detail'] == 'Your license does not allow adding surveys.' - -@mock.patch('awx.main.access.BaseAccess.check_license', mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_deny_enabling_survey(deploy_jobtemplate, patch, admin_user): - response = patch(url=deploy_jobtemplate.get_absolute_url(), - data=dict(survey_enabled=True), user=admin_user, expect=402) - assert response.data['detail'] == 'Feature surveys is not enabled in the active license.' - -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_job_start_blocked_without_survey_license(job_template_with_survey, admin_user): - """Check that user can't start a job with surveys without a survey license.""" - access = JobTemplateAccess(admin_user) - with pytest.raises(LicenseForbids): - access.can_start(job_template_with_survey) - -@mock.patch('awx.main.access.BaseAccess.check_license', mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_deny_creating_with_survey(project, post, admin_user): - response = post( - url=reverse('api:job_template_list'), - data=dict( - name = 'JT with survey', - job_type = 'run', - project = project.pk, - playbook = 'helloworld.yml', - ask_credential_on_launch = True, - ask_inventory_on_launch = True, - survey_enabled = True), - user=admin_user, expect=402) - assert response.data['detail'] == 'Feature surveys is not enabled in the active license.' - -# Test normal operations with survey license work -@mock.patch('awx.api.views.feature_enabled', lambda feature: True) -@pytest.mark.django_db -@pytest.mark.survey -def test_survey_spec_view_allowed(deploy_jobtemplate, get, admin_user): - get(reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)), - admin_user, expect=200) - -@mock.patch('awx.api.views.feature_enabled', lambda feature: True) -@pytest.mark.django_db -@pytest.mark.survey -def test_survey_spec_sucessful_creation(survey_spec_factory, job_template, post, admin_user): - survey_input_data = survey_spec_factory('new_question') - post(url=reverse('api:job_template_survey_spec', args=(job_template.id,)), - data=survey_input_data, user=admin_user, expect=200) - updated_jt = JobTemplate.objects.get(pk=job_template.pk) - assert updated_jt.survey_spec == survey_input_data - -# Tests related to survey content validation -@mock.patch('awx.api.views.feature_enabled', lambda feature: True) -@pytest.mark.django_db -@pytest.mark.survey -def test_survey_spec_non_dict_error(deploy_jobtemplate, post, admin_user): - """When a question doesn't follow the standard format, verify error thrown.""" - response = post( - url=reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)), - data={"description": "Email of the submitter", - "spec": ["What is your email?"], "name": "Email survey"}, - user=admin_user, expect=400) - assert response.data['error'] == "Survey question 0 is not a json object." - -@mock.patch('awx.api.views.feature_enabled', lambda feature: True) -@pytest.mark.django_db -@pytest.mark.survey -def test_survey_spec_dual_names_error(survey_spec_factory, deploy_jobtemplate, post, user): - response = post( - url=reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)), - data=survey_spec_factory(['submitter_email', 'submitter_email']), - user=user('admin', True), expect=400) - assert response.data['error'] == "'variable' 'submitter_email' duplicated in survey question 1." - -# Test actions that should be allowed with non-survey license -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_disable_survey_access_without_license(job_template_with_survey, admin_user): - """Assure that user can disable a JT survey after downgrading license.""" - access = JobTemplateAccess(admin_user) - assert access.can_change(job_template_with_survey, dict(survey_enabled=False)) - -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_delete_survey_access_without_license(job_template_with_survey, admin_user): - """Assure that access.py allows deleting surveys after downgrading license.""" - access = JobTemplateAccess(admin_user) - assert access.can_change(job_template_with_survey, dict(survey_spec=None)) - assert access.can_change(job_template_with_survey, dict(survey_spec={})) - -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_job_start_allowed_with_survey_spec(job_template_factory, admin_user): - """After user downgrades survey license and disables survey on the JT, - check that jobs still launch even if the survey_spec data persists.""" - objects = job_template_factory('jt', project='prj', survey='submitter_email') - obj = objects.job_template - obj.survey_enabled = False - obj.save() - access = JobTemplateAccess(admin_user) - assert access.can_start(job_template_with_survey, {}) - -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_job_template_delete_access_with_survey(job_template_with_survey, admin_user): - """The survey_spec view relies on JT `can_delete` to determine permission - to delete the survey. This checks that system admins can delete the survey on a JT.""" - access = JobTemplateAccess(admin_user) - assert access.can_delete(job_template_with_survey) - -@mock.patch('awx.api.views.feature_enabled', lambda feature: False) -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@pytest.mark.django_db -@pytest.mark.survey -def test_delete_survey_spec_without_license(job_template_with_survey, delete, admin_user): - """Functional delete test through the survey_spec view.""" - delete(reverse('api:job_template_survey_spec', args=[job_template_with_survey.pk]), - admin_user, expect=200) - new_jt = JobTemplate.objects.get(pk=job_template_with_survey.pk) - assert new_jt.survey_spec == {} - -@mock.patch('awx.main.access.BaseAccess.check_license', lambda self, **kwargs: True) -@mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', - lambda self, extra_vars: mock.MagicMock(spec=Job, id=968)) -@mock.patch('awx.api.serializers.JobSerializer.to_representation', lambda self, obj: {}) -@pytest.mark.django_db -@pytest.mark.survey -def test_launch_survey_enabled_but_no_survey_spec(job_template_factory, post, admin_user): - """False-ish values for survey_spec are interpreted as a survey with 0 questions.""" - objects = job_template_factory('jt', organization='org1', project='prj', - inventory='inv', credential='cred') - obj = objects.job_template - obj.survey_enabled = True - obj.save() - response = post(reverse('api:job_template_launch', args=[obj.pk]), - dict(extra_vars=dict(survey_var=7)), admin_user, expect=201) - assert 'survey_var' in response.data['ignored_fields']['extra_vars'] - -@mock.patch('awx.main.access.BaseAccess.check_license', new=mock_no_surveys) -@mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.create_unified_job', - lambda self: mock.MagicMock(spec=Job, id=968)) -@mock.patch('awx.api.serializers.JobSerializer.to_representation', lambda self, obj: {}) -@pytest.mark.django_db -@pytest.mark.survey -def test_launch_with_non_empty_survey_spec_no_license(job_template_factory, post, admin_user): - """Assure jobs can still be launched from JTs with a survey_spec - when the survey is diabled.""" - objects = job_template_factory('jt', organization='org1', project='prj', - inventory='inv', credential='cred', - survey='survey_var') - obj = objects.job_template - obj.survey_enabled = False - obj.save() - post(reverse('api:job_template_launch', args=[obj.pk]), {}, admin_user, expect=201) - -@pytest.mark.django_db -@pytest.mark.survey -def test_redact_survey_passwords_in_activity_stream(job_with_secret_key): - AS_record = ActivityStream.objects.filter(object1='job').all()[0] - changes_dict = json.loads(AS_record.changes) - extra_vars = json.loads(changes_dict['extra_vars']) - assert extra_vars['secret_key'] == '$encrypted$' diff --git a/awx/main/tests/functional/api/test_survey_spec_view.py b/awx/main/tests/functional/api/test_survey_spec_view.py new file mode 100644 index 0000000000..b45c88f495 --- /dev/null +++ b/awx/main/tests/functional/api/test_survey_spec_view.py @@ -0,0 +1,135 @@ +import mock +import pytest + +from django.core.urlresolvers import reverse +from awx.main.models.jobs import JobTemplate +from awx.api.license import LicenseForbids + +def mock_feature_enabled(feature, bypass_database=None): + return True + +def mock_feature_disabled(feature, bypass_database=None): + return False + +def mock_check_license(self, add_host=False, feature=None, check_expiration=True): + raise LicenseForbids("Feature %s is not enabled in the active license." % feature) + +@pytest.fixture +def survey_jobtemplate(project, inventory, credential): + return JobTemplate.objects.create( + job_type='run', + project=project, + inventory=inventory, + credential=credential, + name='deploy-job-template' + ) + +@mock.patch('awx.api.views.feature_enabled', new=mock_feature_disabled) +@pytest.mark.django_db +@pytest.mark.survey +def test_survey_spec_view_denied(deploy_jobtemplate, get, user): + # TODO: Test non-enterprise license + spec_url = reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)) + response = get(spec_url, user('admin', True)) + + assert response.status_code == 402 + assert response.data['detail'] == 'Your license does not allow adding surveys.' + +@mock.patch('awx.main.access.BaseAccess.check_license', mock_check_license) +@pytest.mark.django_db +@pytest.mark.survey +def test_deny_enabling_survey(deploy_jobtemplate, patch, user): + JT_url = reverse('api:job_template_detail', args=(deploy_jobtemplate.id,)) + response = patch(url=JT_url, data=dict(survey_enabled=True), user=user('admin', True)) + assert response.status_code == 402 + assert response.data['detail'] == 'Feature surveys is not enabled in the active license.' + +@mock.patch('awx.main.access.BaseAccess.check_license', mock_check_license) +@pytest.mark.django_db +@pytest.mark.survey +def test_deny_creating_with_survey(machine_credential, project, inventory, post, user): + JT_url = reverse('api:job_template_list') + JT_data = dict( + name = 'JT with survey', + job_type = 'run', + inventory = inventory.pk, + project = project.pk, + playbook = 'hiworld.yml', + credential = machine_credential.pk, + survey_enabled = True, + ) + response = post(url=JT_url, data=JT_data, user=user('admin', True)) + + assert response.status_code == 402 + assert response.data['detail'] == 'Feature surveys is not enabled in the active license.' + +@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled) +@pytest.mark.django_db +@pytest.mark.survey +def test_survey_spec_view_allowed(deploy_jobtemplate, get, user): + spec_url = reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)) + response = get(spec_url, user('admin', True)) + + assert response.status_code == 200 + +@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled) +@pytest.mark.django_db +@pytest.mark.survey +def test_survey_spec_sucessful_creation(deploy_jobtemplate, post, user): + spec_url = reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)) + response = post( + url=spec_url, + data={ + "description": "Email of the submitter", + "spec": [{ + "variable": "submitter_email", + "question_name": "Enter your email", + "type": "text", + "required": False + }], + "name": "Email survey" + }, + user=user('admin', True)) + + assert response.status_code == 200 + +@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled) +@pytest.mark.django_db +@pytest.mark.survey +def test_survey_spec_non_dict_error(deploy_jobtemplate, post, user): + spec_url = reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)) + response = post( + url=spec_url, + data={"description": "Email of the submitter", + "spec": ["What is your email?"], "name": "Email survey"}, + user=user('admin', True)) + + assert response.status_code == 400 + assert response.data['error'] == "Survey question 0 is not a json object." + +@mock.patch('awx.api.views.feature_enabled', new=mock_feature_enabled) +@pytest.mark.django_db +@pytest.mark.survey +def test_survey_spec_dual_names_error(deploy_jobtemplate, post, user): + spec_url = reverse('api:job_template_survey_spec', args=(deploy_jobtemplate.id,)) + response = post( + url=spec_url, + data={ + "description": "Email of the submitter", + "spec": [{ + "variable": "submitter_email", + "question_name": "Enter your email", + "type": "text", + "required": False + }, { + "variable": "submitter_email", + "question_name": "Same variable as last question", + "type": "integer", + "required": False + }], + "name": "Email survey" + }, + user=user('admin', True)) + + assert response.status_code == 400 + assert response.data['error'] == "'variable' 'submitter_email' duplicated in survey question 1." diff --git a/awx/main/tests/functional/conftest.py b/awx/main/tests/functional/conftest.py index 3aab7a2537..59d34a2832 100644 --- a/awx/main/tests/functional/conftest.py +++ b/awx/main/tests/functional/conftest.py @@ -147,6 +147,18 @@ def instance(settings): def organization(instance): return Organization.objects.create(name="test-org", description="test-org-desc") +@pytest.fixture +def organization_factory(instance): + def factory(name): + try: + org = Organization.objects.get(name=name) + except Organization.DoesNotExist: + org = Organization.objects.create(name=name, + description="description for " + name, + ) + return org + return factory + @pytest.fixture def credential(): return Credential.objects.create(kind='aws', name='test-cred') @@ -185,11 +197,6 @@ def notification_template(organization): notification_type="webhook", notification_configuration=dict(url="http://localhost", headers={"Test": "Header"})) - -@pytest.fixture -def job_with_secret_key(job_with_secret_key_factory): - return job_with_secret_key_factory(persisted=True) - @pytest.fixture def admin(user): return user('admin', True) @@ -214,13 +221,6 @@ def org_admin(user, organization): organization.member_role.members.add(ret) return ret -@pytest.fixture -def org_auditor(user, organization): - ret = user('org-auditor', False) - organization.auditor_role.members.add(ret) - organization.member_role.members.add(ret) - return ret - @pytest.fixture def org_member(user, organization): ret = user('org-member', False) @@ -282,9 +282,24 @@ def permissions(): 'update':False, 'delete':False, 'scm_update':False, 'execute':False, 'use':True,}, } +@pytest.fixture +def notification_template_factory(organization): + def n(name="test-notification_template"): + try: + notification_template = NotificationTemplate.objects.get(name=name) + except NotificationTemplate.DoesNotExist: + notification_template = NotificationTemplate(name=name, + organization=organization, + notification_type="webhook", + notification_configuration=dict(url="http://localhost", + headers={"Test": "Header"})) + notification_template.save() + return notification_template + return n + @pytest.fixture def post(): - def rf(url, data, user=None, middleware=None, expect=None, **kwargs): + def rf(url, data, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -296,16 +311,12 @@ def post(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def get(): - def rf(url, user=None, middleware=None, expect=None, **kwargs): + def rf(url, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -317,16 +328,12 @@ def get(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def put(): - def rf(url, data, user=None, middleware=None, expect=None, **kwargs): + def rf(url, data, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -338,16 +345,12 @@ def put(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def patch(): - def rf(url, data, user=None, middleware=None, expect=None, **kwargs): + def rf(url, data, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -359,16 +362,12 @@ def patch(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def delete(): - def rf(url, user=None, middleware=None, expect=None, **kwargs): + def rf(url, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -380,16 +379,12 @@ def delete(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def head(): - def rf(url, user=None, middleware=None, expect=None, **kwargs): + def rf(url, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -401,16 +396,12 @@ def head(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @pytest.fixture def options(): - def rf(url, data, user=None, middleware=None, expect=None, **kwargs): + def rf(url, data, user=None, middleware=None, **kwargs): view, view_args, view_kwargs = resolve(urlparse(url)[2]) if 'format' not in kwargs: kwargs['format'] = 'json' @@ -422,10 +413,6 @@ def options(): response = view(request, *view_args, **view_kwargs) if middleware: middleware.process_response(request, response) - if expect: - if response.status_code != expect: - print(response.data) - assert response.status_code == expect return response return rf @@ -487,4 +474,3 @@ def job_template_labels(organization, job_template): job_template.labels.create(name="label-2", organization=organization) return job_template - diff --git a/awx/main/tests/functional/test_fixture_factories.py b/awx/main/tests/functional/test_fixture_factories.py deleted file mode 100644 index bb6dd6cd63..0000000000 --- a/awx/main/tests/functional/test_fixture_factories.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest - -from awx.main.tests.factories import NotUnique - -def test_roles_exc_not_persisted(organization_factory): - with pytest.raises(RuntimeError) as exc: - organization_factory('test-org', roles=['test-org.admin_role:user1'], persisted=False) - assert 'persisted=False' in str(exc.value) - - -@pytest.mark.django_db -def test_roles_exc_bad_object(organization_factory): - with pytest.raises(KeyError): - organization_factory('test-org', roles=['test-project.admin_role:user']) - - -@pytest.mark.django_db -def test_roles_exc_not_unique(organization_factory): - with pytest.raises(NotUnique) as exc: - organization_factory('test-org', projects=['foo'], teams=['foo'], roles=['foo.admin_role:user']) - assert 'not a unique key' in str(exc.value) - - -@pytest.mark.django_db -def test_roles_exc_not_assignment(organization_factory): - with pytest.raises(RuntimeError) as exc: - organization_factory('test-org', projects=['foo'], roles=['foo.admin_role']) - assert 'provide an assignment' in str(exc.value) - - -@pytest.mark.django_db -def test_roles_exc_not_found(organization_factory): - with pytest.raises(RuntimeError) as exc: - organization_factory('test-org', users=['user'], projects=['foo'], roles=['foo.admin_role:user.bad_role']) - assert 'unable to find' in str(exc.value) - - -@pytest.mark.django_db -def test_roles_exc_not_user(organization_factory): - with pytest.raises(RuntimeError) as exc: - organization_factory('test-org', projects=['foo'], roles=['foo.admin_role:foo']) - assert 'unable to add non-user' in str(exc.value) - - -@pytest.mark.django_db -def test_org_factory_roles(organization_factory): - objects = organization_factory('org_roles_test', - teams=['team1', 'team2'], - users=['team1:foo', 'bar'], - projects=['baz', 'bang'], - roles=['team2.member_role:foo', - 'team1.admin_role:bar', - 'team1.admin_role:team2.admin_role', - 'baz.admin_role:foo']) - - assert objects.users.bar in objects.teams.team2.admin_role - assert objects.users.foo in objects.projects.baz.admin_role - assert objects.users.foo in objects.teams.team1.member_role - assert objects.teams.team2.admin_role in objects.teams.team1.admin_role.children.all() - - -@pytest.mark.django_db -def test_org_factory(organization_factory): - objects = organization_factory('organization1', - teams=['team1'], - superusers=['superuser'], - users=['admin', 'alice', 'team1:bob'], - projects=['proj1']) - assert hasattr(objects.users, 'admin') - assert hasattr(objects.users, 'alice') - assert hasattr(objects.superusers, 'superuser') - assert objects.users.bob in objects.teams.team1.member_role.members.all() - assert objects.projects.proj1.organization == objects.organization - - -@pytest.mark.django_db -def test_job_template_factory(job_template_factory): - jt_objects = job_template_factory('testJT', organization='org1', - project='proj1', inventory='inventory1', - credential='cred1', survey='test-survey', - jobs=[1]) - assert jt_objects.job_template.name == 'testJT' - assert jt_objects.project.name == 'proj1' - assert jt_objects.inventory.name == 'inventory1' - assert jt_objects.credential.name == 'cred1' - assert jt_objects.inventory.organization.name == 'org1' - assert jt_objects.job_template.survey_enabled is True - assert jt_objects.job_template.survey_spec is not None - assert 'test-survey' in jt_objects.jobs[1].extra_vars - -def test_survey_spec_generator_simple(survey_spec_factory): - survey_spec = survey_spec_factory('survey_variable') - assert 'name' in survey_spec - assert 'spec' in survey_spec - assert type(survey_spec['spec']) is list - assert type(survey_spec['spec'][0]) is dict - assert survey_spec['spec'][0]['type'] == 'integer' - -def test_survey_spec_generator_mixed(survey_spec_factory): - survey_spec = survey_spec_factory( - [{'variable': 'question1', 'type': 'integer', 'max': 87}, - {'variable': 'question2', 'type': 'str'}, - 'some_variable']) - assert len(survey_spec['spec']) == 3 - assert [spec_item['type'] for spec_item in survey_spec['spec']] == ['integer', 'str', 'integer'] - assert survey_spec['spec'][0]['max'] == 87 diff --git a/awx/main/tests/functional/test_jobs.py b/awx/main/tests/functional/test_jobs.py index e65ef9edb7..aefb4e8bb7 100644 --- a/awx/main/tests/functional/test_jobs.py +++ b/awx/main/tests/functional/test_jobs.py @@ -22,16 +22,3 @@ def test_job_blocking(get, post, job_template, inventory, inventory_factory): assert j_callback_1.is_blocked_by(j_callback_2) j_callback_2.limit = 'b' assert not j_callback_1.is_blocked_by(j_callback_2) - -@pytest.mark.django_db -def test_job_blocking_allow_simul(get, post, job_template, inventory): - job_template.allow_simultaneous = True - j1 = Job.objects.create(job_template=job_template, - inventory=inventory) - j2 = Job.objects.create(job_template=job_template, - inventory=inventory) - assert not j1.is_blocked_by(j2) - assert not j2.is_blocked_by(j1) - job_template.allow_simultaneous = False - assert j1.is_blocked_by(j2) - assert j2.is_blocked_by(j1) diff --git a/awx/main/tests/functional/test_projects.py b/awx/main/tests/functional/test_projects.py index 4c32d1dd69..d8bcd5d151 100644 --- a/awx/main/tests/functional/test_projects.py +++ b/awx/main/tests/functional/test_projects.py @@ -1,6 +1,7 @@ import mock # noqa import pytest +from django.db import transaction from django.core.urlresolvers import reverse from awx.main.models import Project @@ -8,55 +9,62 @@ from awx.main.models import Project # # Project listing and visibility tests # -@pytest.fixture -def team_project_list(organization_factory): - objects = organization_factory('org-test', - superusers=['admin'], - users=['team1:alice', 'team2:bob'], - teams=['team1', 'team2'], - projects=['pteam1', 'pteam2', 'pshared'], - roles=['team1.member_role:pteam1.admin_role', - 'team2.member_role:pteam2.admin_role', - 'team1.member_role:pshared.admin_role', - 'team2.member_role:pshared.admin_role']) - return objects - @pytest.mark.django_db -def test_user_project_list(get, organization_factory): +def test_user_project_list(get, project_factory, organization, admin, alice, bob): 'List of projects a user has access to, filtered by projects you can also see' - objects = organization_factory('org1', - projects=['alice project', 'bob project', 'shared project'], - superusers=['admin'], - users=['alice', 'bob'], - roles=['alice project.admin_role:alice', - 'bob project.admin_role:bob', - 'shared project.admin_role:bob', - 'shared project.admin_role:alice']) + organization.member_role.members.add(alice, bob) - assert get(reverse('api:user_projects_list', args=(objects.superusers.admin.pk,)), objects.superusers.admin).data['count'] == 3 + alice_project = project_factory('alice project') + alice_project.admin_role.members.add(alice) + + bob_project = project_factory('bob project') + bob_project.admin_role.members.add(bob) + + shared_project = project_factory('shared project') + shared_project.admin_role.members.add(alice) + shared_project.admin_role.members.add(bob) + + # admins can see all projects + assert get(reverse('api:user_projects_list', args=(admin.pk,)), admin).data['count'] == 3 # admins can see everyones projects - assert get(reverse('api:user_projects_list', args=(objects.users.alice.pk,)), objects.superusers.admin).data['count'] == 2 - assert get(reverse('api:user_projects_list', args=(objects.users.bob.pk,)), objects.superusers.admin).data['count'] == 2 + assert get(reverse('api:user_projects_list', args=(alice.pk,)), admin).data['count'] == 2 + assert get(reverse('api:user_projects_list', args=(bob.pk,)), admin).data['count'] == 2 # users can see their own projects - assert get(reverse('api:user_projects_list', args=(objects.users.alice.pk,)), objects.users.alice).data['count'] == 2 + assert get(reverse('api:user_projects_list', args=(alice.pk,)), alice).data['count'] == 2 # alice should only be able to see the shared project when looking at bobs projects - assert get(reverse('api:user_projects_list', args=(objects.users.bob.pk,)), objects.users.alice).data['count'] == 1 + assert get(reverse('api:user_projects_list', args=(bob.pk,)), alice).data['count'] == 1 # alice should see all projects they can see when viewing an admin - assert get(reverse('api:user_projects_list', args=(objects.superusers.admin.pk,)), objects.users.alice).data['count'] == 2 + assert get(reverse('api:user_projects_list', args=(admin.pk,)), alice).data['count'] == 2 +def setup_test_team_project_list(project_factory, team_factory, admin, alice, bob): + team1 = team_factory('team1') + team2 = team_factory('team2') + + team1_project = project_factory('team1 project') + team1_project.admin_role.parents.add(team1.member_role) + + team2_project = project_factory('team2 project') + team2_project.admin_role.parents.add(team2.member_role) + + shared_project = project_factory('shared project') + shared_project.admin_role.parents.add(team1.member_role) + shared_project.admin_role.parents.add(team2.member_role) + + team1.member_role.members.add(alice) + team2.member_role.members.add(bob) + return team1, team2 + @pytest.mark.django_db -def test_team_project_list(get, team_project_list): - objects = team_project_list - - team1, team2 = objects.teams.team1, objects.teams.team2 - alice, bob, admin = objects.users.alice, objects.users.bob, objects.superusers.admin +def test_team_project_list(get, project_factory, team_factory, admin, alice, bob): + 'List of projects a team has access to, filtered by projects you can also see' + team1, team2 = setup_test_team_project_list(project_factory, team_factory, admin, alice, bob) # admins can see all projects on a team assert get(reverse('api:team_projects_list', args=(team1.pk,)), admin).data['count'] == 2 @@ -70,6 +78,12 @@ def test_team_project_list(get, team_project_list): assert get(reverse('api:team_projects_list', args=(team2.pk,)), alice).data['count'] == 1 team2.read_role.members.remove(alice) + # Test user endpoints first, very similar tests to test_user_project_list + # but permissions are being derived from team membership instead. + with transaction.atomic(): + res = get(reverse('api:user_projects_list', args=(bob.pk,)), alice) + assert res.status_code == 403 + # admins can see all projects assert get(reverse('api:user_projects_list', args=(admin.pk,)), admin).data['count'] == 3 @@ -84,11 +98,17 @@ def test_team_project_list(get, team_project_list): assert get(reverse('api:user_projects_list', args=(admin.pk,)), alice).data['count'] == 2 @pytest.mark.django_db -def test_team_project_list_fail1(get, team_project_list): - objects = team_project_list - res = get(reverse('api:team_projects_list', args=(objects.teams.team2.pk,)), objects.users.alice) +def test_team_project_list_fail1(get, project_factory, team_factory, admin, alice, bob): + # alice should not be able to see team2 projects because she doesn't have access to team2 + team1, team2 = setup_test_team_project_list(project_factory, team_factory, admin, alice, bob) + res = get(reverse('api:team_projects_list', args=(team2.pk,)), alice) assert res.status_code == 403 +@pytest.mark.django_db +def test_team_project_list_fail2(get, project_factory, team_factory, admin, alice, bob): + team1, team2 = setup_test_team_project_list(project_factory, team_factory, admin, alice, bob) + # alice should not be able to see bob + @pytest.mark.parametrize("u,expected_status_code", [ ('rando', 403), ('org_member', 403), diff --git a/awx/main/tests/functional/test_rbac_api.py b/awx/main/tests/functional/test_rbac_api.py index b3c75a4a2d..10438504e2 100644 --- a/awx/main/tests/functional/test_rbac_api.py +++ b/awx/main/tests/functional/test_rbac_api.py @@ -406,9 +406,9 @@ def test_ensure_rbac_fields_are_present(organization, get, admin): org = response.data assert 'summary_fields' in org - assert 'object_roles' in org['summary_fields'] + assert 'roles' in org['summary_fields'] - role_pk = org['summary_fields']['object_roles']['admin_role']['id'] + role_pk = org['summary_fields']['roles']['admin_role']['id'] role_url = reverse('api:role_detail', args=(role_pk,)) org_role_response = get(role_url, admin) @@ -435,5 +435,5 @@ def test_ensure_role_summary_is_present(organization, get, user): org = response.data assert 'summary_fields' in org - assert 'object_roles' in org['summary_fields'] - assert org['summary_fields']['object_roles']['admin_role']['id'] > 0 + assert 'roles' in org['summary_fields'] + assert org['summary_fields']['roles']['admin_role']['id'] > 0 diff --git a/awx/main/tests/functional/test_rbac_credential.py b/awx/main/tests/functional/test_rbac_credential.py index a42c5b489d..75bcffecb6 100644 --- a/awx/main/tests/functional/test_rbac_credential.py +++ b/awx/main/tests/functional/test_rbac_credential.py @@ -118,9 +118,6 @@ def test_cred_job_template(user, team, deploy_jobtemplate): access = CredentialAccess(a) rbac.migrate_credential(apps, None) - - cred.refresh_from_db() - assert access.can_change(cred, {'organization': org.pk}) org.admin_role.members.remove(a) @@ -138,8 +135,6 @@ def test_cred_multi_job_template_single_org_xfail(user, deploy_jobtemplate): access = CredentialAccess(a) rbac.migrate_credential(apps, None) - cred.refresh_from_db() - assert not access.can_change(cred, {'organization': org.pk}) @pytest.mark.django_db @@ -154,8 +149,6 @@ def test_cred_multi_job_template_single_org(user, team, deploy_jobtemplate): access = CredentialAccess(a) rbac.migrate_credential(apps, None) - cred.refresh_from_db() - assert access.can_change(cred, {'organization': org.pk}) org.admin_role.members.remove(a) @@ -187,7 +180,6 @@ def test_single_cred_multi_job_template_multi_org(user, organizations, credentia for jt in jts: jt.refresh_from_db() - credential.refresh_from_db() assert jts[0].credential != jts[1].credential assert access.can_change(jts[0].credential, {'organization': org.pk}) diff --git a/awx/main/tests/functional/test_rbac_job.py b/awx/main/tests/functional/test_rbac_job.py deleted file mode 100644 index f54d661095..0000000000 --- a/awx/main/tests/functional/test_rbac_job.py +++ /dev/null @@ -1,72 +0,0 @@ -import pytest - -from awx.main.access import JobAccess -from awx.main.models import Job - - -@pytest.fixture -def normal_job(deploy_jobtemplate): - return Job.objects.create( - job_template=deploy_jobtemplate, - project=deploy_jobtemplate.project, - inventory=deploy_jobtemplate.inventory - ) - -# Read permissions testing -@pytest.mark.django_db -def test_superuser_sees_orphans(normal_job, admin_user): - normal_job.job_template = None - access = JobAccess(admin_user) - assert access.can_read(normal_job) - -@pytest.mark.django_db -def test_org_member_does_not_see_orphans(normal_job, org_member, project): - normal_job.job_template = None - # Check that privledged access to project still does not grant access - project.admin_role.members.add(org_member) - access = JobAccess(org_member) - assert not access.can_read(normal_job) - -@pytest.mark.django_db -def test_org_admin_sees_orphans(normal_job, org_admin): - normal_job.job_template = None - access = JobAccess(org_admin) - assert access.can_read(normal_job) - -@pytest.mark.django_db -def test_org_auditor_sees_orphans(normal_job, org_auditor): - normal_job.job_template = None - access = JobAccess(org_auditor) - assert access.can_read(normal_job) - -# Delete permissions testing -@pytest.mark.django_db -def test_JT_admin_delete_denied(normal_job, rando): - normal_job.job_template.admin_role.members.add(rando) - access = JobAccess(rando) - assert not access.can_delete(normal_job) - -@pytest.mark.django_db -def test_inventory_admin_delete_denied(normal_job, rando): - normal_job.job_template.inventory.admin_role.members.add(rando) - access = JobAccess(rando) - assert not access.can_delete(normal_job) - -@pytest.mark.django_db -def test_null_related_delete_denied(normal_job, rando): - normal_job.project = None - normal_job.inventory = None - access = JobAccess(rando) - assert not access.can_delete(normal_job) - -@pytest.mark.django_db -def test_inventory_org_admin_delete_allowed(normal_job, org_admin): - normal_job.project = None # do this so we test job->inventory->org->admin connection - access = JobAccess(org_admin) - assert access.can_delete(normal_job) - -@pytest.mark.django_db -def test_project_org_admin_delete_allowed(normal_job, org_admin): - normal_job.inventory = None # do this so we test job->project->org->admin connection - access = JobAccess(org_admin) - assert access.can_delete(normal_job) diff --git a/awx/main/tests/functional/test_rbac_job_templates.py b/awx/main/tests/functional/test_rbac_job_templates.py index 3c7a7b32fc..f775053ccc 100644 --- a/awx/main/tests/functional/test_rbac_job_templates.py +++ b/awx/main/tests/functional/test_rbac_job_templates.py @@ -7,11 +7,8 @@ from awx.main.access import ( ) from awx.main.migrations import _rbac as rbac from awx.main.models import Permission -from awx.main.models.jobs import JobTemplate from django.apps import apps -from django.core.urlresolvers import reverse - @pytest.mark.django_db def test_job_template_migration_check(credential, deploy_jobtemplate, check_jobtemplate, user): @@ -158,26 +155,3 @@ def test_job_template_access_superuser(check_license, user, deploy_jobtemplate): # THEN all access checks should pass assert access.can_read(deploy_jobtemplate) assert access.can_add({}) - -@pytest.mark.django_db -@pytest.mark.job_permissions -def test_job_template_creator_access(project, rando, post): - - project.admin_role.members.add(rando) - with mock.patch( - 'awx.main.models.projects.ProjectOptions.playbooks', - new_callable=mock.PropertyMock(return_value=['helloworld.yml'])): - response = post(reverse('api:job_template_list', args=[]), dict( - name='newly-created-jt', - job_type='run', - ask_inventory_on_launch=True, - ask_credential_on_launch=True, - project=project.pk, - playbook='helloworld.yml' - ), rando) - - assert response.status_code == 201 - jt_pk = response.data['id'] - jt_obj = JobTemplate.objects.get(pk=jt_pk) - # Creating a JT should place the creator in the admin role - assert rando in jt_obj.admin_role diff --git a/awx/main/tests/functional/test_rbac_label.py b/awx/main/tests/functional/test_rbac_label.py index e425d50908..ec3c83f314 100644 --- a/awx/main/tests/functional/test_rbac_label.py +++ b/awx/main/tests/functional/test_rbac_label.py @@ -31,22 +31,20 @@ def test_label_access_superuser(label, user): assert access.can_delete(label) @pytest.mark.django_db -def test_label_access_admin(organization_factory): +def test_label_access_admin(label, user, organization_factory): '''can_change because I am an admin of that org''' - no_members = organization_factory("no_members") - members = organization_factory("has_members", - users=['admin'], - labels=['test']) + a = user('admin', False) + org_no_members = organization_factory("no_members") + org_members = organization_factory("has_members") - label = members.labels.test - admin = members.users.admin - members.organization.admin_role.members.add(admin) + label.organization.admin_role.members.add(a) + org_members.admin_role.members.add(a) - access = LabelAccess(admin) - assert not access.can_change(label, {'organization': no_members.organization.id}) + access = LabelAccess(user('admin', False)) + assert not access.can_change(label, {'organization': org_no_members.id}) assert access.can_read(label) assert access.can_change(label, None) - assert access.can_change(label, {'organization': members.organization.id}) + assert access.can_change(label, {'organization': org_members.id}) assert access.can_delete(label) @pytest.mark.django_db diff --git a/awx/main/tests/functional/test_rbac_notifications.py b/awx/main/tests/functional/test_rbac_notifications.py index 9cabec6fbf..467ae8038a 100644 --- a/awx/main/tests/functional/test_rbac_notifications.py +++ b/awx/main/tests/functional/test_rbac_notifications.py @@ -25,44 +25,35 @@ def test_notification_template_get_queryset_orgadmin(notification_template, user assert access.get_queryset().count() == 1 @pytest.mark.django_db -def test_notification_template_access_superuser(notification_template_factory): - nf_objects = notification_template_factory('test-orphaned', organization='test', superusers=['admin']) - admin = nf_objects.superusers.admin - nf = nf_objects.notification_template - - access = NotificationTemplateAccess(admin) - assert access.can_read(nf) - assert access.can_change(nf, None) - assert access.can_delete(nf) - +def test_notification_template_access_superuser(notification_template, user, notification_template_factory): + access = NotificationTemplateAccess(user('admin', True)) + assert access.can_read(notification_template) + assert access.can_change(notification_template, None) + assert access.can_delete(notification_template) + nf = notification_template_factory("test-orphaned") nf.organization = None nf.save() - assert access.can_read(nf) assert access.can_change(nf, None) assert access.can_delete(nf) @pytest.mark.django_db -def test_notification_template_access_admin(organization_factory, notification_template_factory): - other_objects = organization_factory('other') - present_objects = organization_factory('present', - users=['admin'], - notification_templates=['test-notification'], - roles=['present.admin_role:admin']) +def test_notification_template_access_admin(notification_template, user, organization_factory, notification_template_factory): + adm = user('admin', False) + other_org = organization_factory('other') + present_org = organization_factory('present') + notification_template.organization.admin_role.members.add(adm) + present_org.admin_role.members.add(adm) - notification_template = present_objects.notification_templates.test_notification - other_org = other_objects.organization - present_org = present_objects.organization - admin = present_objects.users.admin - - access = NotificationTemplateAccess(admin) + access = NotificationTemplateAccess(user('admin', False)) assert not access.can_change(notification_template, {'organization': other_org.id}) assert access.can_read(notification_template) assert access.can_change(notification_template, None) assert access.can_change(notification_template, {'organization': present_org.id}) assert access.can_delete(notification_template) - nf = notification_template_factory("test-orphaned") + nf.organization = None + nf.save() assert not access.can_read(nf) assert not access.can_change(nf, None) assert not access.can_delete(nf) diff --git a/awx/main/tests/old/ad_hoc.py b/awx/main/tests/old/ad_hoc.py index 2c81ec71a0..b05dc6df89 100644 --- a/awx/main/tests/old/ad_hoc.py +++ b/awx/main/tests/old/ad_hoc.py @@ -404,6 +404,164 @@ class AdHocCommandApiTest(BaseAdHocCommandTest): del data[k] return self.post(url, data, expect=expect) + @mock.patch('awx.main.tasks.BaseTask.run_pexpect', side_effect=run_pexpect_mock) + def test_ad_hoc_command_list(self, ignore): + url = reverse('api:ad_hoc_command_list') + + # Retrieve the empty list of ad hoc commands. + qs = AdHocCommand.objects.none() + self.check_get_list(url, 'admin', qs) + self.check_get_list(url, 'normal', qs) + self.check_get_list(url, 'other', qs) + self.check_get_list(url, 'nobody', qs) + self.check_get_list(url, None, qs, expect=401) + + # Start a new ad hoc command. Only admin and normal user (org admin) + # can run commands by default. + with self.current_user('admin'): + response = self.run_test_ad_hoc_command() + self.assertEqual(response['job_type'], 'run') + self.assertEqual(response['inventory'], self.inventory.pk) + self.assertEqual(response['credential'], self.credential.pk) + self.assertEqual(response['module_name'], 'command') + self.assertEqual(response['module_args'], 'uptime') + self.assertEqual(response['limit'], '') + self.assertEqual(response['forks'], 0) + self.assertEqual(response['verbosity'], 0) + self.assertEqual(response['become_enabled'], False) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user('normal'): + self.run_test_ad_hoc_command() + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user('other'): + self.run_test_ad_hoc_command(expect=403) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user('nobody'): + self.run_test_ad_hoc_command(expect=403) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user(None): + self.run_test_ad_hoc_command(expect=401) + self.put(url, {}, expect=401) + self.patch(url, {}, expect=401) + self.delete(url, expect=401) + + # Retrieve the list of ad hoc commands (only admin/normal can see by default). + qs = AdHocCommand.objects.all() + self.assertEqual(qs.count(), 2) + self.check_get_list(url, 'admin', qs) + self.check_get_list(url, 'normal', qs) + qs = AdHocCommand.objects.none() + self.check_get_list(url, 'other', qs) + self.check_get_list(url, 'nobody', qs) + self.check_get_list(url, None, qs, expect=401) + + # Explicitly give other user updater permission on the inventory (still + # not allowed to run ad hoc commands). + user_roles_list_url = reverse('api:user_roles_list', args=(self.other_django_user.pk,)) + with self.current_user('admin'): + response = self.post(user_roles_list_url, {"id": self.inventory.update_role.id}, expect=204) + with self.current_user('other'): + self.run_test_ad_hoc_command(expect=403) + self.check_get_list(url, 'other', qs) + + # Add executor role permissions to other. Fails + # when other user can't read credential. + with self.current_user('admin'): + response = self.post(user_roles_list_url, {"id": self.inventory.execute_role.id}, expect=204) + with self.current_user('other'): + self.run_test_ad_hoc_command(expect=403) + + # Succeeds once other user has a readable credential. Other user can + # only see his own ad hoc command (because of credential permissions). + other_cred = self.create_test_credential(user=self.other_django_user) + with self.current_user('other'): + self.run_test_ad_hoc_command(credential=other_cred.pk) + qs = AdHocCommand.objects.filter(created_by=self.other_django_user) + self.assertEqual(qs.count(), 1) + self.check_get_list(url, 'other', qs) + + # Explicitly give nobody user read permission on the inventory. + nobody_roles_list_url = reverse('api:user_roles_list', args=(self.nobody_django_user.pk,)) + with self.current_user('admin'): + response = self.post(nobody_roles_list_url, {"id": self.inventory.read_role.id}, expect=204) + with self.current_user('nobody'): + self.run_test_ad_hoc_command(credential=other_cred.pk, expect=403) + self.check_get_list(url, 'other', qs) + + # Create a cred for the nobody user, run an ad hoc command as the admin + # user with that cred. Nobody user can still not see the ad hoc command + # without the run_ad_hoc_commands permission flag. + nobody_cred = self.create_test_credential(user=self.nobody_django_user) + with self.current_user('admin'): + self.run_test_ad_hoc_command(credential=nobody_cred.pk) + qs = AdHocCommand.objects.none() + self.check_get_list(url, 'nobody', qs) + + # Give the nobody user the run_ad_hoc_commands flag, and can now see + # the one ad hoc command previously run. + with self.current_user('admin'): + response = self.post(nobody_roles_list_url, {"id": self.inventory.execute_role.id}, expect=204) + qs = AdHocCommand.objects.filter(credential_id=nobody_cred.pk) + self.assertEqual(qs.count(), 1) + self.check_get_list(url, 'nobody', qs) + + # Post without inventory (should fail). + with self.current_user('admin'): + self.run_test_ad_hoc_command(inventory=None, expect=400) + + # Post without credential (should fail). + with self.current_user('admin'): + self.run_test_ad_hoc_command(credential=None, expect=400) + + # Post with empty or unsupported module name (empty defaults to command). + with self.current_user('admin'): + response = self.run_test_ad_hoc_command(module_name=None) + self.assertEqual(response['module_name'], 'command') + with self.current_user('admin'): + response = self.run_test_ad_hoc_command(module_name='') + self.assertEqual(response['module_name'], 'command') + with self.current_user('admin'): + self.run_test_ad_hoc_command(module_name='transcombobulator', expect=400) + + # Post with empty module args for shell/command modules (should fail), + # empty args for other modules ok. + with self.current_user('admin'): + self.run_test_ad_hoc_command(module_args=None, expect=400) + with self.current_user('admin'): + self.run_test_ad_hoc_command(module_name='shell', module_args=None, expect=400) + with self.current_user('admin'): + self.run_test_ad_hoc_command(module_name='shell', module_args='', expect=400) + with self.current_user('admin'): + self.run_test_ad_hoc_command(module_name='ping', module_args=None) + + # Post with invalid values for other parameters. + with self.current_user('admin'): + self.run_test_ad_hoc_command(job_type='something', expect=400) + with self.current_user('admin'): + response = self.run_test_ad_hoc_command(job_type='check') + self.assertEqual(response['job_type'], 'check') + with self.current_user('admin'): + self.run_test_ad_hoc_command(verbosity=-1, expect=400) + with self.current_user('admin'): + self.run_test_ad_hoc_command(forks=-1, expect=400) + with self.current_user('admin'): + response = self.run_test_ad_hoc_command(become_enabled=True) + self.assertEqual(response['become_enabled'], True) + + # Try to run with expired license. + self.create_expired_license_file() + with self.current_user('admin'): + self.run_test_ad_hoc_command(expect=403) + with self.current_user('normal'): + self.run_test_ad_hoc_command(expect=403) @mock.patch('awx.main.tasks.BaseTask.run_pexpect', side_effect=run_pexpect_mock) def test_ad_hoc_command_detail(self, ignore): @@ -795,6 +953,98 @@ class AdHocCommandApiTest(BaseAdHocCommandTest): self.patch(url, {}, expect=401) self.delete(url, expect=401) + @mock.patch('awx.main.tasks.BaseTask.run_pexpect', side_effect=run_pexpect_mock) + def test_inventory_ad_hoc_commands_list(self, ignore): + with self.current_user('admin'): + response = self.run_test_ad_hoc_command() + response = self.run_test_ad_hoc_command(inventory=self.inventory2.pk) + + # Test the ad hoc commands list for an inventory. Should only return + # the ad hoc command(s) run against that inventory. Posting should + # start a new ad hoc command and always set the inventory from the URL. + url = reverse('api:inventory_ad_hoc_commands_list', args=(self.inventory.pk,)) + inventory_url = reverse('api:inventory_detail', args=(self.inventory.pk,)) + with self.current_user('admin'): + response = self.get(url, expect=200) + self.assertEqual(response['count'], 1) + response = self.run_test_ad_hoc_command(url=url, inventory=None, expect=201) + self.assertEqual(response['inventory'], self.inventory.pk) + response = self.run_test_ad_hoc_command(url=url, inventory=self.inventory2.pk, expect=201) + self.assertEqual(response['inventory'], self.inventory.pk) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + response = self.get(inventory_url, expect=200) + self.assertTrue(response['can_run_ad_hoc_commands']) + with self.current_user('normal'): + response = self.get(url, expect=200) + self.assertEqual(response['count'], 3) + response = self.run_test_ad_hoc_command(url=url, inventory=None, expect=201) + self.assertEqual(response['inventory'], self.inventory.pk) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + response = self.get(inventory_url, expect=200) + self.assertTrue(response['can_run_ad_hoc_commands']) + with self.current_user('other'): + self.get(url, expect=403) + self.post(url, {}, expect=403) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user('nobody'): + self.get(url, expect=403) + self.post(url, {}, expect=403) + self.put(url, {}, expect=405) + self.patch(url, {}, expect=405) + self.delete(url, expect=405) + with self.current_user(None): + self.get(url, expect=401) + self.post(url, {}, expect=401) + self.put(url, {}, expect=401) + self.patch(url, {}, expect=401) + self.delete(url, expect=401) + + # Create another unrelated inventory permission with run_ad_hoc_commands + # set; this tests an edge case in the RBAC query where we'll return + # can_run_ad_hoc_commands = True when we shouldn't. + nobody_roles_list_url = reverse('api:user_roles_list', args=(self.nobody_django_user.pk,)) + with self.current_user('admin'): + response = self.post(nobody_roles_list_url, {"id": self.inventory.execute_role.id}, expect=204) + + # Create a credential for the other user and explicitly give other + # user admin permission on the inventory (still not allowed to run ad + # hoc commands; can get the list but can't see any items). + other_cred = self.create_test_credential(user=self.other_django_user) + user_roles_list_url = reverse('api:user_roles_list', args=(self.other_django_user.pk,)) + with self.current_user('admin'): + response = self.post(user_roles_list_url, {"id": self.inventory.update_role.id}, expect=204) + with self.current_user('other'): + response = self.get(url, expect=200) + self.assertEqual(response['count'], 0) + response = self.get(inventory_url, expect=200) + self.assertFalse(response['can_run_ad_hoc_commands']) + self.run_test_ad_hoc_command(url=url, inventory=None, credential=other_cred.pk, expect=403) + + # Update permission to allow other user to run ad hoc commands. Can + # only see his own ad hoc commands (because of credential permission). + with self.current_user('admin'): + response = self.post(user_roles_list_url, {"id": self.inventory.adhoc_role.id}, expect=204) + with self.current_user('other'): + response = self.get(url, expect=200) + self.assertEqual(response['count'], 0) + self.run_test_ad_hoc_command(url=url, inventory=None, credential=other_cred.pk, expect=201) + response = self.get(url, expect=200) + self.assertEqual(response['count'], 1) + response = self.get(inventory_url, expect=200) + self.assertTrue(response['can_run_ad_hoc_commands']) + + # Try to run with expired license. + self.create_expired_license_file() + with self.current_user('admin'): + self.run_test_ad_hoc_command(url=url, expect=403) + with self.current_user('normal'): + self.run_test_ad_hoc_command(url=url, expect=403) def test_host_ad_hoc_commands_list(self): # TODO: Figure out why this test needs pexpect diff --git a/awx/main/tests/old/inventory.py b/awx/main/tests/old/inventory.py index 2bed467144..c0fb172b63 100644 --- a/awx/main/tests/old/inventory.py +++ b/awx/main/tests/old/inventory.py @@ -1770,7 +1770,6 @@ class InventoryUpdatesTest(BaseTransactionTest): self.assertFalse(inventory_update.name.endswith(inventory_update.inventory_source.name), inventory_update.name) def test_update_from_rax(self): - self.skipTest('Skipping until we can resolve the CERTIFICATE_VERIFY_FAILED issue: #1706') source_username = getattr(settings, 'TEST_RACKSPACE_USERNAME', '') source_password = getattr(settings, 'TEST_RACKSPACE_API_KEY', '') source_regions = getattr(settings, 'TEST_RACKSPACE_REGIONS', '') diff --git a/awx/main/tests/old/jobs/jobs_monolithic.py b/awx/main/tests/old/jobs/jobs_monolithic.py index fbb80fd786..de308f52c5 100644 --- a/awx/main/tests/old/jobs/jobs_monolithic.py +++ b/awx/main/tests/old/jobs/jobs_monolithic.py @@ -961,7 +961,7 @@ class JobTemplateCallbackTest(BaseJobTestMixin, django.test.LiveServerTestCase): self.assertEqual(jobs_qs.count(), 7) job = jobs_qs[0] self.assertEqual(job.launch_type, 'callback') - self.assertEqual(job.limit, host.name) + self.assertEqual(job.limit, ':&'.join([job_template.limit, host.name])) self.assertEqual(job.hosts.count(), 1) self.assertEqual(job.hosts.all()[0], host) diff --git a/awx/main/tests/unit/api/test_serializers.py b/awx/main/tests/unit/api/test_serializers.py index a8fb25d005..4f98892e8c 100644 --- a/awx/main/tests/unit/api/test_serializers.py +++ b/awx/main/tests/unit/api/test_serializers.py @@ -1,7 +1,6 @@ # Python import pytest import mock -import json # AWX from awx.api.serializers import JobTemplateSerializer, JobSerializer, JobOptionsSerializer @@ -10,14 +9,9 @@ from awx.main.models import Label, Job #DRF from rest_framework import serializers -def mock_JT_resource_data(): - return ({}, []) - @pytest.fixture def job_template(mocker): - mock_jt = mocker.MagicMock(pk=5) - mock_jt.resource_validation_data = mock_JT_resource_data - return mock_jt + return mocker.MagicMock(pk=5) @pytest.fixture def job(mocker, job_template): @@ -146,21 +140,6 @@ class TestJobSerializerGetRelated(GetRelatedMixin): assert 'job_template' in related assert related['job_template'] == '/api/v1/%s/%d/' % ('job_templates', job.job_template.pk) -@mock.patch('awx.api.serializers.BaseSerializer.to_representation', lambda self,obj: { - 'extra_vars': obj.extra_vars}) -class TestJobSerializerSubstitution(): - - def test_survey_password_hide(self, mocker): - job = mocker.MagicMock(**{ - 'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}', - 'extra_vars.return_value': '{\"secret_key\": \"my_password\"}'}) - serializer = JobSerializer(job) - rep = serializer.to_representation(job) - extra_vars = json.loads(rep['extra_vars']) - assert extra_vars['secret_key'] == '$encrypted$' - job.display_extra_vars.assert_called_once_with() - assert 'my_password' not in extra_vars - @mock.patch('awx.api.serializers.BaseSerializer.get_summary_fields', lambda x,y: {}) class TestJobOptionsSerializerGetSummaryFields(GetSummaryFieldsMixin): def test__summary_field_labels_10_max(self, mocker, job_template, labels): diff --git a/awx/main/tests/unit/models/test_job_template_unit.py b/awx/main/tests/unit/models/test_job_template_unit.py deleted file mode 100644 index a25cce6f6c..0000000000 --- a/awx/main/tests/unit/models/test_job_template_unit.py +++ /dev/null @@ -1,40 +0,0 @@ -import pytest - - -def test_missing_project_error(job_template_factory): - objects = job_template_factory( - 'missing-project-jt', - organization='org1', - inventory='inventory1', - credential='cred1', - persisted=False) - obj = objects.job_template - assert 'project' in obj.resources_needed_to_start - validation_errors, resources_needed_to_start = obj.resource_validation_data() - assert 'project' in validation_errors - -def test_inventory_credential_need_to_start(job_template_factory): - objects = job_template_factory( - 'job-template-few-resources', - project='project1', - persisted=False) - obj = objects.job_template - assert 'inventory' in obj.resources_needed_to_start - assert 'credential' in obj.resources_needed_to_start - -def test_inventory_credential_contradictions(job_template_factory): - objects = job_template_factory( - 'job-template-paradox', - project='project1', - persisted=False) - obj = objects.job_template - obj.ask_inventory_on_launch = False - obj.ask_credential_on_launch = False - validation_errors, resources_needed_to_start = obj.resource_validation_data() - assert 'inventory' in validation_errors - assert 'credential' in validation_errors - -@pytest.mark.survey -def test_survey_password_list(job_with_secret_key_unit): - """Verify that survey_password_variables method gives a list of survey passwords""" - assert job_with_secret_key_unit.job_template.survey_password_variables() == ['secret_key', 'SSN'] diff --git a/awx/main/tests/unit/models/test_job_unit.py b/awx/main/tests/unit/models/test_job_unit.py deleted file mode 100644 index a1791c59d5..0000000000 --- a/awx/main/tests/unit/models/test_job_unit.py +++ /dev/null @@ -1,39 +0,0 @@ -import pytest -import json - -from awx.main.tasks import RunJob - - -@pytest.fixture -def job(mocker): - return mocker.MagicMock(**{ - 'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}', - 'extra_vars_dict': {"secret_key": "my_password"}, - 'pk': 1, 'job_template.pk': 1, 'job_template.name': '', - 'created_by.pk': 1, 'created_by.username': 'admin', - 'launch_type': 'manual'}) - -@pytest.mark.survey -def test_job_redacted_extra_vars(job_with_secret_key_unit): - """Verify that this method redacts vars marked as passwords in a survey""" - assert json.loads(job_with_secret_key_unit.display_extra_vars()) == { - 'submitter_email': 'foobar@redhat.com', - 'secret_key': '$encrypted$', - 'SSN': '$encrypted$'} - -def test_job_safe_args_redacted_passwords(job): - """Verify that safe_args hides passwords in the job extra_vars""" - kwargs = {'ansible_version': '2.1'} - run_job = RunJob() - safe_args = run_job.build_safe_args(job, **kwargs) - ev_index = safe_args.index('-e') + 1 - extra_vars = json.loads(safe_args[ev_index]) - assert extra_vars['secret_key'] == '$encrypted$' - -def test_job_args_unredacted_passwords(job): - kwargs = {'ansible_version': '2.1'} - run_job = RunJob() - args = run_job.build_args(job, **kwargs) - ev_index = args.index('-e') + 1 - extra_vars = json.loads(args[ev_index]) - assert extra_vars['secret_key'] == 'my_password' diff --git a/awx/plugins/inventory/ec2.py b/awx/plugins/inventory/ec2.py index bf3ba28ea0..cab0d2b85c 100755 --- a/awx/plugins/inventory/ec2.py +++ b/awx/plugins/inventory/ec2.py @@ -141,7 +141,6 @@ except ImportError: class Ec2Inventory(object): - def _empty_inventory(self): return {"_meta" : {"hostvars" : {}}} @@ -158,9 +157,6 @@ class Ec2Inventory(object): # Boto profile to use (if any) self.boto_profile = None - # AWS credentials. - self.credentials = {} - # Read settings and parse CLI arguments self.parse_cli_args() self.read_settings() @@ -228,7 +224,7 @@ class Ec2Inventory(object): configRegions_exclude = config.get('ec2', 'regions_exclude') if (configRegions == 'all'): if self.eucalyptus_host: - self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name, **self.credentials) + self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name) else: for regionInfo in ec2.regions(): if regionInfo.name not in configRegions_exclude: @@ -240,19 +236,6 @@ class Ec2Inventory(object): self.destination_variable = config.get('ec2', 'destination_variable') self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable') - if config.has_option('ec2', 'hostname_variable'): - self.hostname_variable = config.get('ec2', 'hostname_variable') - else: - self.hostname_variable = None - - if config.has_option('ec2', 'destination_format') and \ - config.has_option('ec2', 'destination_format_tags'): - self.destination_format = config.get('ec2', 'destination_format') - self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',') - else: - self.destination_format = None - self.destination_format_tags = None - # Route53 self.route53_enabled = config.getboolean('ec2', 'route53') self.route53_excluded_zones = [] @@ -327,29 +310,6 @@ class Ec2Inventory(object): if config.has_option('ec2', 'boto_profile') and not self.boto_profile: self.boto_profile = config.get('ec2', 'boto_profile') - # AWS credentials (prefer environment variables) - if not (self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID') or - os.environ.get('AWS_PROFILE')): - if config.has_option('credentials', 'aws_access_key_id'): - aws_access_key_id = config.get('credentials', 'aws_access_key_id') - else: - aws_access_key_id = None - if config.has_option('credentials', 'aws_secret_access_key'): - aws_secret_access_key = config.get('credentials', 'aws_secret_access_key') - else: - aws_secret_access_key = None - if config.has_option('credentials', 'aws_security_token'): - aws_security_token = config.get('credentials', 'aws_security_token') - else: - aws_security_token = None - if aws_access_key_id: - self.credentials = { - 'aws_access_key_id': aws_access_key_id, - 'aws_secret_access_key': aws_secret_access_key - } - if aws_security_token: - self.credentials['security_token'] = aws_security_token - # Cache related cache_dir = os.path.expanduser(config.get('ec2', 'cache_path')) if self.boto_profile: @@ -357,22 +317,10 @@ class Ec2Inventory(object): if not os.path.exists(cache_dir): os.makedirs(cache_dir) - cache_name = 'ansible-ec2' - aws_profile = lambda: (self.boto_profile or - os.environ.get('AWS_PROFILE') or - os.environ.get('AWS_ACCESS_KEY_ID') or - self.credentials.get('aws_access_key_id', None)) - if aws_profile(): - cache_name = '%s-%s' % (cache_name, aws_profile()) - self.cache_path_cache = cache_dir + "/%s.cache" % cache_name - self.cache_path_index = cache_dir + "/%s.index" % cache_name + self.cache_path_cache = cache_dir + "/ansible-ec2.cache" + self.cache_path_index = cache_dir + "/ansible-ec2.index" self.cache_max_age = config.getint('ec2', 'cache_max_age') - if config.has_option('ec2', 'expand_csv_tags'): - self.expand_csv_tags = config.getboolean('ec2', 'expand_csv_tags') - else: - self.expand_csv_tags = False - # Configure nested groups instead of flat namespace. if config.has_option('ec2', 'nested_groups'): self.nested_groups = config.getboolean('ec2', 'nested_groups') @@ -434,10 +382,7 @@ class Ec2Inventory(object): # Instance filters (see boto and EC2 API docs). Ignore invalid filters. self.ec2_instance_filters = defaultdict(list) if config.has_option('ec2', 'instance_filters'): - - filters = [f for f in config.get('ec2', 'instance_filters').split(',') if f] - - for instance_filter in filters: + for instance_filter in config.get('ec2', 'instance_filters', '').split(','): instance_filter = instance_filter.strip() if not instance_filter or '=' not in instance_filter: continue @@ -456,7 +401,7 @@ class Ec2Inventory(object): help='Get all the variables about a specific instance') parser.add_argument('--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)') - parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile', + parser.add_argument('--boto-profile', action='store', help='Use boto profile for connections to EC2') self.args = parser.parse_args() @@ -481,7 +426,7 @@ class Ec2Inventory(object): def connect(self, region): ''' create connection to api server''' if self.eucalyptus: - conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials) + conn = boto.connect_euca(host=self.eucalyptus_host) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) @@ -495,7 +440,7 @@ class Ec2Inventory(object): return connect_args def connect_to_aws(self, module, region): - connect_args = self.credentials + connect_args = {} # only pass the profile name if it's set (as it is not supported by older boto versions) if self.boto_profile: @@ -521,27 +466,15 @@ class Ec2Inventory(object): else: reservations = conn.get_all_instances() - # Pull the tags back in a second step - # AWS are on record as saying that the tags fetched in the first `get_all_instances` request are not - # reliable and may be missing, and the only way to guarantee they are there is by calling `get_all_tags` - instance_ids = [] - for reservation in reservations: - instance_ids.extend([instance.id for instance in reservation.instances]) - tags = conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids}) - tags_by_instance_id = defaultdict(dict) - for tag in tags: - tags_by_instance_id[tag.res_id][tag.name] = tag.value - for reservation in reservations: for instance in reservation.instances: - instance.tags = tags_by_instance_id[instance.id] self.add_instance(instance, region) except boto.exception.BotoServerError as e: if e.error_code == 'AuthFailure': error = self.get_auth_error_message() else: - backend = 'Eucalyptus' if self.eucalyptus else 'AWS' + backend = 'Eucalyptus' if self.eucalyptus else 'AWS' error = "Error connecting to %s backend.\n%s" % (backend, e.message) self.fail_with_error(error, 'getting EC2 instances') @@ -552,14 +485,9 @@ class Ec2Inventory(object): try: conn = self.connect_to_aws(rds, region) if conn: - marker = None - while True: - instances = conn.get_all_dbinstances(marker=marker) - marker = instances.marker - for instance in instances: - self.add_rds_instance(instance, region) - if not marker: - break + instances = conn.get_all_dbinstances() + for instance in instances: + self.add_rds_instance(instance, region) except boto.exception.BotoServerError as e: error = e.reason @@ -681,9 +609,7 @@ class Ec2Inventory(object): return # Select the best destination address - if self.destination_format and self.destination_format_tags: - dest = self.destination_format.format(*[ getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags ]) - elif instance.subnet_id: + if instance.subnet_id: dest = getattr(instance, self.vpc_destination_variable, None) if dest is None: dest = getattr(instance, 'tags').get(self.vpc_destination_variable, None) @@ -696,46 +622,32 @@ class Ec2Inventory(object): # Skip instances we cannot address (e.g. private VPC subnet) return - # Set the inventory name - hostname = None - if self.hostname_variable: - if self.hostname_variable.startswith('tag_'): - hostname = instance.tags.get(self.hostname_variable[4:], None) - else: - hostname = getattr(instance, self.hostname_variable) - - # If we can't get a nice hostname, use the destination address - if not hostname: - hostname = dest - else: - hostname = self.to_safe(hostname).lower() - # if we only want to include hosts that match a pattern, skip those that don't - if self.pattern_include and not self.pattern_include.match(hostname): + if self.pattern_include and not self.pattern_include.match(dest): return # if we need to exclude hosts that match a pattern, skip those - if self.pattern_exclude and self.pattern_exclude.match(hostname): + if self.pattern_exclude and self.pattern_exclude.match(dest): return # Add to index - self.index[hostname] = [region, instance.id] + self.index[dest] = [region, instance.id] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: - self.inventory[instance.id] = [hostname] + self.inventory[instance.id] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', instance.id) # Inventory: Group by region if self.group_by_region: - self.push(self.inventory, region, hostname) + self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone: - self.push(self.inventory, instance.placement, hostname) + self.push(self.inventory, instance.placement, dest) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, instance.placement) @@ -744,28 +656,28 @@ class Ec2Inventory(object): # Inventory: Group by Amazon Machine Image (AMI) ID if self.group_by_ami_id: ami_id = self.to_safe(instance.image_id) - self.push(self.inventory, ami_id, hostname) + self.push(self.inventory, ami_id, dest) if self.nested_groups: self.push_group(self.inventory, 'images', ami_id) # Inventory: Group by instance type if self.group_by_instance_type: type_name = self.to_safe('type_' + instance.instance_type) - self.push(self.inventory, type_name, hostname) + self.push(self.inventory, type_name, dest) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by key pair if self.group_by_key_pair and instance.key_name: key_name = self.to_safe('key_' + instance.key_name) - self.push(self.inventory, key_name, hostname) + self.push(self.inventory, key_name, dest) if self.nested_groups: self.push_group(self.inventory, 'keys', key_name) # Inventory: Group by VPC if self.group_by_vpc_id and instance.vpc_id: vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id) - self.push(self.inventory, vpc_id_name, hostname) + self.push(self.inventory, vpc_id_name, dest) if self.nested_groups: self.push_group(self.inventory, 'vpcs', vpc_id_name) @@ -774,51 +686,44 @@ class Ec2Inventory(object): try: for group in instance.groups: key = self.to_safe("security_group_" + group.name) - self.push(self.inventory, key, hostname) + self.push(self.inventory, key, dest) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) except AttributeError: - self.fail_with_error('\n'.join(['Package boto seems a bit older.', + self.fail_with_error('\n'.join(['Package boto seems a bit older.', 'Please upgrade boto >= 2.3.0.'])) # Inventory: Group by tag keys if self.group_by_tag_keys: for k, v in instance.tags.items(): - if self.expand_csv_tags and v and ',' in v: - values = map(lambda x: x.strip(), v.split(',')) + if v: + key = self.to_safe("tag_" + k + "=" + v) else: - values = [v] - - for v in values: + key = self.to_safe("tag_" + k) + self.push(self.inventory, key, dest) + if self.nested_groups: + self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k)) if v: - key = self.to_safe("tag_" + k + "=" + v) - else: - key = self.to_safe("tag_" + k) - self.push(self.inventory, key, hostname) - if self.nested_groups: - self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k)) - if v: - self.push_group(self.inventory, self.to_safe("tag_" + k), key) + self.push_group(self.inventory, self.to_safe("tag_" + k), key) # Inventory: Group by Route53 domain names if enabled if self.route53_enabled and self.group_by_route53_names: route53_names = self.get_instance_route53_names(instance) for name in route53_names: - self.push(self.inventory, name, hostname) + self.push(self.inventory, name, dest) if self.nested_groups: self.push_group(self.inventory, 'route53', name) # Global Tag: instances without tags if self.group_by_tag_none and len(instance.tags) == 0: - self.push(self.inventory, 'tag_none', hostname) + self.push(self.inventory, 'tag_none', dest) if self.nested_groups: self.push_group(self.inventory, 'tags', 'tag_none') # Global Tag: tag all EC2 instances - self.push(self.inventory, 'ec2', hostname) + self.push(self.inventory, 'ec2', dest) - self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) - self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest + self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance) def add_rds_instance(self, instance, region): @@ -836,38 +741,24 @@ class Ec2Inventory(object): # Skip instances we cannot address (e.g. private VPC subnet) return - # Set the inventory name - hostname = None - if self.hostname_variable: - if self.hostname_variable.startswith('tag_'): - hostname = instance.tags.get(self.hostname_variable[4:], None) - else: - hostname = getattr(instance, self.hostname_variable) - - # If we can't get a nice hostname, use the destination address - if not hostname: - hostname = dest - - hostname = self.to_safe(hostname).lower() - # Add to index - self.index[hostname] = [region, instance.id] + self.index[dest] = [region, instance.id] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: - self.inventory[instance.id] = [hostname] + self.inventory[instance.id] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', instance.id) # Inventory: Group by region if self.group_by_region: - self.push(self.inventory, region, hostname) + self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone: - self.push(self.inventory, instance.availability_zone, hostname) + self.push(self.inventory, instance.availability_zone, dest) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, instance.availability_zone) @@ -876,14 +767,14 @@ class Ec2Inventory(object): # Inventory: Group by instance type if self.group_by_instance_type: type_name = self.to_safe('type_' + instance.instance_class) - self.push(self.inventory, type_name, hostname) + self.push(self.inventory, type_name, dest) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by VPC if self.group_by_vpc_id and instance.subnet_group and instance.subnet_group.vpc_id: vpc_id_name = self.to_safe('vpc_id_' + instance.subnet_group.vpc_id) - self.push(self.inventory, vpc_id_name, hostname) + self.push(self.inventory, vpc_id_name, dest) if self.nested_groups: self.push_group(self.inventory, 'vpcs', vpc_id_name) @@ -892,32 +783,31 @@ class Ec2Inventory(object): try: if instance.security_group: key = self.to_safe("security_group_" + instance.security_group.name) - self.push(self.inventory, key, hostname) + self.push(self.inventory, key, dest) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) except AttributeError: - self.fail_with_error('\n'.join(['Package boto seems a bit older.', + self.fail_with_error('\n'.join(['Package boto seems a bit older.', 'Please upgrade boto >= 2.3.0.'])) # Inventory: Group by engine if self.group_by_rds_engine: - self.push(self.inventory, self.to_safe("rds_" + instance.engine), hostname) + self.push(self.inventory, self.to_safe("rds_" + instance.engine), dest) if self.nested_groups: self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine)) # Inventory: Group by parameter group if self.group_by_rds_parameter_group: - self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), hostname) + self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), dest) if self.nested_groups: self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name)) # Global Tag: all RDS instances - self.push(self.inventory, 'rds', hostname) + self.push(self.inventory, 'rds', dest) - self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) - self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest + self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance) def add_elasticache_cluster(self, cluster, region): ''' Adds an ElastiCache cluster to the inventory and index, as long as @@ -1230,8 +1120,6 @@ class Ec2Inventory(object): instance_vars['ec2_placement'] = value.zone elif key == 'ec2_tags': for k, v in value.items(): - if self.expand_csv_tags and ',' in v: - v = map(lambda x: x.strip(), v.split(',')) key = self.to_safe('ec2_tag_' + k) instance_vars[key] = v elif key == 'ec2_groups': @@ -1406,7 +1294,7 @@ class Ec2Inventory(object): def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" - if not self.replace_dash_in_groups: + if self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word) @@ -1422,3 +1310,4 @@ class Ec2Inventory(object): # Run the script Ec2Inventory() + diff --git a/awx/settings/defaults.py b/awx/settings/defaults.py index a4110e8286..603bd21d19 100644 --- a/awx/settings/defaults.py +++ b/awx/settings/defaults.py @@ -540,7 +540,6 @@ EC2_REGION_NAMES = { 'ap-southeast-1': 'Asia Pacific (Singapore)', 'ap-southeast-2': 'Asia Pacific (Sydney)', 'ap-northeast-1': 'Asia Pacific (Tokyo)', - 'ap-northeast-2': 'Asia Pacific (Seoul)', 'sa-east-1': 'South America (Sao Paulo)', 'us-gov-west-1': 'US West (GovCloud)', 'cn-north-1': 'China (Beijing)', diff --git a/awx/sso/backends.py b/awx/sso/backends.py index 3d5edb7ec9..9e227624ec 100644 --- a/awx/sso/backends.py +++ b/awx/sso/backends.py @@ -6,7 +6,6 @@ import logging # Django from django.dispatch import receiver -from django.contrib.auth.models import User from django.conf import settings as django_settings # django-auth-ldap @@ -105,18 +104,6 @@ class RADIUSBackend(BaseRADIUSBackend): return None return super(RADIUSBackend, self).get_user(user_id) - def get_django_user(self, username, password=None): - try: - user = User.objects.get(username=username) - except User.DoesNotExist: - user = User(username=username) - - if password is not None: - user.set_unusable_password() - user.save() - - return user - class TowerSAMLIdentityProvider(BaseSAMLIdentityProvider): ''' @@ -176,7 +163,7 @@ class SAMLAuth(BaseSAMLAuth): return super(SAMLAuth, self).get_user(user_id) -def _update_m2m_from_groups(user, ldap_user, rel, opts, remove=True): +def _update_m2m_from_groups(user, ldap_user, rel, opts, remove=False): ''' Hepler function to update m2m relationship based on LDAP group membership. ''' @@ -220,7 +207,7 @@ def on_populate_user(sender, **kwargs): org_map = getattr(backend.settings, 'ORGANIZATION_MAP', {}) for org_name, org_opts in org_map.items(): org, created = Organization.objects.get_or_create(name=org_name) - remove = bool(org_opts.get('remove', True)) + remove = bool(org_opts.get('remove', False)) admins_opts = org_opts.get('admins', None) remove_admins = bool(org_opts.get('remove_admins', remove)) _update_m2m_from_groups(user, ldap_user, org.admin_role.members, admins_opts, @@ -238,7 +225,7 @@ def on_populate_user(sender, **kwargs): org, created = Organization.objects.get_or_create(name=team_opts['organization']) team, created = Team.objects.get_or_create(name=team_name, organization=org) users_opts = team_opts.get('users', None) - remove = bool(team_opts.get('remove', True)) + remove = bool(team_opts.get('remove', False)) _update_m2m_from_groups(user, ldap_user, team.member_role.users, users_opts, remove) diff --git a/awx/sso/pipeline.py b/awx/sso/pipeline.py index 756e64279d..a79aecacb0 100644 --- a/awx/sso/pipeline.py +++ b/awx/sso/pipeline.py @@ -44,7 +44,7 @@ def prevent_inactive_login(backend, details, user=None, *args, **kwargs): raise AuthInactive(backend) -def _update_m2m_from_expression(user, rel, expr, remove=True): +def _update_m2m_from_expression(user, rel, expr, remove=False): ''' Helper function to update m2m relationship based on user matching one or more expressions. @@ -95,7 +95,7 @@ def update_user_orgs(backend, details, user=None, *args, **kwargs): continue # Update org admins from expression(s). - remove = bool(org_opts.get('remove', True)) + remove = bool(org_opts.get('remove', False)) admins_expr = org_opts.get('admins', None) remove_admins = bool(org_opts.get('remove_admins', remove)) _update_m2m_from_expression(user, org.admin_role.members, admins_expr, remove_admins) @@ -133,5 +133,5 @@ def update_user_teams(backend, details, user=None, *args, **kwargs): # Update team members from expression(s). team = Team.objects.get_or_create(name=team_name, organization=org)[0] users_expr = team_opts.get('users', None) - remove = bool(team_opts.get('remove', True)) + remove = bool(team_opts.get('remove', False)) _update_m2m_from_expression(user, team.member_role.members, users_expr, remove) diff --git a/awx/static/api/api.css b/awx/static/api/api.css index a3f57a773d..078799e6a5 100644 --- a/awx/static/api/api.css +++ b/awx/static/api/api.css @@ -37,13 +37,13 @@ body .navbar { border-color: #E8E8E8; } body .navbar .navbar-brand { - color: #707070; + color: #848992; padding: 0; font-size: 14px; } body .navbar .navbar-brand:focus, body .navbar .navbar-brand:hover { - color: #707070; + color: #848992; } body .navbar .navbar-brand img { display: inline-block; @@ -60,7 +60,7 @@ body .navbar .navbar-brand > span { body .navbar .navbar-title { float: left; height: 50px; - color: #707070; + color: #848992; padding: 0; font-size: 14px; display: none; @@ -74,19 +74,19 @@ body.show-title .navbar .navbar-title { display: inline-block; } body .navbar .navbar-nav > li > a { - color: #707070; + color: #848992; display: flex; justify-content: center; } body .navbar .navbar-nav > li > a:focus, body .navbar .navbar-nav > li > a:hover { - color: #707070; + color: #848992; } body .navbar .navbar-nav > li > a > span.glyphicon { font-size: 20px; padding-right: 5px; padding-left: 5px; - color: #848992; + color: #B7B7B7; } body .page-header { @@ -110,7 +110,7 @@ body .description .hide-description span.glyphicon { font-size: 20px; } body .description .hide-description:hover span.glyphicon { - color: #848992; + color: #B7B7B7; } body ul.breadcrumb, body .description, @@ -167,7 +167,7 @@ body .form-actions button { body .form-horizontal .control-label { text-transform: uppercase; font-weight: normal; - color: #707070; + color: #848992; } body textarea.form-control { font-family: Menlo, Monaco, Consolas, "Courier New", monospace; @@ -182,22 +182,22 @@ body .description pre { } body .tooltip.bottom .tooltip-arrow { - border-bottom-color: #707070; + border-bottom-color: #848992; } body .tooltip.top .tooltip-arrow { - border-top-color: #707070; + border-top-color: #848992; } body .tooltip.left .tooltip-arrow { - border-left-color: #707070; + border-left-color: #848992; } body .tooltip.right .tooltip-arrow { - border-right-color: #707070; + border-right-color: #848992; } body .tooltip.in { opacity: 1; } body .tooltip-inner { - background-color: #707070; + background-color: #848992; } body .btn { @@ -205,7 +205,7 @@ body .btn { } .btn-primary { background-color: #FFFFFF; - color: #707070; + color: #848992; border: 1px solid #E8E8E8; } .btn-primary:hover, @@ -224,14 +224,14 @@ body .btn { .open>.dropdown-toggle.btn-primary:hover, .open>.dropdown-toggle.btn-primary { background-color: #FAFAFA; - color: #707070; + color: #848992; border: 1px solid #E8E8E8; } body .tab-content .btn-primary { - background-color: #5cb85c; + background-color: #3CB878; color: #FFFFFF; - border: 1px solid #5cb85c; + border: 1px solid #3CB878; } body .tab-content .btn-primary:hover, body .tab-content .btn-primary.focus, @@ -244,9 +244,9 @@ body .tab-content .btn-primary.active:hover, body .tab-content .btn-primary:active.focus, body .tab-content .btn-primary:active:focus, body .tab-content .btn-primary:active:hover { - background-color: #449d44; + background-color: #60D66F; color: #FFFFFF; - border: 1px solid #449d44; + border: 1px solid #60D66F; } .btn-danger { @@ -265,8 +265,8 @@ body .tab-content .btn-primary:active:hover { .btn-danger:active.focus, .btn-danger:active:focus, .btn-danger:active:hover { - background-color: #c9302c; - border-color: #c9302c; + background-color: #F0AD4E; + border-color: #F0AD4E; } body .wrapper { @@ -283,7 +283,7 @@ body #footer { overflow: hidden; margin-bottom: 0; height: 40px; - color: #707070; + color: #848992; } body #footer .footer-logo { text-align: left; @@ -302,7 +302,7 @@ body #footer .footer-copyright { padding-top: 10px; } body #footer .footer-copyright a { - color: #707070; + color: #848992; } @media screen and (min-width: 768px) { @@ -329,7 +329,7 @@ body #footer .footer-copyright a { border-color: #E8E8E8; } body .navbar .navbar-toggle .icon-bar { - background-color: #848992; + background-color: #B7B7B7; } body .navbar .tooltip { visibility: hidden; diff --git a/awx/static/favicon.ico b/awx/static/favicon.ico index 5003cda615bd139085627face4da71ed34c80f6e..31b759caf9efd7d8b9130d6df61d9e62fccc36d0 100644 GIT binary patch literal 6518 zcmeHKNlaBq6n#tr4uBDds31-aYSMHXVw8npp~h9m#Ek<+d*#x^jXPr^3*0t?-8dyG zYNQnw&Bmc2p&bAdqXsc9G$!%^!3H$Q|9q_1=iILQQanBy*ZPu5Ro%MxoLjf1`#dkn zOZIYdJk$kVQJUxd;CWs_f$isd-Y<|9K?W6Q{4Yo4d63WWr8x4fGF1KRY|yPfkwu)6&wUz{a09Z=TOF==_F$hQ&#>bp~`>z~NID zB{p~N+zHf^EK8OwnZS6AV;1)>w9`@KBQF~M{Q2`^TefV8lOKJGu)`DAFS{k1< zYnI?x8w`16^v&wTySlpkTeohBE%c?vn7M!dzIpcS8TIHF=kf`48E|TW>91I^LU6BM zy=q2AMof8mx!CU9xzqIY^cdgw&Aof~#23shnv;`5tZLYI5pU_zrNlKGHf%71gM;SG znKS0lp+jb1V8DO%>Xmu-?wvV$^r+ZlPCADU*uO>bGcz+8C*f>qX)*8Lzc>B;{pS4n z^QN(}(Y$!^LdM9kXwjlLIbqjNd#)4ulQvf7;I9WwJRUa}FJ2Uz-rinw<;oRl7Znw; zj?>24ccrGLN?Z_kgII`OcXzkBapQ(LQF+3DJNVXY+O$dJ`T6qW1orpCN^^Tu%QH*ek)*_t(LSW`Dj8`yH)%d9g^WsCZOc69da*~F6l zi$3QYg{_e7aW_<}P)KTr(y$d{g;E;X=Z-$VY1I0%AeKEkc zwJW27{ahQBeRDPM$pVye6yB%u;ST+ZkN01)qrV*MyAScML*0t<9PJSnw0kJCWBXvU z+_58u-ldNCvrYF#F9z-@ls?^uU#j6tA8o);?6A0)j(A#A_fIA;PNIw{AKH^Ba#m2s zQMhke*jD)`M}G|RDllYP7R8=M8X7NzU8jQ+v-n13tRdr>lA?0kr!O%_)&cy&5J%Vt z^{o`~i&*>#v^h6&P2saV0l(X)E$mn%F18;5VaW_W=-L!I+)=a*->?M>7MQH8EW^Ib z6K;b??nBCi^_lCICTf26x^7&0oP3FUg5AsfO zjQq$A=tJDjaSZa{Y=ZN5E0;aX`RC>330_rImArM#GmalWF0z7x0$B%Q!v|yEZt<_P zvop|t^5lv7WVkNW=lm?!AL#STgG}xg9pjw1e=sIR^PKj7+NICAa4&G3HRcr+74oLj zPc7Be)uK;-iK*+$+U~_X)D>3FyG7QN`<(OA7@RwIPB2GDN6oHXy9AT@1oh}+Wo4z| z7{Ln$Kvz85?{!T_9@FB#Gd2C)wylozTFHB4GC^TLxYTIY%X8E zEOK%`efpGno%EZVn?#TMmvgt=Q(^!a^YJ!~i|VkZ4P&giA9Gi7FmF=s_V)IGn>pFB zW5=Zb@#9Ccckf=&LvAEBIK&5cu9*KFl;>8)yUO)b>~vorK73emNBVH~>{;{p@nhi{ zA0IdM_4T65T$RULaKMa>jftFbpuXn4I(K4Qu1Q<}I}<<0X-AyG!a}LJpUKPe=+PsyapOjj zQ>XFIMv=dK`7)3(Z+1A{cECSV{51}Yfu3FN$G*Nk;o%yPmocXN_3PIn=UJhgGWxGL zTHATM@lUw_9DO-wJj2Aje*JndPmPP-QNzQ-X6x3ifnV;vcktZxzXN%~^QZc(5hIx= z`FHQ$ZMeU=2D;7LDSaOCcf}&&^H#{ zFAk@>_k;u7z2rvWf6}z~Cu~bxy^Gl9KIa;6-mL5D>V#YOM54WCF~jcu z270D1HC!SuKRFY{#l^zEY}qoo^TYm!xcUD6NMd}F17Lhg{t>q4e4rb=3EQ@9V_qQq z&CSg+X8&Uoo;!=D>#O+(^PhzI*Gw@Wj^-byPoI{%cE^q#!msiKzH=XrTg-6&#TX>Y zKgYv3?DH%#7QB}k4=p@%Y;!Duop8f8QT_=t`7|G8{;l~4b3u8R+<5RT@J-;|$G1Jq z?dXQ{@1H|lwi{IHL-_wgaNtXDcF|@``9?^t&)V|x9TUGD8Dk#Ky93ftLw!i}|HatK zzYS{s6ESCEVO#!@l+*h1wf|r0iu%BQG2&g%wR5pQ*QPG~VSX9pxM;hW#QoA2{2N%s reBkZ}F8{y(Mq%zS%)&Mb-x9gcp`Y)7yJyT1e{X(|!1oAz>k;@5pB}e3 literal 15086 zcmdU$dvI0N6~+%mMW^HF)aie<(#l)KAczP)5Uf=cw6=m3TPli=nQB#Z9BGw^w$@fD zTD3AGSUbg0LE2g$qoPJFibzNx;UUieA-nHX8EKC4z@Gof&-l`p-JO%s%vagb zlL2ole(+s%UWKh(wbvf_^*ZZcRBrPmXWR`dec54M0dE?=%j+&2FHGNJQ=i*xcl>gV zef04z>w8AIUq4qSh~cFT{PuHs)ZyBnEVr`q2Aem(-ijx#kJIhiFWrBRpSX9Ag*InS zovmB9&xV{|5pH)^ch`T6f%N!sGHBUjNtDe`j+Ti(OA(W(UgGrO&WQWp=`XcJW`P%I!aU|dPwxCXq$*Jc2MN{ zj^Ct_M;Xe(18*K0Q$^tksGH&^MKvO)D`^Z5yvXq7B>@tY1@|?grJ|(zGL=IHvU0YC z%7C+zXuN2rD3i>5(~*TtWXCoG>7tIJdqj<*e0Ah1k4$8vqZJ0e0~)FLaMnAD3EAjq zH6DU*#>o;pwytp*2ZT?;c5BqD|GU)KfB#ofouH6}{t;!>3fQGJQVuvB%#teyzRq@-`bWY-!y3PFZyM{SfHyqnP>9M*kI;EwxQsnr(l} zLA&$LHF5im&jZ$eXO`Quf7xV>jR%bI$io{ll}8skUHw@vTIqJ*y}B&4SG7kI-gHd1?KH|055kr)W|Pw;i3j#ulw`PyF2~8wnzLJKt4Lr&6>@+nbsNpO`o3CyWBpN ztwDI|&o$OfX{7h+QfhbKz1FHXHu?QCe_?~w?QZdHs%(7~$VaE!OIq0(Vg3B34IY%O zL8x5XXao8#vZB+g23*J}N~uC8ga@%OB?K4+BK9NC0~$$x5PPiB+t_Rwr)(s|Qf z*y77?+;hOMXK7i3jk;#JZ_g6%QrmCd+HB03h&`H?;p!B`ZvW1dpH8O_(6O_w#mDgW zJ3DQ#>^IU`o2JRGB+QyEdp2U{M|7rTDjof_K{ze`x5iuVo@Msl`>8gjztK(K43=HI zdhK4@*L1*cx-r%sj+dFz%^1i!{v1B^G2R(tjKhKb7x`^JLAE^MbJ@hKK^fNFC9X4jn3V#k(t>0%u2UliV@14$Y?A9OFz>Mo}8~w8XhwJ>cbz8H)9?qSgT9;mU zaf`oCM$2dUcIz+tWA~p-yzFta|GC|71OC+QYO$Y=`ZCjA6RxxS9o>J}3)vH0e%6?A zc=Nbb{+@vT_dl$&Gj$eDIPQ>*uCyJb-?Tw@QCs^X1`~Sv>HPWW=ew;*=jXfcTANSZ zTiG8W8w3oA?JqD~A^YOi+g4j2?F9+z9&3MvFwiE6?N8PofBh2{@#Uh%Kz6#_(HjoR zrwxvX{q1lB7>>yKBZ7gp=q6&UGGB7FZ!{ksc#(lDCq8i;@X;3k)AMH(V1T28;=_La zwvvu!o@WO=Z{j}BJEhL^PN?#{PEd*Gbu5$|Qxbnm$l2H}NLpD0lg-&$irzjHr zLX`GXbScbFArV)FNjB_=sqQjUe42<1lL_I_|h^C6z zJ6DTpMSDa|0r8tO@+d=Dc;H3GVMLZ$6nX+WUhxRg4AFYgeo=Iu=K6*QUSuE(nFY<~ z%!pGtPOjqPMCf``gkLZh#-#bkLMF106&<#EI9ZAryVFIxMM-hxTMpUJiwa&_!+jw+ zv;%XE`L{@vFP=inqYIq{&vWsDow{Ll9~swo&O!qR zEVlcL*ITiCViQHfM=Z7OIRE^!BdsKX)Iply1jIH4FEjnKG zhA5*9AHVz@<&}*bZ~ZX)_3g2~*KBe)pWz?DFIc-{zb~gozT_*1hkU4+aexu5ejSJd zqFy;|0{kS8%Ma+nCj4^pTO{m%zuW-%m!`|Ff$!IaUG*)#AC5689N7qrejfz5!GE;q z@1kscejaT%Oy}#3o12_!d+hP*ME)IkFa6;Xn^RIJKUJFD|1noSgMNJy`^dlwX4m%E zvDkt+@lysr&g3f~9be`cjqwWk*rEZy--Gh8CGEoiE0`UAZ1EPb zB_aCw#+z1JgZ#Y&#=*_EtcvxuFt@pzn4mWXjJ3G1TK?-HgJbX9GvNU%n8DA!#(5%B z**594XWzh2y2`z2%kwp;U+utPq= zQP<|>BXl^y40iT3&UG$5Q4G$Z7ggG7y|*AxjYsv4hI-LIqpw?GWqKFm!cO6wEdOp_ z%~9_CTzFS^8+rN|9X>FFopUv3Q$oym)6jdZ`kuBW)a$MzPa{JRZ)I{B4aiw0>wFJ%7~UNB?R{YZqLAS>3`e2tScdrHVG}(1 zShW@DZC7|ckJB3480@*MrNf6O-?wAh&*7&J3K~Dir0)mm&06KMLv!`Tm$q6D%?;Yz z>1EG*MR$`fy!Nl{cG{u$b?I`he1h1GpTg&F(5H-nr=CgO9f5ED!g_zKIQ;CZmuYRS z)*4G-zq{qu`28*cZdX?~e+yba!+N;Ozf$+_TWVALYji(m46(KbTZPRpRsE9NIu36% zcI#(B`&Sr0zp)W!|NGG075g#wS&Xl9v^1*+ey)n{C)-OYGF|q|)~W=~Wx{`TMe)*Kx8EraAio8z?XPElz%FeO%;^eSeVa z&+j#6dg?93Y|T{{UYxNt{HE2lWxjFPegl7A_H!J5(iju$PtGP{oR9wb3hl+IdBGcy z(W48pb)xmd)(_jyoCOk{Uov4&;V-ox$Udm5PT554$De5};!d6L{zrBGp5WG{Y_f9X zMb9tvL89|x4!Qn#`J2}NXlT~^BkUsPNiG>V@>`uBIRvXbl=J+aL#~eteAoYMg>jw@ zhovj_*!kxbZ0m&U-0J-991%es=!1;@lO*^V8@&1XFnD|6>hSb)o7!XRIQ+5xlTaTV zCydjQ;LKKrKDci}mH&1N{9Acnc2y$Zh{KsF&gj1i)q(vOUtJ~{In(Kbf$|f*skcbg zItM&Eb#wTC33Bph&~UY^{WW`#udiL8W0;*>#n>9uV}=M@@c;V#KulF!e=xtX zV>v%?p5RQxxsJ0b=WBcf5Wh(yk1~{n2j0BzcjNH1Crucr5A)plBb{IDYNbK!homvC zDO2#hdK9PsSjat8BIY3xag`ny5trzp5iyMVqc=u+W#oA+#20#=ii_b;thY#djpTV% z#GMYsC4B3Ds9apkH~)hbiTV60Lovc*^p=nw!dJz22*0aWw7#w#T)U`={B}yWTUF4G Lu3f{Av{d-N$NdAy diff --git a/awx/ui/client/assets/favicon.ico b/awx/ui/client/assets/favicon.ico index 5003cda615bd139085627face4da71ed34c80f6e..31b759caf9efd7d8b9130d6df61d9e62fccc36d0 100644 GIT binary patch literal 6518 zcmeHKNlaBq6n#tr4uBDds31-aYSMHXVw8npp~h9m#Ek<+d*#x^jXPr^3*0t?-8dyG zYNQnw&Bmc2p&bAdqXsc9G$!%^!3H$Q|9q_1=iILQQanBy*ZPu5Ro%MxoLjf1`#dkn zOZIYdJk$kVQJUxd;CWs_f$isd-Y<|9K?W6Q{4Yo4d63WWr8x4fGF1KRY|yPfkwu)6&wUz{a09Z=TOF==_F$hQ&#>bp~`>z~NID zB{p~N+zHf^EK8OwnZS6AV;1)>w9`@KBQF~M{Q2`^TefV8lOKJGu)`DAFS{k1< zYnI?x8w`16^v&wTySlpkTeohBE%c?vn7M!dzIpcS8TIHF=kf`48E|TW>91I^LU6BM zy=q2AMof8mx!CU9xzqIY^cdgw&Aof~#23shnv;`5tZLYI5pU_zrNlKGHf%71gM;SG znKS0lp+jb1V8DO%>Xmu-?wvV$^r+ZlPCADU*uO>bGcz+8C*f>qX)*8Lzc>B;{pS4n z^QN(}(Y$!^LdM9kXwjlLIbqjNd#)4ulQvf7;I9WwJRUa}FJ2Uz-rinw<;oRl7Znw; zj?>24ccrGLN?Z_kgII`OcXzkBapQ(LQF+3DJNVXY+O$dJ`T6qW1orpCN^^Tu%QH*ek)*_t(LSW`Dj8`yH)%d9g^WsCZOc69da*~F6l zi$3QYg{_e7aW_<}P)KTr(y$d{g;E;X=Z-$VY1I0%AeKEkc zwJW27{ahQBeRDPM$pVye6yB%u;ST+ZkN01)qrV*MyAScML*0t<9PJSnw0kJCWBXvU z+_58u-ldNCvrYF#F9z-@ls?^uU#j6tA8o);?6A0)j(A#A_fIA;PNIw{AKH^Ba#m2s zQMhke*jD)`M}G|RDllYP7R8=M8X7NzU8jQ+v-n13tRdr>lA?0kr!O%_)&cy&5J%Vt z^{o`~i&*>#v^h6&P2saV0l(X)E$mn%F18;5VaW_W=-L!I+)=a*->?M>7MQH8EW^Ib z6K;b??nBCi^_lCICTf26x^7&0oP3FUg5AsfO zjQq$A=tJDjaSZa{Y=ZN5E0;aX`RC>330_rImArM#GmalWF0z7x0$B%Q!v|yEZt<_P zvop|t^5lv7WVkNW=lm?!AL#STgG}xg9pjw1e=sIR^PKj7+NICAa4&G3HRcr+74oLj zPc7Be)uK;-iK*+$+U~_X)D>3FyG7QN`<(OA7@RwIPB2GDN6oHXy9AT@1oh}+Wo4z| z7{Ln$Kvz85?{!T_9@FB#Gd2C)wylozTFHB4GC^TLxYTIY%X8E zEOK%`efpGno%EZVn?#TMmvgt=Q(^!a^YJ!~i|VkZ4P&giA9Gi7FmF=s_V)IGn>pFB zW5=Zb@#9Ccckf=&LvAEBIK&5cu9*KFl;>8)yUO)b>~vorK73emNBVH~>{;{p@nhi{ zA0IdM_4T65T$RULaKMa>jftFbpuXn4I(K4Qu1Q<}I}<<0X-AyG!a}LJpUKPe=+PsyapOjj zQ>XFIMv=dK`7)3(Z+1A{cECSV{51}Yfu3FN$G*Nk;o%yPmocXN_3PIn=UJhgGWxGL zTHATM@lUw_9DO-wJj2Aje*JndPmPP-QNzQ-X6x3ifnV;vcktZxzXN%~^QZc(5hIx= z`FHQ$ZMeU=2D;7LDSaOCcf}&&^H#{ zFAk@>_k;u7z2rvWf6}z~Cu~bxy^Gl9KIa;6-mL5D>V#YOM54WCF~jcu z270D1HC!SuKRFY{#l^zEY}qoo^TYm!xcUD6NMd}F17Lhg{t>q4e4rb=3EQ@9V_qQq z&CSg+X8&Uoo;!=D>#O+(^PhzI*Gw@Wj^-byPoI{%cE^q#!msiKzH=XrTg-6&#TX>Y zKgYv3?DH%#7QB}k4=p@%Y;!Duop8f8QT_=t`7|G8{;l~4b3u8R+<5RT@J-;|$G1Jq z?dXQ{@1H|lwi{IHL-_wgaNtXDcF|@``9?^t&)V|x9TUGD8Dk#Ky93ftLw!i}|HatK zzYS{s6ESCEVO#!@l+*h1wf|r0iu%BQG2&g%wR5pQ*QPG~VSX9pxM;hW#QoA2{2N%s reBkZ}F8{y(Mq%zS%)&Mb-x9gcp`Y)7yJyT1e{X(|!1oAz>k;@5pB}e3 literal 15086 zcmdU$dvI0N6~+%mMW^HF)aie<(#l)KAczP)5Uf=cw6=m3TPli=nQB#Z9BGw^w$@fD zTD3AGSUbg0LE2g$qoPJFibzNx;UUieA-nHX8EKC4z@Gof&-l`p-JO%s%vagb zlL2ole(+s%UWKh(wbvf_^*ZZcRBrPmXWR`dec54M0dE?=%j+&2FHGNJQ=i*xcl>gV zef04z>w8AIUq4qSh~cFT{PuHs)ZyBnEVr`q2Aem(-ijx#kJIhiFWrBRpSX9Ag*InS zovmB9&xV{|5pH)^ch`T6f%N!sGHBUjNtDe`j+Ti(OA(W(UgGrO&WQWp=`XcJW`P%I!aU|dPwxCXq$*Jc2MN{ zj^Ct_M;Xe(18*K0Q$^tksGH&^MKvO)D`^Z5yvXq7B>@tY1@|?grJ|(zGL=IHvU0YC z%7C+zXuN2rD3i>5(~*TtWXCoG>7tIJdqj<*e0Ah1k4$8vqZJ0e0~)FLaMnAD3EAjq zH6DU*#>o;pwytp*2ZT?;c5BqD|GU)KfB#ofouH6}{t;!>3fQGJQVuvB%#teyzRq@-`bWY-!y3PFZyM{SfHyqnP>9M*kI;EwxQsnr(l} zLA&$LHF5im&jZ$eXO`Quf7xV>jR%bI$io{ll}8skUHw@vTIqJ*y}B&4SG7kI-gHd1?KH|055kr)W|Pw;i3j#ulw`PyF2~8wnzLJKt4Lr&6>@+nbsNpO`o3CyWBpN ztwDI|&o$OfX{7h+QfhbKz1FHXHu?QCe_?~w?QZdHs%(7~$VaE!OIq0(Vg3B34IY%O zL8x5XXao8#vZB+g23*J}N~uC8ga@%OB?K4+BK9NC0~$$x5PPiB+t_Rwr)(s|Qf z*y77?+;hOMXK7i3jk;#JZ_g6%QrmCd+HB03h&`H?;p!B`ZvW1dpH8O_(6O_w#mDgW zJ3DQ#>^IU`o2JRGB+QyEdp2U{M|7rTDjof_K{ze`x5iuVo@Msl`>8gjztK(K43=HI zdhK4@*L1*cx-r%sj+dFz%^1i!{v1B^G2R(tjKhKb7x`^JLAE^MbJ@hKK^fNFC9X4jn3V#k(t>0%u2UliV@14$Y?A9OFz>Mo}8~w8XhwJ>cbz8H)9?qSgT9;mU zaf`oCM$2dUcIz+tWA~p-yzFta|GC|71OC+QYO$Y=`ZCjA6RxxS9o>J}3)vH0e%6?A zc=Nbb{+@vT_dl$&Gj$eDIPQ>*uCyJb-?Tw@QCs^X1`~Sv>HPWW=ew;*=jXfcTANSZ zTiG8W8w3oA?JqD~A^YOi+g4j2?F9+z9&3MvFwiE6?N8PofBh2{@#Uh%Kz6#_(HjoR zrwxvX{q1lB7>>yKBZ7gp=q6&UGGB7FZ!{ksc#(lDCq8i;@X;3k)AMH(V1T28;=_La zwvvu!o@WO=Z{j}BJEhL^PN?#{PEd*Gbu5$|Qxbnm$l2H}NLpD0lg-&$irzjHr zLX`GXbScbFArV)FNjB_=sqQjUe42<1lL_I_|h^C6z zJ6DTpMSDa|0r8tO@+d=Dc;H3GVMLZ$6nX+WUhxRg4AFYgeo=Iu=K6*QUSuE(nFY<~ z%!pGtPOjqPMCf``gkLZh#-#bkLMF106&<#EI9ZAryVFIxMM-hxTMpUJiwa&_!+jw+ zv;%XE`L{@vFP=inqYIq{&vWsDow{Ll9~swo&O!qR zEVlcL*ITiCViQHfM=Z7OIRE^!BdsKX)Iply1jIH4FEjnKG zhA5*9AHVz@<&}*bZ~ZX)_3g2~*KBe)pWz?DFIc-{zb~gozT_*1hkU4+aexu5ejSJd zqFy;|0{kS8%Ma+nCj4^pTO{m%zuW-%m!`|Ff$!IaUG*)#AC5689N7qrejfz5!GE;q z@1kscejaT%Oy}#3o12_!d+hP*ME)IkFa6;Xn^RIJKUJFD|1noSgMNJy`^dlwX4m%E zvDkt+@lysr&g3f~9be`cjqwWk*rEZy--Gh8CGEoiE0`UAZ1EPb zB_aCw#+z1JgZ#Y&#=*_EtcvxuFt@pzn4mWXjJ3G1TK?-HgJbX9GvNU%n8DA!#(5%B z**594XWzh2y2`z2%kwp;U+utPq= zQP<|>BXl^y40iT3&UG$5Q4G$Z7ggG7y|*AxjYsv4hI-LIqpw?GWqKFm!cO6wEdOp_ z%~9_CTzFS^8+rN|9X>FFopUv3Q$oym)6jdZ`kuBW)a$MzPa{JRZ)I{B4aiw0>wFJ%7~UNB?R{YZqLAS>3`e2tScdrHVG}(1 zShW@DZC7|ckJB3480@*MrNf6O-?wAh&*7&J3K~Dir0)mm&06KMLv!`Tm$q6D%?;Yz z>1EG*MR$`fy!Nl{cG{u$b?I`he1h1GpTg&F(5H-nr=CgO9f5ED!g_zKIQ;CZmuYRS z)*4G-zq{qu`28*cZdX?~e+yba!+N;Ozf$+_TWVALYji(m46(KbTZPRpRsE9NIu36% zcI#(B`&Sr0zp)W!|NGG075g#wS&Xl9v^1*+ey)n{C)-OYGF|q|)~W=~Wx{`TMe)*Kx8EraAio8z?XPElz%FeO%;^eSeVa z&+j#6dg?93Y|T{{UYxNt{HE2lWxjFPegl7A_H!J5(iju$PtGP{oR9wb3hl+IdBGcy z(W48pb)xmd)(_jyoCOk{Uov4&;V-ox$Udm5PT554$De5};!d6L{zrBGp5WG{Y_f9X zMb9tvL89|x4!Qn#`J2}NXlT~^BkUsPNiG>V@>`uBIRvXbl=J+aL#~eteAoYMg>jw@ zhovj_*!kxbZ0m&U-0J-991%es=!1;@lO*^V8@&1XFnD|6>hSb)o7!XRIQ+5xlTaTV zCydjQ;LKKrKDci}mH&1N{9Acnc2y$Zh{KsF&gj1i)q(vOUtJ~{In(Kbf$|f*skcbg zItM&Eb#wTC33Bph&~UY^{WW`#udiL8W0;*>#n>9uV}=M@@c;V#KulF!e=xtX zV>v%?p5RQxxsJ0b=WBcf5Wh(yk1~{n2j0BzcjNH1Crucr5A)plBb{IDYNbK!homvC zDO2#hdK9PsSjat8BIY3xag`ny5trzp5iyMVqc=u+W#oA+#20#=ii_b;thY#djpTV% z#GMYsC4B3Ds9apkH~)hbiTV60Lovc*^p=nw!dJz22*0aWw7#w#T)U`={B}yWTUF4G Lu3f{Av{d-N$NdAy diff --git a/awx/ui/client/legacy-styles/ansible-ui.less b/awx/ui/client/legacy-styles/ansible-ui.less index 354e14a1d1..0d0bfc9928 100644 --- a/awx/ui/client/legacy-styles/ansible-ui.less +++ b/awx/ui/client/legacy-styles/ansible-ui.less @@ -962,10 +962,6 @@ input[type="checkbox"].checkbox-no-label { .checkbox-inline, .radio-inline { margin-right: 10px; } - - .checkbox-inline.stack-inline { - display: block; - } } .checkbox-options { @@ -976,7 +972,6 @@ input[type="checkbox"].checkbox-no-label { /* Display list actions next to search widget */ .list-actions { text-align: right; - margin-bottom: 20px; .fa-lg { vertical-align: -8%; @@ -1971,6 +1966,7 @@ tr td button i { } .list-actions { + margin-bottom: 20px; text-align: left; } @@ -2239,11 +2235,3 @@ a:hover { .dropdown-menu>li>a { padding: 3px 10px; } - -#scheduled-jobs-tab .List-header { - display: none; -} - -.ui-widget { - font-family: 'Open Sans'; -} diff --git a/awx/ui/client/legacy-styles/forms.less b/awx/ui/client/legacy-styles/forms.less index f452a028e9..ed66d8de04 100644 --- a/awx/ui/client/legacy-styles/forms.less +++ b/awx/ui/client/legacy-styles/forms.less @@ -173,26 +173,12 @@ } .Form-formGroup--fullWidth { - max-width: none !important; - width: 100% !important; + max-width: none; } .Form-formGroup--checkbox{ display: flex; - align-items: flex-start; -} - -.Form-checkbox--stacked { - label { - display: block; - } -} - -.Form-textUneditable { - .Form-textInput { - border: none; - padding: 0; - } + align-items: flex-end; } .Form-subForm { @@ -234,12 +220,14 @@ } .Form-textArea{ + background-color: @field-secondary-bg!important; + background-color: @field-secondary-bg!important; border-radius: 5px; color: @field-input-text; } .Form-textInput{ - height: 30px; + height: 30px!important; background-color: @field-secondary-bg!important; border-radius: 5px; border:1px solid @field-border; @@ -254,19 +242,6 @@ font-family: Menlo,Monaco,Consolas,"Courier New",monospace!important; } -.Form-alertblock { - margin: 20px 0; - font-size: 12px; - width: 100%; - padding: 15px; - padding-top: 10px; - margin-bottom: 15px; - border-radius: 4px; - border: 1px solid @login-notice-border; - background-color: @login-notice-bg; - color: @login-notice-text; -} - .ui-spinner{ height: 30px; background-color: @field-secondary-bg; @@ -307,7 +282,7 @@ } .Form-dropDown { - min-height: 30px !important; + height: 30px !important; border-radius: 5px !important; border:1px solid @field-border!important; color: @field-input-text!important; @@ -349,12 +324,6 @@ .select2-dropdown{ border:1px solid @field-border; - -} - -.select2-container--open .select2-dropdown--below { - margin-top: -1px; - border-top: 1px solid @field-border; } .Form-dropDown:focus{ @@ -458,10 +427,6 @@ input[type='radio']:checked:before { outline:none; } -.Form-inputLabelContainer { - width: 100%; - display: block !important; -} .Form-inputLabel{ text-transform: uppercase; color: @default-interface-txt; @@ -472,16 +437,6 @@ input[type='radio']:checked:before { .noselect; } -.Form-labelAction { - text-transform: uppercase; - font-weight: normal; - font-size: 0.8em; - padding-left:5px; - float: right; - margin-top: 3px; - .noselect; -} - .Form-buttons{ height: 30px; display: flex; @@ -539,6 +494,7 @@ input[type='radio']:checked:before { .Form-surveyButton { background-color: @default-link; + margin-right: 20px; color: @default-bg; text-transform: uppercase; padding-left:15px; @@ -582,8 +538,3 @@ input[type='radio']:checked:before { padding-right: 50px; } } - -.action_column { - float: right; - margin-bottom: 20px; -} diff --git a/awx/ui/client/legacy-styles/job-details.less b/awx/ui/client/legacy-styles/job-details.less index 6f19e70fe8..d4a21a9421 100644 --- a/awx/ui/client/legacy-styles/job-details.less +++ b/awx/ui/client/legacy-styles/job-details.less @@ -214,7 +214,7 @@ } #job-detail-container { - + .well { overflow: hidden; } @@ -276,8 +276,6 @@ overflow-x: hidden; overflow-y: auto; background-color: @white; - min-height: 40px; - .row { border-top: 1px solid @grey; } @@ -320,7 +318,7 @@ #play-section { .table-detail { - min-height: 40px; + height: 150px; } } @@ -423,6 +421,7 @@ table-layout: fixed; } #hosts-table-detail { + height: 150px; background-color: @white; } #hosts-table-detail table { diff --git a/awx/ui/client/lib/lrInfiniteScroll/.bower.json b/awx/ui/client/lib/lrInfiniteScroll/.bower.json deleted file mode 100644 index 7e27fd82a2..0000000000 --- a/awx/ui/client/lib/lrInfiniteScroll/.bower.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "lrInfiniteScroll", - "main": "lrInfiniteScroll.js", - "version": "1.0.0", - "homepage": "https://github.com/lorenzofox3/lrInfiniteScroll", - "authors": [ - "lorenzofox3 " - ], - "description": "angular directive to handle element scroll", - "keywords": [ - "angular", - "scroll", - "inifinite" - ], - "license": "MIT", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ], - "_release": "1.0.0", - "_resolution": { - "type": "version", - "tag": "1.0.0", - "commit": "c833e9d8ff56d6c66e2a21ed7f27ad840f159a8b" - }, - "_source": "https://github.com/lorenzofox3/lrInfiniteScroll.git", - "_target": "~1.0.0", - "_originalSource": "lrInfiniteScroll" -} \ No newline at end of file diff --git a/awx/ui/client/lib/lrInfiniteScroll/index.js b/awx/ui/client/lib/lrInfiniteScroll/index.js deleted file mode 100644 index 62f33e97b4..0000000000 --- a/awx/ui/client/lib/lrInfiniteScroll/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require('./lrInfiniteScroll'); -module.exports = 'lrInfiniteScroll'; diff --git a/awx/ui/client/lib/lrInfiniteScroll/lrInfiniteScroll.js b/awx/ui/client/lib/lrInfiniteScroll/lrInfiniteScroll.js index ac29895c2b..3268a94081 100644 --- a/awx/ui/client/lib/lrInfiniteScroll/lrInfiniteScroll.js +++ b/awx/ui/client/lib/lrInfiniteScroll/lrInfiniteScroll.js @@ -2,12 +2,13 @@ 'use strict'; var module = ng.module('lrInfiniteScroll', []); - module.directive('lrInfiniteScroll', ['$timeout', function (timeout) { + module.directive('lrInfiniteScroll', ['$log', '$timeout', function ($log, timeout) { return{ link: function (scope, element, attr) { var lengthThreshold = attr.scrollThreshold || 50, timeThreshold = attr.timeThreshold || 400, + direction = attr.direction || 'down', handler = scope.$eval(attr.lrInfiniteScroll), promise = null, lastRemaining = 9999; @@ -19,14 +20,14 @@ handler = ng.noop; } + $log.debug('lrInfiniteScroll: ' + attr.lrInfiniteScroll); + element.bind('scroll', function () { - var - remaining = element[0].scrollHeight - (element[0].clientHeight + element[0].scrollTop); - - //if we have reached the threshold and we scroll down - if (remaining < lengthThreshold && (remaining - lastRemaining) < 0) { - - //if there is already a timer running which has no expired yet we have to cancel it and restart the timer + var remaining = (direction === 'down') ? element[0].scrollHeight - (element[0].clientHeight + element[0].scrollTop) : element[0].scrollTop; + // if we have reached the threshold and we scroll down + if ((direction === 'down' && remaining < lengthThreshold && (remaining - lastRemaining) < 0) || + direction === 'up' && remaining < lengthThreshold) { + //if there is already a timer running which has not expired yet we have to cancel it and restart the timer if (promise !== null) { timeout.cancel(promise); } diff --git a/awx/ui/client/src/about/about.controller.js b/awx/ui/client/src/about/about.controller.js index 90824532db..678b3ba1ff 100644 --- a/awx/ui/client/src/about/about.controller.js +++ b/awx/ui/client/src/about/about.controller.js @@ -1,5 +1,5 @@ export default - ['$scope', '$state', 'ConfigService', function($scope, $state, ConfigService){ + ['$scope', '$state', 'CheckLicense', function($scope, $state, CheckLicense){ var processVersion = function(version){ // prettify version & calculate padding // e,g 3.0.0-0.git201602191743/ -> 3.0.0 @@ -16,10 +16,10 @@ export default return paddedStr; }; var init = function(){ - ConfigService.getConfig() - .then(function(config){ - $scope.subscription = config.license_info.subscription_name; - $scope.version = processVersion(config.version); + CheckLicense.get() + .then(function(res){ + $scope.subscription = res.data.license_info.subscription_name; + $scope.version = processVersion(res.data.version); $('#about-modal').modal('show'); }); }; diff --git a/awx/ui/client/src/access/addPermissions/addPermissions.controller.js b/awx/ui/client/src/access/addPermissions/addPermissions.controller.js index 75177cc308..938b47985e 100644 --- a/awx/ui/client/src/access/addPermissions/addPermissions.controller.js +++ b/awx/ui/client/src/access/addPermissions/addPermissions.controller.js @@ -30,25 +30,25 @@ export default ['$rootScope', '$scope', 'GetBasePath', 'Rest', '$q', 'Wait', 'Pr // array for all possible roles for the object scope.roles = Object - .keys(scope.object.summary_fields.object_roles) + .keys(scope.object.summary_fields.roles) .map(function(key) { return { value: scope.object.summary_fields - .object_roles[key].id, + .roles[key].id, label: scope.object.summary_fields - .object_roles[key].name }; + .roles[key].name }; }); // TODO: get working with api // array w roles and descriptions for key scope.roleKey = Object - .keys(scope.object.summary_fields.object_roles) + .keys(scope.object.summary_fields.roles) .map(function(key) { return { name: scope.object.summary_fields - .object_roles[key].name, + .roles[key].name, description: scope.object.summary_fields - .object_roles[key].description }; + .roles[key].description }; }); scope.showKeyPane = false; diff --git a/awx/ui/client/src/access/addPermissions/addPermissions.partial.html b/awx/ui/client/src/access/addPermissions/addPermissions.partial.html index 85fd03d7f9..5d0d4f01b9 100644 --- a/awx/ui/client/src/access/addPermissions/addPermissions.partial.html +++ b/awx/ui/client/src/access/addPermissions/addPermissions.partial.html @@ -41,11 +41,11 @@
- +
- +
diff --git a/awx/ui/client/src/access/addPermissions/addPermissionsList/addPermissionsList.directive.js b/awx/ui/client/src/access/addPermissions/addPermissionsList/addPermissionsList.directive.js index 6722fac853..6342ec0b8d 100644 --- a/awx/ui/client/src/access/addPermissions/addPermissionsList/addPermissionsList.directive.js +++ b/awx/ui/client/src/access/addPermissions/addPermissionsList/addPermissionsList.directive.js @@ -13,7 +13,6 @@ export default return { restrict: 'E', scope: { - allSelected: '=' }, template: "
", link: function(scope, element, attrs, ctrl) { @@ -51,23 +50,6 @@ export default PaginateInit({ scope: scope, list: list, url: url, pageSize: 5 }); - if (scope.removePostRefresh) { - scope.removePostRefresh(); - } - scope.removePostRefresh = scope.$on('PostRefresh', function () { - if(scope.allSelected && scope.allSelected.length > 0) { - // We need to check to see if any of the selected items are now in our list! - for(var i=0; i { - return Boolean(attrs.teamRoleList) === Boolean(role.team_id); + return !!attrs.teamRoleList == !!role.team_id; }) .sort((a, b) => { if (a.name diff --git a/awx/ui/client/src/activity-stream/activitystream.route.js b/awx/ui/client/src/activity-stream/activitystream.route.js index 06977c591d..a7e1da313f 100644 --- a/awx/ui/client/src/activity-stream/activitystream.route.js +++ b/awx/ui/client/src/activity-stream/activitystream.route.js @@ -18,26 +18,25 @@ export default { label: "ACTIVITY STREAM" }, resolve: { - features: ['FeaturesService', 'ProcessErrors', '$state', '$rootScope', - function(FeaturesService, ProcessErrors, $state, $rootScope) { - var features = FeaturesService.get(); - if(features){ + features: ['FeaturesService', 'ProcessErrors', '$state', function(FeaturesService, ProcessErrors, $state) { + FeaturesService.get() + .then(function(features) { if(FeaturesService.featureEnabled('activity_streams')) { + // Good to go - pass the features along to the controller. return features; } else { + // The activity stream feature isn't enabled. Take the user + // back to the dashboard $state.go('dashboard'); } - } - $rootScope.featuresConfigured.promise.then(function(features){ - if(features){ - if(FeaturesService.featureEnabled('activity_streams')) { - return features; - } - else { - $state.go('dashboard'); - } - } + }) + .catch(function (response) { + ProcessErrors(null, response.data, response.status, null, { + hdr: 'Error!', + msg: 'Failed to get feature info. GET returned status: ' + + response.status + }); }); }], subTitle: diff --git a/awx/ui/client/src/activity-stream/streamDropdownNav/stream-dropdown-nav.directive.js b/awx/ui/client/src/activity-stream/streamDropdownNav/stream-dropdown-nav.directive.js index 229c3d4271..c9047422f4 100644 --- a/awx/ui/client/src/activity-stream/streamDropdownNav/stream-dropdown-nav.directive.js +++ b/awx/ui/client/src/activity-stream/streamDropdownNav/stream-dropdown-nav.directive.js @@ -21,7 +21,7 @@ export default ['templateUrl', function(templateUrl) { {label: 'Inventories', value: 'inventory'}, {label: 'Inventory Scripts', value: 'inventory_script'}, {label: 'Job Templates', value: 'job_template'}, - {label: 'Jobs', value: 'job'}, + {label: 'Management Jobs', value: 'management_job'}, {label: 'Organizations', value: 'organization'}, {label: 'Projects', value: 'project'}, {label: 'Schedules', value: 'schedule'}, diff --git a/awx/ui/client/src/inventories/manage/adhoc/adhoc.controller.js b/awx/ui/client/src/adhoc/adhoc.controller.js similarity index 94% rename from awx/ui/client/src/inventories/manage/adhoc/adhoc.controller.js rename to awx/ui/client/src/adhoc/adhoc.controller.js index 7f67d81936..4ccf56ca54 100644 --- a/awx/ui/client/src/inventories/manage/adhoc/adhoc.controller.js +++ b/awx/ui/client/src/adhoc/adhoc.controller.js @@ -9,8 +9,8 @@ * @name controllers.function:Adhoc * @description This controller controls the adhoc form creation, command launching and navigating to standard out after command has been succesfully ran. */ -function adhocController($q, $scope, $location, $stateParams, - $state, CheckPasswords, PromptForPasswords, CreateLaunchDialog, CreateSelect2, adhocForm, +function adhocController($q, $scope, $rootScope, $location, $stateParams, + $state, CheckPasswords, PromptForPasswords, CreateLaunchDialog, adhocForm, GenerateForm, Rest, ProcessErrors, ClearScope, GetBasePath, GetChoices, KindChange, LookUpInit, CredentialList, Empty, Wait) { @@ -23,7 +23,7 @@ function adhocController($q, $scope, $location, $stateParams, this.privateFn = privateFn; var id = $stateParams.inventory_id, - hostPattern = $stateParams.pattern; + hostPattern = $rootScope.hostPatterns || "all"; // note: put any urls that the controller will use in here!!!! privateFn.setAvailableUrls = function() { @@ -68,17 +68,6 @@ function adhocController($q, $scope, $location, $stateParams, if (formReadyPromise === 2) { privateFn.setFieldDefaults($scope.adhoc_verbosity_options, $scope.forks_field.default); - - CreateSelect2({ - element: '#adhoc_module_name', - multiple: false - }); - - CreateSelect2({ - element: '#adhoc_verbosity', - multiple: false - }); - Wait('stop'); } } @@ -113,6 +102,7 @@ function adhocController($q, $scope, $location, $stateParams, privateFn.instantiateHostPatterns = function(hostPattern) { $scope.limit = hostPattern; $scope.providedHostPatterns = $scope.limit; + delete $rootScope.hostPatterns; }; // call helpers to initialize lookup and select fields through get @@ -305,8 +295,8 @@ function adhocController($q, $scope, $location, $stateParams, } -export default ['$q', '$scope', '$location', '$stateParams', - '$state', 'CheckPasswords', 'PromptForPasswords', 'CreateLaunchDialog', 'CreateSelect2', - 'adhocForm', 'GenerateForm', 'Rest', 'ProcessErrors', 'ClearScope', 'GetBasePath', +export default ['$q', '$scope', '$rootScope', '$location', '$stateParams', + '$state', 'CheckPasswords', 'PromptForPasswords', 'CreateLaunchDialog', 'adhocForm', + 'GenerateForm', 'Rest', 'ProcessErrors', 'ClearScope', 'GetBasePath', 'GetChoices', 'KindChange', 'LookUpInit', 'CredentialList', 'Empty', 'Wait', adhocController]; diff --git a/awx/ui/client/src/inventories/manage/adhoc/adhoc.form.js b/awx/ui/client/src/adhoc/adhoc.form.js similarity index 97% rename from awx/ui/client/src/inventories/manage/adhoc/adhoc.form.js rename to awx/ui/client/src/adhoc/adhoc.form.js index 1934aa1341..44a5c3ba6d 100644 --- a/awx/ui/client/src/inventories/manage/adhoc/adhoc.form.js +++ b/awx/ui/client/src/adhoc/adhoc.form.js @@ -122,19 +122,20 @@ export default function() { dataContainer: "body" }, }, + buttons: { reset: { ngClick: 'formReset()', ngDisabled: true, label: 'Reset', - 'class': 'btn btn-sm Form-cancelButton' + 'class': 'Form-buttonDefault Form-button' }, launch: { label: 'Save', ngClick: 'launchJob()', ngDisabled: true, - 'class': 'btn btn-sm List-buttonSubmit' - } + 'class': 'Form-buttonDefault Form-button' + } }, related: {} diff --git a/awx/ui/client/src/inventories/manage/adhoc/adhoc.partial.html b/awx/ui/client/src/adhoc/adhoc.partial.html similarity index 100% rename from awx/ui/client/src/inventories/manage/adhoc/adhoc.partial.html rename to awx/ui/client/src/adhoc/adhoc.partial.html diff --git a/awx/ui/client/src/adhoc/adhoc.route.js b/awx/ui/client/src/adhoc/adhoc.route.js new file mode 100644 index 0000000000..c10d565c72 --- /dev/null +++ b/awx/ui/client/src/adhoc/adhoc.route.js @@ -0,0 +1,14 @@ +/************************************************* + * Copyright (c) 2015 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ + + import {templateUrl} from '../shared/template-url/template-url.factory'; + +export default { + route: '/adhoc', + name: 'inventoryManage.adhoc', + templateUrl: templateUrl('adhoc/adhoc'), + controller: 'adhocController' +}; diff --git a/awx/ui/client/src/adhoc/main.js b/awx/ui/client/src/adhoc/main.js new file mode 100644 index 0000000000..e854ce9f97 --- /dev/null +++ b/awx/ui/client/src/adhoc/main.js @@ -0,0 +1,10 @@ +import route from './adhoc.route'; +import adhocController from './adhoc.controller'; +import form from './adhoc.form'; + +export default angular.module('adhoc', []) + .controller('adhocController', adhocController) + .run(['$stateExtender', function($stateExtender) { + $stateExtender.addState(route); + }]) + .factory('adhocForm', form); diff --git a/awx/ui/client/src/app.js b/awx/ui/client/src/app.js index 40d9b1e419..6d5673a77b 100644 --- a/awx/ui/client/src/app.js +++ b/awx/ui/client/src/app.js @@ -47,12 +47,12 @@ import browserData from './browser-data/main'; import dashboard from './dashboard/main'; import moment from './shared/moment/main'; import templateUrl from './shared/template-url/main'; +import adhoc from './adhoc/main'; import login from './login/main'; import activityStream from './activity-stream/main'; import standardOut from './standard-out/main'; import JobTemplates from './job-templates/main'; import search from './search/main'; -import credentials from './credentials/main'; import {ProjectsList, ProjectsAdd, ProjectsEdit} from './controllers/Projects'; import OrganizationsList from './organizations/list/organizations-list.controller'; import OrganizationsAdd from './organizations/add/organizations-add.controller'; @@ -67,9 +67,9 @@ import './shared/Modal'; import './shared/prompt-dialog'; import './shared/directives'; import './shared/filters'; +import './shared/InventoryTree'; import './shared/Socket'; import './shared/features/main'; -import config from './shared/config/main'; import './login/authenticationServices/pendo/ng-pendo'; import footer from './footer/main'; import scheduler from './scheduler/main'; @@ -81,7 +81,6 @@ __deferLoadIfEnabled(); var tower = angular.module('Tower', [ //'ngAnimate', - 'lrInfiniteScroll', 'ngSanitize', 'ngCookies', about.name, @@ -100,6 +99,7 @@ var tower = angular.module('Tower', [ dashboard.name, moment.name, templateUrl.name, + adhoc.name, login.name, activityStream.name, footer.name, @@ -111,8 +111,6 @@ var tower = angular.module('Tower', [ JobTemplates.name, portalMode.name, search.name, - config.name, - credentials.name, 'ngToast', 'templates', 'Utilities', @@ -171,6 +169,7 @@ var tower = angular.module('Tower', [ 'StreamWidget', 'JobsHelper', 'InventoryGroupsHelpDefinition', + 'InventoryTree', 'CredentialsHelper', 'StreamListDefinition', 'HomeGroupListDefinition', @@ -216,10 +215,8 @@ var tower = angular.module('Tower', [ timeout: 4000 }); }]) - .config(['$stateProvider', '$urlRouterProvider', '$breadcrumbProvider', - '$urlMatcherFactoryProvider', - function ($stateProvider, $urlRouterProvider, $breadcrumbProvider, - $urlMatcherFactoryProvider) { + .config(['$stateProvider', '$urlRouterProvider', '$breadcrumbProvider', '$urlMatcherFactoryProvider', + function ($stateProvider, $urlRouterProvider, $breadcrumbProvider, $urlMatcherFactoryProvider) { $urlMatcherFactoryProvider.strictMode(false); $breadcrumbProvider.setOptions({ templateUrl: urlPrefix + 'partials/breadcrumb.html' @@ -227,7 +224,6 @@ var tower = angular.module('Tower', [ // route to the details pane of /job/:id/host-event/:eventId if no other child specified $urlRouterProvider.when('/jobs/*/host-event/*', '/jobs/*/host-event/*/details'); - // $urlRouterProvider.otherwise("/home"); $urlRouterProvider.otherwise(function($injector){ var $state = $injector.get("$state"); @@ -247,9 +243,10 @@ var tower = angular.module('Tower', [ label: "DASHBOARD" }, resolve: { - graphData: ['$q', 'jobStatusGraphData', function($q, jobStatusGraphData) { + graphData: ['$q', 'jobStatusGraphData', 'FeaturesService', function($q, jobStatusGraphData, FeaturesService) { return $q.all({ jobStatus: jobStatusGraphData.get("month", "all"), + features: FeaturesService.get() }); }] } @@ -275,7 +272,7 @@ var tower = angular.module('Tower', [ }). state('projects', { - url: '/projects?{status}', + url: '/projects', templateUrl: urlPrefix + 'partials/projects.html', controller: ProjectsList, data: { @@ -303,13 +300,8 @@ var tower = angular.module('Tower', [ controller: ProjectsEdit, data: { activityStreamId: 'id' - }, - ncyBreadcrumb: { - parent: 'projects', - label: '{{name}}' } }). - state('projectOrganizations', { url: '/projects/:project_id/organizations', templateUrl: urlPrefix + 'partials/projects.html', @@ -321,7 +313,6 @@ var tower = angular.module('Tower', [ templateUrl: urlPrefix + 'partials/projects.html', controller: OrganizationsAdd }). - state('teams', { url: '/teams', templateUrl: urlPrefix + 'partials/teams.html', @@ -352,10 +343,6 @@ var tower = angular.module('Tower', [ controller: TeamsEdit, data: { activityStreamId: 'team_id' - }, - ncyBreadcrumb: { - parent: "teams", - label: "{{team_obj.name}}" } }). @@ -440,7 +427,7 @@ var tower = angular.module('Tower', [ }, ncyBreadcrumb: { parent: "credentials", - label: "{{credential_obj.name}}" + label: "EDIT CREDENTIAL" } }). @@ -474,10 +461,6 @@ var tower = angular.module('Tower', [ controller: UsersEdit, data: { activityStreamId: 'user_id' - }, - ncyBreadcrumb: { - parent: "users", - label: "{{user_obj.username}}" } }). @@ -523,16 +506,10 @@ var tower = angular.module('Tower', [ }]); }]) - .run(['$q', '$compile', '$cookieStore', '$rootScope', '$log', - 'CheckLicense', '$location', 'Authorization', 'LoadBasePaths', 'Timer', - 'ClearScope', 'Socket', 'LoadConfig', 'Store', - 'ShowSocketHelp', 'pendoService', 'Prompt', 'Rest', 'Wait', - 'ProcessErrors', '$state', 'GetBasePath', 'ConfigService', - 'FeaturesService', - function ($q, $compile, $cookieStore, $rootScope, $log, CheckLicense, - $location, Authorization, LoadBasePaths, Timer, ClearScope, Socket, - LoadConfig, Store, ShowSocketHelp, pendoService, Prompt, Rest, Wait, - ProcessErrors, $state, GetBasePath, ConfigService, FeaturesService) { + .run(['$q', '$compile', '$cookieStore', '$rootScope', '$log', 'CheckLicense', '$location', 'Authorization', 'LoadBasePaths', 'Timer', 'ClearScope', 'Socket', + 'LoadConfig', 'Store', 'ShowSocketHelp', 'pendoService', 'Prompt', 'Rest', 'Wait', 'ProcessErrors', '$state', 'GetBasePath', + function ($q, $compile, $cookieStore, $rootScope, $log, CheckLicense, $location, Authorization, LoadBasePaths, Timer, ClearScope, Socket, + LoadConfig, Store, ShowSocketHelp, pendoService, Prompt, Rest, Wait, ProcessErrors, $state, GetBasePath) { var sock; $rootScope.addPermission = function (scope) { $compile("")(scope); @@ -600,11 +577,11 @@ var tower = angular.module('Tower', [ Prompt({ hdr: `Remove role`, body: ` -
- Confirm the removal of the ${roleType} - ${roleName} - role associated with ${userName}. -
+
+ Confirm the removal of the ${roleType} + ${roleName} + role associated with ${userName}. +
`, action: action, actionText: 'REMOVE' @@ -630,11 +607,11 @@ var tower = angular.module('Tower', [ Prompt({ hdr: `Remove role`, body: ` -
- Confirm the removal of the ${roleType} - ${roleName} - role associated with the ${teamName} team. -
+
+ Confirm the removal of the ${roleType} + ${roleName} + role associated with the ${teamName} team. +
`, action: action, actionText: 'REMOVE' @@ -760,7 +737,7 @@ var tower = angular.module('Tower', [ control_socket.on("limit_reached", function(data) { $log.debug(data.reason); $rootScope.sessionTimer.expireSession('session_limit'); - $state.go('signOut'); + $location.url('/login'); }); } openSocket(); @@ -775,7 +752,9 @@ var tower = angular.module('Tower', [ $rootScope.$on("$stateChangeStart", function (event, next, nextParams, prev) { - + if (next.name !== 'signOut'){ + CheckLicense.notify(); + } $rootScope.$broadcast("closePermissionsModal"); $rootScope.$broadcast("closeUsersModal"); // this line removes the query params attached to a route @@ -826,15 +805,15 @@ var tower = angular.module('Tower', [ if ($rootScope.current_user === undefined || $rootScope.current_user === null) { Authorization.restoreUserInfo(); //user must have hit browser refresh } - if (next && (next.name !== "signIn" && next.name !== "signOut" && next.name !== "license")) { - // if not headed to /login or /logout, then check the license - CheckLicense.test(event); - } } activateTab(); }); $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState) { + // catch license expiration notifications immediately after user logs in, redirect + if (fromState.name === 'signIn'){ + CheckLicense.notify(); + } if(fromState.name === 'license' && toParams.hasOwnProperty('licenseMissing')){ $rootScope.licenseMissing = toParams.licenseMissing; @@ -872,27 +851,17 @@ var tower = angular.module('Tower', [ // User not authenticated, redirect to login page $rootScope.sessionExpired = false; $cookieStore.put('sessionExpired', false); - $rootScope.configReady = true; $location.path('/login'); } else { // If browser refresh, set the user_is_superuser value $rootScope.user_is_superuser = Authorization.getUserInfo('is_superuser'); // state the user refreshes we want to open the socket, except if the user is on the login page, which should happen after the user logs in (see the AuthService module for that call to OpenSocket) if(!_.contains($location.$$url, '/login')){ - ConfigService.getConfig().then(function(){ - Timer.init().then(function(timer){ - $rootScope.sessionTimer = timer; - $rootScope.$emit('OpenSocket'); - pendoService.issuePendoIdentity(); - CheckLicense.test(); - FeaturesService.get(); - if($location.$$path === "/home" && $state.current && $state.current.name === ""){ - $state.go('dashboard'); - } - else if($location.$$path === "/portal" && $state.current && $state.current.name === ""){ - $state.go('portalMode'); - } - }); + Timer.init().then(function(timer){ + $rootScope.sessionTimer = timer; + $rootScope.$emit('OpenSocket'); + pendoService.issuePendoIdentity(); + CheckLicense.notify(); }); } } @@ -927,11 +896,7 @@ var tower = angular.module('Tower', [ // create a promise that will resolve state $AnsibleConfig is loaded $rootScope.loginConfig = $q.defer(); } - if (!$rootScope.featuresConfigured) { - // create a promise that will resolve when features are loaded - $rootScope.featuresConfigured = $q.defer(); - } - $rootScope.licenseMissing = true; + //the authorization controller redirects to the home page automatcially if there is no last path defined. in order to override // this, set the last path to /portal for instances where portal is visited for the first time. $rootScope.lastPath = ($location.path() === "/portal") ? 'portal' : undefined; diff --git a/awx/ui/client/src/bread-crumb/bread-crumb.block.less b/awx/ui/client/src/bread-crumb/bread-crumb.block.less index 58aa900c65..7ec5a6142b 100644 --- a/awx/ui/client/src/bread-crumb/bread-crumb.block.less +++ b/awx/ui/client/src/bread-crumb/bread-crumb.block.less @@ -31,26 +31,14 @@ .BreadCrumb-menuLink:hover { color: @bc-link-icon-focus; } -.BreadCrumb-menuLinkImage { - font-size: 18px; - color: @bc-link-icon; - flex: initial; - - &:hover { - color: @default-link-hov; - } -} .BreadCrumb-menuLink.BreadCrumb-menuLinkActive { color: @bc-link-icon-focus; - - .BreadCrumb-menuLinkImage { - color: @bc-link-icon-focus; - - &:hover { - color: @default-link-hov - } - } } +.BreadCrumb-menuLinkImage { + font-size: 18px; + flex: initial; +} + .BreadCrumb-list { padding: 0px 20px; list-style: none; diff --git a/awx/ui/client/src/bread-crumb/bread-crumb.directive.js b/awx/ui/client/src/bread-crumb/bread-crumb.directive.js index 3331a10736..bfb11e42cc 100644 --- a/awx/ui/client/src/bread-crumb/bread-crumb.directive.js +++ b/awx/ui/client/src/bread-crumb/bread-crumb.directive.js @@ -1,6 +1,5 @@ export default - ['templateUrl', '$state', 'FeaturesService', 'ProcessErrors','$rootScope', 'Store', 'Empty', - function(templateUrl, $state, FeaturesService, ProcessErrors, $rootScope, Store, Empty) { + [ 'templateUrl', '$state', 'FeaturesService', 'ProcessErrors', 'Store', 'Empty', function(templateUrl, $state, FeaturesService, ProcessErrors, Store, Empty) { return { restrict: 'E', templateUrl: templateUrl('bread-crumb/bread-crumb'), @@ -13,40 +12,40 @@ export default scope.toggleActivityStream = function() { - // If the user is not already on the activity stream then they want to navigate to it - if(!scope.activityStreamActive) { - var stateGoParams = {}; + // If the user is not already on the activity stream then they want to navigate to it + if(!scope.activityStreamActive) { + var stateGoParams = {}; - if(streamConfig && streamConfig.activityStream) { - if(streamConfig.activityStreamTarget) { - stateGoParams.target = streamConfig.activityStreamTarget; - } - if(streamConfig.activityStreamId) { - stateGoParams.id = $state.params[streamConfig.activityStreamId]; - } + if(streamConfig && streamConfig.activityStream) { + if(streamConfig.activityStreamTarget) { + stateGoParams.target = streamConfig.activityStreamTarget; + } + if(streamConfig.activityStreamId) { + stateGoParams.id = $state.params[streamConfig.activityStreamId]; } - - $state.go('activityStream', stateGoParams); } - // The user is navigating away from the activity stream - take them back from whence they came + + $state.go('activityStream', stateGoParams); + } + // The user is navigating away from the activity stream - take them back from whence they came + else { + // Pull the previous state out of local storage + var previousState = Store('previous_state'); + + if(previousState && !Empty(previousState.name)) { + $state.go(previousState.name, previousState.fromParams); + } else { - // Pull the previous state out of local storage - var previousState = Store('previous_state'); - - if(previousState && !Empty(previousState.name)) { - $state.go(previousState.name, previousState.fromParams); - } - else { - // If for some reason something went wrong (like local storage was wiped, etc) take the - // user back to the dashboard - $state.go('dashboard'); - } - + // If for some reason something went wrong (like local storage was wiped, etc) take the + // user back to the dashboard + $state.go('dashboard'); } - }; + } - scope.$on("$stateChangeStart", function updateActivityStreamButton(event, toState, toParams, fromState, fromParams) { + }; + + scope.$on("$stateChangeSuccess", function updateActivityStreamButton(event, toState, toParams, fromState, fromParams) { if(fromState && !Empty(fromState.name)) { // Go ahead and attach the from params to the state object so that it can all be stored together @@ -66,13 +65,26 @@ export default // point. We use the get() function call here just in case the features aren't available. // The get() function will only fire off the server call if the features aren't already // attached to the $rootScope. - var features = FeaturesService.get(); - if(features){ + + FeaturesService.get() + .then(function() { scope.loadingLicense = false; scope.activityStreamActive = (toState.name === 'activityStream') ? true : false; - scope.activityStreamTooltip = (toState.name === 'activityStream') ? 'Hide Activity Stream' : 'View Activity Stream'; - scope.showActivityStreamButton = (FeaturesService.featureEnabled('activity_streams') || toState.name ==='activityStream') ? true : false; - } + scope.showActivityStreamButton = (FeaturesService.featureEnabled('activity_streams') || toState.name === 'activityStream') ? true : false; + var licenseInfo = FeaturesService.getLicenseInfo(); + scope.licenseType = licenseInfo ? licenseInfo.license_type : null; + if (!licenseInfo) { + console.warn("License info not loaded correctly"); + } + }) + .catch(function (response) { + ProcessErrors(null, response.data, response.status, null, { + hdr: 'Error!', + msg: 'Failed to get feature info. GET returned status: ' + + response.status + }); + }); + } else { @@ -81,16 +93,6 @@ export default } }); - // scope.$on('featuresLoaded', function(){ - $rootScope.featuresConfigured.promise.then(function(features){ - // var features = FeaturesService.get(); - if(features){ - scope.loadingLicense = false; - scope.activityStreamActive = ($state.current.name === 'activityStream') ? true : false; - scope.activityStreamTooltip = ($state.current.name === 'activityStream') ? 'Hide Activity Stream' : 'View Activity Stream'; - scope.showActivityStreamButton = (FeaturesService.featureEnabled('activity_streams') || $state.current.name ==='activityStream') ? true : false; - } - }); } }; }]; diff --git a/awx/ui/client/src/bread-crumb/bread-crumb.partial.html b/awx/ui/client/src/bread-crumb/bread-crumb.partial.html index 94018460b8..4d51219070 100644 --- a/awx/ui/client/src/bread-crumb/bread-crumb.partial.html +++ b/awx/ui/client/src/bread-crumb/bread-crumb.partial.html @@ -1,15 +1,14 @@ \n"; + + defaultUrl = GetBasePath('hosts') + host_id + '/'; + scope = generator.inject(null, { mode: 'edit', modal: true, related: false, html: html }); + + for (i=0; i < scope.hosts.length; i++) { + if (scope.hosts[i].id === host_id) { + scope.host = scope.hosts[i]; + } + } + + scope.selectedGroups = null; + scope.assignedGroups = null; + scope.leftButtonDisabled = true; + scope.rightButtonDisabled = true; + + scope.formModalActionLabel = 'Save'; + //scope.formModalHeader = 'Host Groups'; + scope.formModalHeader = scope.host.name + ' - Groups'; + scope.formModalCancelShow = true; + scope.formModalActionDisabled = true; + + $('#form-modal .btn-none').removeClass('btn-none').addClass('btn-success'); + + if (scope.hostGroupChangeRemove) { + scope.hostGroupChangeRemove(); + } + scope.hostGroupChangeRemove = scope.$on('hostGroupChange', function() { + actions.pop(); + if (actions.length === 0) { + postAction = function() { + setTimeout(function() { Wait('stop'); }, 500); + }; + HostsReload({ scope: scope, inventory_id: inventory_id, group_id: scope.group_id , action: postAction }); + } + }); + + // Save changes + scope.formModalAction = function() { + var i, j, found; + + $('#form-modal').modal('hide'); + Wait('start'); + + // removed host from deleted groups + for (i=0; i < scope.original_groups.length; i++) { + found = false; + for (j=0; j < scope.host_groups.length; j++) { + if (scope.original_groups[i].id === scope.host_groups[j].id) { + found = true; + } + } + if (!found) { + // group was removed + actions.push({ group_id: scope.original_groups[i].id , action: 'delete' }); + Rest.setUrl(GetBasePath('groups') + scope.original_groups[i].id + '/hosts/'); + Rest.post({ id: host_id, disassociate: 1 }) + .success( function() { + scope.$emit('hostGroupChange'); + }) + .error( function(data, status) { + scope.$emit('hostGroupChange'); + ProcessErrors(scope, data, status, null, + { hdr: 'Error!', msg: 'Attempt to remove host from group ' + scope.original_groups[i].name + + ' failed. POST returned status: ' + status }); + }); + } + } + + // add host to new groups + for (i=0; i < scope.host_groups.length; i++) { + found = false; + for (j=0; j < scope.original_groups.length; j++) { + if (scope.original_groups[j].id === scope.host_groups[i].id) { + found = true; + } + } + if (!found) { + // group was added + actions.push({ group_id: scope.host_groups[i].id , action: 'add' }); + Rest.setUrl(GetBasePath('groups') + scope.host_groups[i].id + '/hosts/'); + Rest.post(scope.host) + .success( function() { + scope.$emit('hostGroupChange'); + }) + .error( function(data, status) { + scope.$emit('hostGroupChange'); + ProcessErrors(scope, data, status, null, + { hdr: 'Error!', msg: 'Attempt to add host to group ' + scope.host_groups[i].name + + ' failed. POST returned status: ' + status }); + }); + } + } + }; + + scope.leftChange = function() { + // Select/deselect on available groups list + if (scope.selectedGroups !== null && scope.selectedGroups.length > 0) { + scope.assignedGroups = null; + scope.leftButtonDisabled = true; + scope.rightButtonDisabled = false; + } + else { + scope.rightButtonDisabled = true; + } + }; + + scope.rightChange = function() { + // Select/deselect made on host groups list + if (scope.assignedGroups !== null && scope.assignedGroups.length > 0) { + scope.selectedGroups = null; + scope.leftButtonDisabled = false; + scope.rightButtonDisabled = true; + } + else { + scope.leftButtonDisabled = true; + } + }; + + scope.moveLeft = function() { + // Remove selected groups from the list of assigned groups + + var i, j, found, placed; + + for (i=0; i < scope.assignedGroups.length; i++){ + for (j=0 ; j < scope.host_groups.length; j++) { + if (scope.host_groups[j].id === scope.assignedGroups[i].id) { + scope.host_groups.splice(j,1); + break; + } + } + } + for (i=0; i < scope.assignedGroups.length; i++){ + found = false; + for (j=0; j < scope.available_groups.length && !found; j++){ + if (scope.available_groups[j].id === scope.assignedGroups[i].id) { + found=true; + } + } + if (!found) { + placed = false; + for (j=0; j < scope.available_groups.length && !placed; j++){ + if (j === 0 && scope.assignedGroups[i].name.toLowerCase() < scope.available_groups[j].name.toLowerCase()) { + // prepend to the beginning of the array + placed=true; + scope.available_groups.unshift(scope.assignedGroups[i]); + } + else if (j + 1 < scope.available_groups.length) { + if (scope.assignedGroups[i].name.toLowerCase() > scope.available_groups[j].name.toLowerCase() && + scope.assignedGroups[i].name.toLowerCase() < scope.available_groups[j + 1].name.toLowerCase() ) { + // insert into the middle of the array + placed = true; + scope.available_groups.splice(j + 1, 0, scope.assignedGroups[i]); + } + } + } + if (!placed) { + // append to the end of the array + scope.available_groups.push(scope.assignedGroups[i]); + } + } + } + scope.assignedGroups = null; + scope.leftButtonDisabled = true; + scope.rightButtonDisabled = true; + scope.formModalActionDisabled = false; + }; + + scope.moveRight = function() { + // Remove selected groups from list of available groups + + var i, j, found, placed; + + for (i=0; i < scope.selectedGroups.length; i++){ + for (j=0 ; j < scope.available_groups.length; j++) { + if (scope.available_groups[j].id === scope.selectedGroups[i].id) { + scope.available_groups.splice(j,1); + break; + } + } + } + for (i=0; i < scope.selectedGroups.length; i++){ + found = false; + for (j=0; j < scope.host_groups.length && !found; j++){ + if (scope.host_groups[j].id === scope.selectedGroups[i].id) { + found=true; + } + } + if (!found) { + placed = false; + for (j=0; j < scope.host_groups.length && !placed; j++) { + if (j === 0 && scope.selectedGroups[i].name.toLowerCase() < scope.host_groups[j].name.toLowerCase()) { + // prepend to the beginning of the array + placed=true; + scope.host_groups.unshift(scope.selectedGroups[i]); + } + else if (j + 1 < scope.host_groups.length) { + if (scope.selectedGroups[i].name.toLowerCase() > scope.host_groups[j].name.toLowerCase() && + scope.selectedGroups[i].name.toLowerCase() < scope.host_groups[j + 1].name.toLowerCase() ) { + // insert into the middle of the array + placed = true; + scope.host_groups.splice(j + 1, 0, scope.selectedGroups[i]); + } + } + } + if (!placed) { + // append to the end of the array + scope.host_groups.push(scope.selectedGroups[i]); + } + } + } + scope.selectedGroups = null; + scope.leftButtonDisabled = true; + scope.rightButtonDisabled = true; + scope.formModalActionDisabled = false; + }; + + + // Load the host's current list of groups + scope.host_groups = []; + scope.original_groups = []; + scope.available_groups = []; + Rest.setUrl(scope.host.related.groups + '?order_by=name'); + Rest.get() + .success( function(data) { + var i, j, found; + for (i=0; i < data.results.length; i++) { + scope.host_groups.push({ + id: data.results[i].id, + name: data.results[i].name, + description: data.results[i].description + }); + scope.original_groups.push({ + id: data.results[i].id, + name: data.results[i].name, + description: data.results[i].description + }); + } + for (i=0; i < scope.inventory_groups.length; i++) { + found = false; + for (j=0; j < scope.host_groups.length; j++) { + if (scope.inventory_groups[i].id === scope.host_groups[j].id) { + found = true; + } + } + if (!found) { + scope.available_groups.push(scope.inventory_groups[i]); + } + } + }) + .error( function(data, status) { + ProcessErrors(scope, data, status, null, + { hdr: 'Error!', msg: 'Failed to get current groups for host: ' + host_id + '. GET returned: ' + status }); + }); + + if (scope.removeHostsReload) { + scope.removeHostsReload(); + } + scope.removeHostsReload = scope.$on('hostsReload', function() { + HostsReload(params); + }); + + if (!scope.$$phase) { + scope.$digest(); + } + }; + }]); diff --git a/awx/ui/client/src/helpers/JobDetail.js b/awx/ui/client/src/helpers/JobDetail.js index f6c0ef60cc..df42b50328 100644 --- a/awx/ui/client/src/helpers/JobDetail.js +++ b/awx/ui/client/src/helpers/JobDetail.js @@ -784,6 +784,7 @@ export default url, play; scope.tasks = []; + if (scope.selectedPlay) { url = scope.job.url + 'job_tasks/?event_id=' + scope.selectedPlay; url += (scope.search_task_name) ? '&task__icontains=' + scope.search_task_name : ''; @@ -911,25 +912,16 @@ export default scope.tasks[idx].taskActiveClass = ''; } }); - if (scope.selectedTask !== null){ - params = { - parent: scope.selectedTask, - event__startswith: 'runner', - page_size: scope.hostResultsMaxRows, - order: 'host_name,counter', - }; - if (scope.search_host_status === 'failed'){ - params.failed = true; - } - JobDetailService.getRelatedJobEvents(scope.job.id, params).success(function(res){ - scope.hostResults = JobDetailService.processHostEvents(res.results); - scope.hostResultsLoading = false; - }); - } - else{ - scope.hostResults = []; + params = { + parent: scope.selectedTask, + event__startswith: 'runner', + page_size: scope.hostResultsMaxRows, + order: 'host_name,counter', + }; + JobDetailService.getRelatedJobEvents(scope.job.id, params).success(function(res){ + scope.hostResults = JobDetailService.processHostEvents(res.results); scope.hostResultsLoading = false; - } + }); }; }]) @@ -942,7 +934,7 @@ export default graph_data.push({ label: 'OK', value: count.ok.length, - color: '#5CB85C' + color: '#60D66F' }); } if (count.changed.length > 0) { @@ -987,19 +979,18 @@ export default job_detail_chart = nv.models.pieChart() .margin({bottom: 15}) .x(function(d) { - return d.label +': '+ Math.floor((d.value/total)*100) + "%"; + return d.label +': '+ Math.round((d.value/total)*100) + "%"; }) .y(function(d) { return d.value; }) - .showLabels(false) - .showLegend(true) + .showLabels(true) + .showLegend(false) .growOnHover(false) .labelThreshold(0.01) .tooltipContent(function(x, y) { return '

'+x+'

'+ '

' + Math.floor(y.replace(',','')) + ' HOSTS ' + '

'; }) .color(colors); - job_detail_chart.legend.rightAlign(false); - job_detail_chart.legend.margin({top: 5, right: 450, left:0, bottom: 0}); + d3.select(element.find('svg')[0]) .datum(dataset) .transition().duration(350) @@ -1009,15 +1000,19 @@ export default "font-style": "normal", "font-weight":400, "src": "url(/static/assets/OpenSans-Regular.ttf)", - "width": 600, + "width": 500, "height": 300, - "color": '#848992' }); - d3.select(element.find(".nv-noData")[0]) + + d3.select(element.find(".nv-label text")[0]) + .attr("class", "HostSummary-graph--successful") .style({ - "text-anchor": 'start' + "font-family": 'Open Sans', + "font-size": "16px", + "text-transform" : "uppercase", + "fill" : colors[0], + "src": "url(/static/assets/OpenSans-Regular.ttf)" }); - /* d3.select(element.find(".nv-label text")[1]) .attr("class", "HostSummary-graph--changed") .style({ @@ -1045,7 +1040,6 @@ export default "fill" : colors[3], "src": "url(/static/assets/OpenSans-Regular.ttf)" }); - */ return job_detail_chart; }; }]) diff --git a/awx/ui/client/src/helpers/JobTemplates.js b/awx/ui/client/src/helpers/JobTemplates.js index 29e9ff8d4c..90317a41a8 100644 --- a/awx/ui/client/src/helpers/JobTemplates.js +++ b/awx/ui/client/src/helpers/JobTemplates.js @@ -31,7 +31,7 @@ angular.module('JobTemplatesHelper', ['Utilities']) // loadingFinishedCount = 0, // base = $location.path().replace(/^\//, '').split('/')[0], master = {}, - id = $stateParams.id, + id = $stateParams.template_id, relatedSets = {}; // checkSCMStatus, getPlaybooks, callback, // choicesCount = 0; @@ -77,7 +77,6 @@ angular.module('JobTemplatesHelper', ['Utilities']) Rest.get() .success(function (data) { scope.job_template_obj = data; - scope.name = data.name; var fld, i; for (fld in form.fields) { if (fld !== 'variables' && fld !== 'survey' && data[fld] !== null && data[fld] !== undefined) { @@ -178,8 +177,8 @@ angular.module('JobTemplatesHelper', ['Utilities']) }); - if (scope.project === "" && scope.playbook === "") { - scope.resetProjectToDefault(); + if(scope.project === "" && scope.playbook === ""){ + scope.toggleScanInfo(); } RelatedSearchInit({ @@ -198,7 +197,7 @@ angular.module('JobTemplatesHelper', ['Utilities']) .error(function (data, status) { ProcessErrors(scope, data, status, form, { hdr: 'Error!', - msg: 'Failed to retrieve job template: ' + $stateParams.id + '. GET status: ' + status + msg: 'Failed to retrieve job template: ' + $stateParams.template_id + '. GET status: ' + status }); }); }; diff --git a/awx/ui/client/src/helpers/Jobs.js b/awx/ui/client/src/helpers/Jobs.js index ec2ecd5f8d..7d8fee0d62 100644 --- a/awx/ui/client/src/helpers/Jobs.js +++ b/awx/ui/client/src/helpers/Jobs.js @@ -157,6 +157,125 @@ export default } ]) + .factory('ShowJobSummary', ['Rest', 'Wait', 'GetBasePath', 'FormatDate', 'ProcessErrors', 'GenerateForm', 'JobSummary', + function (Rest, Wait, GetBasePath, FormatDate, ProcessErrors, GenerateForm, JobSummary) { + return function (params) { + // Display status info in a modal dialog- called from inventory edit page + + var job_id = params.job_id, + generator = GenerateForm, + form = JobSummary, + scope, ww, wh, x, y, maxrows, url, html; + + html = '
' + + '
\n'; + + $('#inventory-modal-container').empty().append(html); + + scope = generator.inject(form, { mode: 'edit', id: 'form-container', related: false }); + + // Set modal dimensions based on viewport width + ww = $(document).width(); + wh = $('body').height(); + if (ww > 1199) { + // desktop + x = 675; + y = (750 > wh) ? wh - 20 : 750; + maxrows = 20; + } else if (ww <= 1199 && ww >= 768) { + x = 550; + y = (620 > wh) ? wh - 15 : 620; + maxrows = 15; + } else { + x = (ww - 20); + y = (500 > wh) ? wh : 500; + maxrows = 10; + } + + // Create the modal + $('#status-modal-dialog').dialog({ + buttons: { + 'OK': function () { + $(this).dialog('close'); + } + }, + modal: true, + width: x, + height: y, + autoOpen: false, + closeOnEscape: false, + create: function () { + // fix the close button + $('.ui-dialog[aria-describedby="status-modal-dialog"]').find('.ui-dialog-titlebar button') + .empty().attr({ + 'class': 'close' + }).text('x'); + // fix the OK button + $('.ui-dialog[aria-describedby="status-modal-dialog"]').find('.ui-dialog-buttonset button:first') + .attr({ + 'class': 'btn btn-primary' + }); + }, + resizeStop: function () { + // for some reason, after resizing dialog the form and fields (the content) doesn't expand to 100% + var dialog = $('.ui-dialog[aria-describedby="status-modal-dialog"]'), + titleHeight = dialog.find('.ui-dialog-titlebar').outerHeight(), + buttonHeight = dialog.find('.ui-dialog-buttonpane').outerHeight(), + content = dialog.find('#status-modal-dialog'); + content.width(dialog.width() - 28); + content.css({ height: (dialog.height() - titleHeight - buttonHeight - 10) }); + }, + close: function () { + // Destroy on close + $('.tooltip').each(function () { + // Remove any lingering tooltip
elements + $(this).remove(); + }); + $('.popover').each(function () { + // remove lingering popover
elements + $(this).remove(); + }); + $('#status-modal-dialog').dialog('destroy'); + $('#inventory-modal-container').empty(); + }, + open: function () { + Wait('stop'); + } + }); + + function calcRows(content) { + var n = content.match(/\n/g), + rows = (n) ? n.length : 1; + return (rows > maxrows) ? 20 : rows; + } + + Wait('start'); + url = GetBasePath('jobs') + job_id + '/'; + Rest.setUrl(url); + Rest.get() + .success(function (data) { + var cDate; + scope.id = data.id; + scope.name = data.name; + scope.status = data.status; + scope.result_stdout = data.result_stdout; + scope.result_traceback = data.result_traceback; + scope.stdout_rows = calcRows(scope.result_stdout); + scope.traceback_rows = calcRows(scope.result_traceback); + cDate = new Date(data.created); + scope.created = FormatDate(cDate); + $('#status-modal-dialog').dialog('open'); + }) + .error(function (data, status) { + ProcessErrors(scope, data, status, null, { hdr: 'Error!', + msg: 'Attempt to load job failed. GET returned status: ' + status }); + }); + }; + + } + ]) + + .factory('JobsListUpdate', ['Rest', function(Rest) { return function(params) { var scope = params.scope, @@ -237,7 +356,7 @@ export default list = params.list, id = params.id, url = params.url, - pageSize = params.pageSize || 10, + pageSize = params.pageSize || 5, base = $location.path().replace(/^\//, '').split('/')[0], search_params = params.searchParams, spinner = (params.spinner === undefined) ? true : params.spinner, key; @@ -343,12 +462,9 @@ export default scope.search(scope.iterator); } }) - .error(function(obj, status) { + .error(function() { Wait('stop'); $('#prompt-modal').modal('hide'); - if (status === 403) { - Alert('Error', obj.detail); - } // Ignore the error. The job most likely already finished. // ProcessErrors(scope, data, status, null, { hdr: 'Error!', msg: 'Call to ' + url + // ' failed. POST returned status: ' + status }); @@ -364,12 +480,9 @@ export default scope.search(scope.iterator); } }) - .error(function (obj, status) { + .error(function () { Wait('stop'); $('#prompt-modal').modal('hide'); - if (status === 403) { - Alert('Error', obj.detail); - } // Ignore the error. The job most likely already finished. //ProcessErrors(scope, data, status, null, { hdr: 'Error!', msg: 'Call to ' + url + // ' failed. DELETE returned status: ' + status }); diff --git a/awx/ui/client/src/helpers/Parse.js b/awx/ui/client/src/helpers/Parse.js index a421b96c0b..d769bae611 100644 --- a/awx/ui/client/src/helpers/Parse.js +++ b/awx/ui/client/src/helpers/Parse.js @@ -16,8 +16,7 @@ export default angular.module('ParseHelper', ['Utilities', 'AngularCodeMirrorModule']) - .factory('ParseTypeChange', ['Alert', 'AngularCodeMirror', '$rootScope', - function (Alert, AngularCodeMirror, $rootScope) { + .factory('ParseTypeChange', ['Alert', 'AngularCodeMirror', function (Alert, AngularCodeMirror) { return function (params) { var scope = params.scope, @@ -46,18 +45,16 @@ export default function createField(onChange, onReady) { //hide the textarea and show a fresh CodeMirror with the current mode (json or yaml) - $rootScope.loginConfig.promise.then(function () { - scope.codeMirror = AngularCodeMirror(); - scope.codeMirror.addModes($AnsibleConfig.variable_edit_modes); - scope.codeMirror.showTextArea({ - scope: scope, - model: fld, - element: field_id, - lineNumbers: true, - mode: scope[pfld], - onReady: onReady, - onChange: onChange - }); + scope.codeMirror = AngularCodeMirror(); + scope.codeMirror.addModes($AnsibleConfig.variable_edit_modes); + scope.codeMirror.showTextArea({ + scope: scope, + model: fld, + element: field_id, + lineNumbers: true, + mode: scope[pfld], + onReady: onReady, + onChange: onChange }); } diff --git a/awx/ui/client/src/helpers/Schedules.js b/awx/ui/client/src/helpers/Schedules.js index b7bf70c833..ae0c8649c0 100644 --- a/awx/ui/client/src/helpers/Schedules.js +++ b/awx/ui/client/src/helpers/Schedules.js @@ -20,7 +20,7 @@ export default angular.module('SchedulesHelper', [ 'Utilities', 'RestServices', 'SchedulesHelper', 'SearchHelper', 'PaginationHelpers', listGenerator.name, 'ModalDialog', 'GeneratorHelpers']) - .factory('EditSchedule', ['SchedulerInit', '$rootScope', 'Wait', 'Rest', + .factory('EditSchedule', ['SchedulerInit', '$rootScope', 'Wait', 'Rest', 'ProcessErrors', 'GetBasePath', 'SchedulePost', '$state', function(SchedulerInit, $rootScope, Wait, Rest, ProcessErrors, GetBasePath, SchedulePost, $state) { @@ -88,6 +88,24 @@ export default } } + if (scope.removeDialogReady) { + scope.removeDialogReady(); + } + scope.removeDialogReady = scope.$on('DialogReady', function() { + $('#scheduler-modal-dialog').dialog('open'); + $('#schedulerName').focus(); + setTimeout(function() { + scope.$apply(function() { + scheduler.setRRule(schedule.rrule); + scheduler.setName(schedule.name); + if(scope.isFactCleanup || scope.cleanupJob){ + setGranularity(); + } + + }); + }, 300); + }); + if (scope.removeScheduleFound) { scope.removeScheduleFound(); } @@ -108,12 +126,6 @@ export default $rootScope.$broadcast("ScheduleFormCreated", scope); }); scope.showRRuleDetail = false; - - scheduler.setRRule(schedule.rrule); - scheduler.setName(schedule.name); - if(scope.isFactCleanup || scope.cleanupJob){ - setGranularity(); - } }); @@ -155,8 +167,6 @@ export default scope.cleanupJob = true; } - scope.schedule_obj = data; - scope.$emit('ScheduleFound'); }) .error(function(data,status){ @@ -166,7 +176,7 @@ export default }; }]) - .factory('AddSchedule', ['$location', '$rootScope', '$stateParams', + .factory('AddSchedule', ['$location', '$rootScope', '$stateParams', 'SchedulerInit', 'Wait', 'GetBasePath', 'Empty', 'SchedulePost', '$state', 'Rest', 'ProcessErrors', function($location, $rootScope, $stateParams, SchedulerInit, Wait, GetBasePath, Empty, SchedulePost, $state, Rest, @@ -175,13 +185,16 @@ export default var scope = params.scope, callback= params.callback, base = params.base || $location.path().replace(/^\//, '').split('/')[0], - url = params.url || null, + url, scheduler; - if (!Empty($stateParams.id) && base !== 'system_job_templates' && base !== 'inventories') { + if (!Empty($stateParams.template_id)) { + url = GetBasePath(base) + $stateParams.template_id + '/schedules/'; + } + else if (!Empty($stateParams.id) && base !== 'system_job_templates' && base !== 'inventory') { url = GetBasePath(base) + $stateParams.id + '/schedules/'; } - else if(base === "inventories"){ + else if(base === "inventory"){ if (!params.url){ url = GetBasePath('groups') + $stateParams.id + '/'; Rest.setUrl(url); @@ -241,21 +254,7 @@ export default Wait('start'); $('#form-container').empty(); scheduler = SchedulerInit({ scope: scope, requireFutureStartTime: false }); - if(scope.schedulerUTCTime) { - // The UTC time is already set - scope.processSchedulerEndDt(); - } - else { - // We need to wait for it to be set by angular-scheduler because the following function depends - // on it - var schedulerUTCTimeWatcher = scope.$watch('schedulerUTCTime', function(newVal) { - if(newVal) { - // Remove the watcher - schedulerUTCTimeWatcher(); - scope.processSchedulerEndDt(); - } - }); - } + scope.processSchedulerEndDt(); scheduler.inject('form-container', false); scheduler.injectDetail('occurrences', false); scheduler.clear(); @@ -274,6 +273,7 @@ export default } $state.go("^"); }); + scope.saveSchedule = function() { SchedulePost({ scope: scope, @@ -295,7 +295,8 @@ export default }]) .factory('SchedulePost', ['Rest', 'ProcessErrors', 'RRuleToAPI', 'Wait', - function(Rest, ProcessErrors, RRuleToAPI, Wait) { + 'ToJSON', + function(Rest, ProcessErrors, RRuleToAPI, Wait, ToJSON) { return function(params) { var scope = params.scope, url = params.url, @@ -325,8 +326,8 @@ export default schedule.extra_data = JSON.stringify(extra_vars); } else if(scope.extraVars){ - schedule.extra_data = scope.parseType === 'yaml' ? - (scope.extraVars === '---' ? "" : jsyaml.safeLoad(scope.extraVars)) : scope.extraVars; + schedule.extra_data = scope.parseType === 'yaml' ? + (scope.extraVars === '---' ? "" : jsyaml.safeLoad(scope.extraVars)) : scope.extraVars; } Rest.setUrl(url); if (mode === 'add') { @@ -429,8 +430,8 @@ export default * }) * */ - .factory('DeleteSchedule', ['GetBasePath','Rest', 'Wait', 'ProcessErrors', 'Prompt', 'Find', '$location', - function(GetBasePath, Rest, Wait, ProcessErrors, Prompt, Find, $location) { + .factory('DeleteSchedule', ['GetBasePath','Rest', 'Wait', 'ProcessErrors', 'Prompt', 'Find', + function(GetBasePath, Rest, Wait, ProcessErrors, Prompt, Find) { return function(params) { var scope = params.scope, @@ -456,9 +457,6 @@ export default .success(function () { $('#prompt-modal').modal('hide'); scope.$emit(callback, id); - if (new RegExp('/' + id + '$').test($location.$$url)) { - $location.url($location.url().replace(/[/][0-9]+$/, "")); // go to list view - } }) .error(function (data, status) { try { @@ -530,36 +528,14 @@ export default }; scope.editSchedule = function(id) { - if ($state.includes('inventoryManage')){ - $state.go('inventoryManage.schedules.edit', {schedule_id: id}); - } - else if ($state.current.name === 'jobs'){ - // id === schedule object in this case - var stateDictionary = { - // type: stateName - job: 'jobTemplateSchedules.edit', - system_job: 'managementJobSchedules.edit', - project_update: 'projectSchedules.edit', - }; - $state.go(stateDictionary[id.type], {schedule_id: id.id, id: id.summary_fields.unified_job_template.id}); - } - else{ - var base = $state.current.name.split(".")[0]; - $state.go(base + ".edit", {schedule_id: id}); - } + var base = $state.current.name.split(".")[0]; + $state.go(base + ".edit", {schedule_id: id}); }; scope.addSchedule = function() { - if ($state.includes('inventoryManage')){ - scope.schedule_url = parent_scope.current_url.split('?')[0]; - ParamPass.set(scope.schedule_url); - $state.go('inventoryManage.schedules.add'); - } - else{ - var base = $state.current.name.split(".")[0]; - ParamPass.set(scope.schedule_url); - $state.go(base + ".add"); - } + var base = $state.current.name.split(".")[0]; + ParamPass.set(scope.schedule_url); + $state.go(base + ".add"); }; scope.refreshSchedules = function() { @@ -651,7 +627,7 @@ export default id = params.id, url = params.url, searchSize = params.searchSize, - pageSize = params.pageSize || 10, + pageSize = params.pageSize || 5, spinner = (params.spinner === undefined) ? true : params.spinner; diff --git a/awx/ui/client/src/helpers/inventory.js b/awx/ui/client/src/helpers/inventory.js index 18a8b27883..9becb2dbb9 100644 --- a/awx/ui/client/src/helpers/inventory.js +++ b/awx/ui/client/src/helpers/inventory.js @@ -81,4 +81,217 @@ export default }); }; } + ]) + + .factory('EditInventoryProperties', ['InventoryForm', 'GenerateForm', 'Rest', 'Alert', 'ProcessErrors', 'LookUpInit', 'OrganizationList', + 'GetBasePath', 'ParseTypeChange', 'SaveInventory', 'Wait', 'Store', 'SearchInit', 'ParseVariableString', 'CreateDialog', 'TextareaResize', + function (InventoryForm, GenerateForm, Rest, Alert, ProcessErrors, LookUpInit, OrganizationList, GetBasePath, ParseTypeChange, SaveInventory, + Wait, Store, SearchInit, ParseVariableString, CreateDialog, TextareaResize) { + return function (params) { + + var parent_scope = params.scope, + inventory_id = params.inventory_id, + generator = GenerateForm, + form = InventoryForm, + master = {}, + //PreviousSearchParams = Store('CurrentSearchParams'), + buttons, + scope = parent_scope.$new(); + + form.well = false; + + var form_scope = + generator.inject(form, { + mode: 'edit', + showButtons: false, + showActions: false, + id: 'inventory-edit-modal-dialog', + related: false, + scope: scope + }); + + /* Reset form properties. Otherwise it screws up future requests of the Inventories detail page */ + form.well = true; + + buttons = [{ + label: "Cancel", + onClick: function() { + scope.cancelModal(); + }, + icon: "fa-times", + "class": "btn btn-default", + "id": "inventory-edit-cancel-button" + },{ + label: "Save", + onClick: function() { + scope.saveModal(); + }, + icon: "fa-check", + "class": "btn btn-primary", + "id": "inventory-edit-save-button" + }]; + + CreateDialog({ + scope: scope, + buttons: buttons, + width: 675, + height: 750, + minWidth: 400, + title: 'Inventory Properties', + id: 'inventory-edit-modal-dialog', + closeOnEscape: false, + form: form_scope.inventory_form, + onClose: function() { + Wait('stop'); + scope.codeMirror.destroy(); + $('#inventory-edit-modal-dialog').empty(); + }, + onResizeStop: function() { + TextareaResize({ + scope: scope, + textareaId: 'inventory_variables', + modalId: 'inventory-edit-modal-dialog', + formId: 'inventory_form' + }); + }, + beforeDestroy: function() { + if (scope.codeMirror) { + scope.codeMirror.destroy(); + } + $('#inventory-edit-modal-dialog').empty(); + }, + onOpen: function() { + $('#inventory_name').focus(); + setTimeout(function() { + TextareaResize({ + scope: scope, + textareaId: 'inventory_variables', + modalId: 'inventory-edit-modal-dialog', + formId: 'inventory_form', + parse: true + }); + }, 300); + }, + callback: 'InventoryEditDialogReady' + }); + + scope.parseType = 'yaml'; + + if (scope.removeInventoryPropertiesLoaded) { + scope.removeInventoryPropertiesLoaded(); + } + scope.removeInventoryPropertiesLoaded = scope.$on('inventoryPropertiesLoaded', function() { + Wait('stop'); + $('#inventory-edit-modal-dialog').dialog('open'); + }); + + scope.formModalActionLabel = 'Save'; + scope.formModalCancelShow = true; + scope.formModalInfo = false; + scope.formModalHeader = 'Inventory Properties'; + + Wait('start'); + Rest.setUrl(GetBasePath('inventory') + inventory_id + '/'); + Rest.get() + .success(function (data) { + var fld; + for (fld in form.fields) { + if (fld === 'variables') { + scope.variables = ParseVariableString(data.variables); + master.variables = scope.variables; + } else if (fld === 'inventory_name') { + scope[fld] = data.name; + master[fld] = scope[fld]; + } else if (fld === 'inventory_description') { + scope[fld] = data.description; + master[fld] = scope[fld]; + } else if (data[fld]) { + scope[fld] = data[fld]; + master[fld] = scope[fld]; + } + if (form.fields[fld].sourceModel && data.summary_fields && + data.summary_fields[form.fields[fld].sourceModel]) { + scope[form.fields[fld].sourceModel + '_' + form.fields[fld].sourceField] = + data.summary_fields[form.fields[fld].sourceModel][form.fields[fld].sourceField]; + master[form.fields[fld].sourceModel + '_' + form.fields[fld].sourceField] = + data.summary_fields[form.fields[fld].sourceModel][form.fields[fld].sourceField]; + } + } + + LookUpInit({ + scope: scope, + form: form, + current_item: scope.organization, + list: OrganizationList, + field: 'organization', + input_type: 'radio' + }); + + scope.$emit('inventoryPropertiesLoaded'); + + }) + .error(function (data, status) { + ProcessErrors(scope, data, status, null, { hdr: 'Error!', + msg: 'Failed to get inventory: ' + inventory_id + '. GET returned: ' + status }); + }); + + if (scope.removeInventorySaved) { + scope.removeInventorySaved(); + } + scope.removeInventorySaved = scope.$on('InventorySaved', function () { + //$('#form-modal').modal('hide'); + // Restore prior search state + //if (scope.searchCleanp) { + // scope.searchCleanup(); + //} + //SearchInit({ + // scope: parent_scope, + // set: PreviousSearchParams.set, + // list: PreviousSearchParams.list, + // url: PreviousSearchParams.defaultUrl, + // iterator: PreviousSearchParams.iterator, + // sort_order: PreviousSearchParams.sort_order, + // setWidgets: false + //}); + //parent_scope.$emit('RefreshInventories'); + try { + $('#inventory-edit-modal-dialog').dialog('close'); + } + catch(err) { + // ignore + } + parent_scope.$emit('RefreshInventories'); + scope.$destroy(); + }); + + scope.cancelModal = function () { + // Restore prior search state + /*if (scope.searchCleanp) { + scope.searchCleanup(); + } + SearchInit({ + scope: parent_scope, + set: PreviousSearchParams.set, + list: PreviousSearchParams.list, + url: PreviousSearchParams.defaultUrl, + iterator: PreviousSearchParams.iterator, + sort_order: PreviousSearchParams.sort_order, + setWidgets: false + });*/ + try { + $('#inventory-edit-modal-dialog').dialog('close'); + } + catch(err) { + // ignore + } + scope.$destroy(); + }; + + scope.saveModal = function () { + scope.inventory_id = inventory_id; + SaveInventory({ scope: scope, parent_scope: parent_scope }); + }; + + }; + } ]); diff --git a/awx/ui/client/src/inventories/edit/inventory-edit.route.js b/awx/ui/client/src/inventories/edit/inventory-edit.route.js index fbf3fc52f8..d721ba92a4 100644 --- a/awx/ui/client/src/inventories/edit/inventory-edit.route.js +++ b/awx/ui/client/src/inventories/edit/inventory-edit.route.js @@ -16,7 +16,11 @@ export default { activityStreamId: 'inventory_id' }, ncyBreadcrumb: { - parent: 'inventories', - label: "{{inventory_obj.name}}" + label: "INVENTORY EDIT" + }, + resolve: { + features: ['FeaturesService', function(FeaturesService) { + return FeaturesService.get(); + }] } }; diff --git a/awx/ui/client/src/inventories/inventories.partial.html b/awx/ui/client/src/inventories/inventories.partial.html index 0284089d54..46d04b20dd 100644 --- a/awx/ui/client/src/inventories/inventories.partial.html +++ b/awx/ui/client/src/inventories/inventories.partial.html @@ -1,5 +1,13 @@
-
+
+
+
diff --git a/awx/ui/client/src/inventories/list/inventory-list.controller.js b/awx/ui/client/src/inventories/list/inventory-list.controller.js index 54fc4fd3eb..947b1c0341 100644 --- a/awx/ui/client/src/inventories/list/inventory-list.controller.js +++ b/awx/ui/client/src/inventories/list/inventory-list.controller.js @@ -17,7 +17,7 @@ function InventoriesList($scope, $rootScope, $location, $log, Find, Empty, $state) { var list = InventoryList, - defaultUrl = GetBasePath('inventory') + ($stateParams.status === 'sync-failed' ? '?not__inventory_sources_with_failures=0' : ''), + defaultUrl = GetBasePath('inventory'), view = generateList, paths = $location.path().replace(/^\//, '').split('/'), mode = (paths[0] === 'inventories') ? 'edit' : 'select'; @@ -323,9 +323,6 @@ function InventoriesList($scope, $rootScope, $location, $log, Rest.destroy() .success(function () { $scope.search(list.iterator); - if (new RegExp('/' + id + '$').test($location.$$url)) { - $state.go('^'); - } }) .error(function (data, status) { ProcessErrors( $scope, data, status, null, { hdr: 'Error!', diff --git a/awx/ui/client/src/inventories/list/inventory-list.route.js b/awx/ui/client/src/inventories/list/inventory-list.route.js index af1cc1853b..65709dd512 100644 --- a/awx/ui/client/src/inventories/list/inventory-list.route.js +++ b/awx/ui/client/src/inventories/list/inventory-list.route.js @@ -9,7 +9,7 @@ import InventoriesList from './inventory-list.controller'; export default { name: 'inventories', - route: '/inventories?{status}', + route: '/inventories', templateUrl: templateUrl('inventories/inventories'), controller: InventoriesList, data: { diff --git a/awx/ui/client/src/inventories/manage/adhoc/adhoc.route.js b/awx/ui/client/src/inventories/manage/adhoc/adhoc.route.js deleted file mode 100644 index d8eb57e735..0000000000 --- a/awx/ui/client/src/inventories/manage/adhoc/adhoc.route.js +++ /dev/null @@ -1,27 +0,0 @@ -/************************************************* - * Copyright (c) 2015 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - import {templateUrl} from '../../../shared/template-url/template-url.factory'; - -export default { - route: '/adhoc', - params:{ - pattern: { - value: 'all', - squash: true - } - }, - name: 'inventoryManage.adhoc', - views: { - 'form@inventoryManage': { - templateUrl: templateUrl('inventories/manage/adhoc/adhoc'), - controller: 'adhocController' - } - }, - ncyBreadcrumb: { - label: "RUN COMMAND" - } -}; diff --git a/awx/ui/client/src/inventories/manage/adhoc/main.js b/awx/ui/client/src/inventories/manage/adhoc/main.js deleted file mode 100644 index 7072a23063..0000000000 --- a/awx/ui/client/src/inventories/manage/adhoc/main.js +++ /dev/null @@ -1,11 +0,0 @@ -import route from './adhoc.route'; -import adhocController from './adhoc.controller'; -import form from './adhoc.form'; - -export default - angular.module('adhoc', []) - .controller('adhocController', adhocController) - .run(['$stateExtender', function($stateExtender) { - $stateExtender.addState(route); - }]) - .factory('adhocForm', form); diff --git a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.block.less b/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.block.less deleted file mode 100644 index d53e9174c8..0000000000 --- a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.block.less +++ /dev/null @@ -1,25 +0,0 @@ -.InventoryManageBreadCrumbs .BreadCrumb-list{ - padding-right: 0px; -} -.InventoryManageBreadCrumb-ncy.BreadCrumb-list{ - padding-left: 5px; -} -.InventoryManageBreadCrumbs-separator{ - content: "/"; - padding: 0 5px; - color: #B7B7B7; -} -.InventoryManageBreadCrumbs{ - position: relative; - height: auto; - top: -40px; - .BreadCrumb-list{ - margin-bottom: 0px; - } -} -.InventoryManage-breakWord{ - word-break: break-all; -} -ol.BreadCrumb-list{ - display: inline-block; -} \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.controller.js b/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.controller.js deleted file mode 100644 index c04f014df2..0000000000 --- a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.controller.js +++ /dev/null @@ -1,27 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - -export default - ['$state', '$stateParams', '$scope', 'inventoryData', 'breadCrumbData', function($state, $stateParams, $scope, inventoryData, breadCrumbData){ - // process result data into the same order specified in the traversal path - $scope.groups = _.sortBy(breadCrumbData, function(item){ - var index = _.indexOf($stateParams.group, item.id); - return (index === -1) ? $stateParams.group.length : index; - }); - $scope.inventory = inventoryData; - // slices the group stack at $index to supply new group params to $state.go() - $scope.goToGroup = function($index){ - var group = $stateParams.group.slice(0, $index); - $state.go('inventoryManage', {group: group}, {reload: true}); - }; - $scope.state = $state; - $scope.isRootState = function(){ - return $state.current.name === 'inventoryManage'; - }; - $scope.goToInventory = function(){ - $state.go('inventoryManage', {group: undefined}, {reload: true}); - }; - }]; \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.partial.html b/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.partial.html deleted file mode 100644 index 0ebe597d3e..0000000000 --- a/awx/ui/client/src/inventories/manage/breadcrumbs/breadcrumbs.partial.html +++ /dev/null @@ -1,37 +0,0 @@ - diff --git a/awx/ui/client/src/inventories/manage/copy-move/copy-move-groups.controller.js b/awx/ui/client/src/inventories/manage/copy-move/copy-move-groups.controller.js deleted file mode 100644 index 0ae7afb857..0000000000 --- a/awx/ui/client/src/inventories/manage/copy-move/copy-move-groups.controller.js +++ /dev/null @@ -1,87 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$scope', '$state', '$stateParams', 'generateList', 'SearchInit', 'PaginateInit', 'GroupManageService', 'GetBasePath', 'CopyMoveGroupList', 'group', - function($scope, $state, $stateParams, GenerateList, SearchInit, PaginateInit, GroupManageService, GetBasePath, CopyMoveGroupList, group){ - var list = CopyMoveGroupList, - view = GenerateList; - $scope.item = group; - $scope.submitMode = $stateParams.groups === undefined ? 'move' : 'copy'; - $scope['toggle_'+ list.iterator] = function(id){ - // toggle off anything else currently selected - _.forEach($scope.groups, (item) => {return item.id === id ? item.checked = 1 : item.checked = null;}); - // yoink the currently selected thing - $scope.selected = _.find($scope.groups, (item) => {return item.id === id;}); - }; - $scope.formCancel = function(){ - $state.go('^'); - }; - $scope.formSave = function(){ - switch($scope.submitMode) { - case 'copy': - GroupManageService.associateGroup(group, $scope.selected.id).then(() => $state.go('^', null, {reload: true})); - break; - case 'move': - switch($scope.targetRootGroup){ - case true: - // disassociating group will bubble it to the root group level - GroupManageService.disassociateGroup(group.id, _.last($stateParams.group)).then(() => $state.go('^', null, {reload: true})); - break; - default: - // at the root group level, no dissassociation is needed - if (!$stateParams.group){ - GroupManageService.associateGroup(group, $scope.selected.id).then(() => $state.go('^', null, {reload: true})); - } - else{ - // unsure if orphaned resources get garbage collected, safe bet is to associate before disassociate - GroupManageService.associateGroup(group, $scope.selected.id).then(() => { - GroupManageService.disassociateGroup(group.id, _.last($stateParams.group)) - .then(() => $state.go('^', null, {reload: true})); - }); - } - break; - } - } - }; - $scope.toggleTargetRootGroup = function(){ - $scope.selected = !$scope.selected; - // cannot perform copy operations to root group level - $scope.submitMode = 'move'; - // toggle off anything currently selected in the list, for clarity - _.forEach($scope.groups, (item) => {item.checked = null;}); - // disable list selections - $('#copyMove-list :input').each((idx, el) => { - $(el).prop('disabled', (idx, value) => !value); - }); - }; - var init = function(){ - var url = GetBasePath('inventory') + $stateParams.inventory_id + '/groups/'; - url += $stateParams.group ? '?not__id__in=' + group.id + ',' + _.last($stateParams.group) : '?not__id=' + group.id; - list.basePath = url; - $scope.atRootLevel = $stateParams.group ? false : true; - view.inject(list, { - mode: 'lookup', - id: 'copyMove-list', - scope: $scope - }); - SearchInit({ - scope: $scope, - set: list.name, - list: list, - url: url - }); - PaginateInit({ - scope: $scope, - list: list, - url : url, - mode: 'lookup' - }); - $scope.search(list.iterator, null, true, false); - // remove the current group from list - }; - init(); - }]; diff --git a/awx/ui/client/src/inventories/manage/copy-move/copy-move-hosts.controller.js b/awx/ui/client/src/inventories/manage/copy-move/copy-move-hosts.controller.js deleted file mode 100644 index f04346f775..0000000000 --- a/awx/ui/client/src/inventories/manage/copy-move/copy-move-hosts.controller.js +++ /dev/null @@ -1,65 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$scope', '$state', '$stateParams', 'generateList', 'SearchInit', 'PaginateInit', 'HostManageService', 'GetBasePath', 'CopyMoveGroupList', 'host', - function($scope, $state, $stateParams, GenerateList, SearchInit, PaginateInit, HostManageService, GetBasePath, CopyMoveGroupList, host){ - var list = CopyMoveGroupList, - view = GenerateList; - $scope.item = host; - $scope.submitMode = 'copy'; - $scope['toggle_'+ list.iterator] = function(id){ - // toggle off anything else currently selected - _.forEach($scope.groups, (item) => {return item.id === id ? item.checked = 1 : item.checked = null;}); - // yoink the currently selected thing - $scope.selected = _.find($scope.groups, (item) => {return item.id === id;}); - }; - $scope.formCancel = function(){ - $state.go('^'); - }; - $scope.formSave = function(){ - switch($scope.submitMode) { - case 'copy': - HostManageService.associateGroup(host, $scope.selected.id).then(() => $state.go('^')); - break; - case 'move': - // at the root group level, no dissassociation is needed - if (!$stateParams.group){ - HostManageService.associateGroup(host, $scope.selected.id).then(() => $state.go('^', null, {reload: true})); - } - else{ - HostManageService.associateGroup(host, $scope.selected.id).then(() => { - HostManageService.disassociateGroup(host, _.last($stateParams.group)) - .then(() => $state.go('^', null, {reload: true})); - }); - } - break; - } - }; - var init = function(){ - var url = GetBasePath('inventory') + $stateParams.inventory_id + '/groups/'; - list.basePath = url; - view.inject(list, { - mode: 'lookup', - id: 'copyMove-list', - scope: $scope - }); - SearchInit({ - scope: $scope, - set: list.name, - list: list, - url: url - }); - PaginateInit({ - scope: $scope, - list: list, - url : url, - mode: 'lookup' - }); - $scope.search(list.iterator, null, true, false); - }; - init(); - }]; diff --git a/awx/ui/client/src/inventories/manage/copy-move/copy-move.partial.html b/awx/ui/client/src/inventories/manage/copy-move/copy-move.partial.html deleted file mode 100644 index 39a87a729f..0000000000 --- a/awx/ui/client/src/inventories/manage/copy-move/copy-move.partial.html +++ /dev/null @@ -1,21 +0,0 @@ -
-
-
{{item.name}}
-
-
- - -
-
-
- Use the inventory root -
-
- - -
-
diff --git a/awx/ui/client/src/inventories/manage/copy-move/copy-move.route.js b/awx/ui/client/src/inventories/manage/copy-move/copy-move.route.js deleted file mode 100644 index 85d856c5ed..0000000000 --- a/awx/ui/client/src/inventories/manage/copy-move/copy-move.route.js +++ /dev/null @@ -1,51 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ -import {templateUrl} from '../../../shared/template-url/template-url.factory'; - -import CopyMoveGroupsController from './copy-move-groups.controller'; -import CopyMoveHostsController from './copy-move-hosts.controller'; - -var copyMoveGroup = { - name: 'inventoryManage.copyMoveGroup', - route: '/copy-move-group/{group_id}', - data: { - group_id: 'group_id', - }, - ncyBreadcrumb: { - label: "COPY OR MOVE {{item.name}}" - }, - resolve: { - group: ['GroupManageService', '$stateParams', function(GroupManageService, $stateParams){ - return GroupManageService.get({id: $stateParams.group_id}).then(res => res.data.results[0]); - }] - }, - views: { - 'form@inventoryManage' : { - controller: CopyMoveGroupsController, - templateUrl: templateUrl('inventories/manage/copy-move/copy-move'), - } - } -}; -var copyMoveHost = { - name: 'inventoryManage.copyMoveHost', - route: '/copy-move-host/{host_id}', - ncyBreadcrumb: { - label: "COPY OR MOVE {{item.name}}" - }, - resolve: { - host: ['HostManageService', '$stateParams', function(HostManageService, $stateParams){ - return HostManageService.get({id: $stateParams.host_id}).then(res => res.data.results[0]); - }] - }, - views: { - 'form@inventoryManage': { - templateUrl: templateUrl('inventories/manage/copy-move/copy-move'), - controller: CopyMoveHostsController, - } - } -}; - -export {copyMoveGroup, copyMoveHost}; diff --git a/awx/ui/client/src/inventories/manage/copy/copy-groups.controller.js b/awx/ui/client/src/inventories/manage/copy/copy-groups.controller.js new file mode 100644 index 0000000000..4690bb9b62 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy-groups.controller.js @@ -0,0 +1,306 @@ +function CopyGroupsCtrl($compile, $state, $scope, $location, Rest, ProcessErrors, CreateDialog, + GetBasePath, Wait, GenerateList, GroupList, SearchInit, PaginateInit, GetRootGroups, ParamPass, Store) { + var vm = this; + var name; + + var params = ParamPass.get(), + group_id, + parent_scope, + scope; + + if (params !== undefined) { + group_id = $state.params.group_id; + parent_scope = params.scope; + scope = parent_scope.$new(); + var parent_group = parent_scope.selected_group_id, + url, group; + } else { + group_id = $state.params.group_id; + parent_scope = $scope.$new(); + scope = parent_scope.$new(); + } + + var inventory_id = $state.params.inventory_id; + var PreviousSearchParams = Store('group_current_search_params'); + + if (scope.removeGroupsCopyPostRefresh) { + scope.removeGroupsCopyPostRefresh(); + } + + scope.removeGroupCopyPostRefresh = scope.$on('PostRefresh', function() { + scope.copy_groups.forEach(function(row, i) { + scope.copy_groups[i].checked = '0'; + }); + Wait('stop'); + + // prevent backspace from navigation when not in input or textarea field + $(document).on('keydown', function(e) { + if (e.which === 8 && !$(e.target).is('input[type="text"], textarea')) { + e.preventDefault(); + } + }); + + }); + + if (scope.removeCopyDialogReady) { + scope.removeCopyDialogReady(); + } + + scope.removeCopyDialogReady = scope.$on('CopyDialogReady', function() { + var url = GetBasePath('inventory') + inventory_id + '/groups/'; + url += (parent_group) ? '?not__id__in=' + group_id + ',' + parent_group : '?not__id=' + group_id; + GenerateList.inject(GroupList, { + mode: 'lookup', + id: 'copyMove-directive--copyGroupSelect', + scope: scope + }); + SearchInit({ + scope: scope, + set: GroupList.name, + list: GroupList, + url: url + }); + PaginateInit({ + scope: scope, + list: GroupList, + url: url, + mode: 'lookup' + }); + scope.search(GroupList.iterator); + }); + + if (scope.removeShowDialog) { + scope.removeShowDialog(); + } + + scope.removeShowDialog = scope.$on('ShowDialog', function() { + var d; + scope.name = group.name; + scope.copy_choice = "copy"; + d = angular.element(document.getElementById('copyMove-directive--copyGroupSelect')); + $compile(d)(scope); + scope.$emit('CopyDialogReady'); + }); + + if (scope.removeRootGroupsReady) { + scope.removeRootGroupsReady(); + } + + scope.removeRootGroupsReady = scope.$on('RootGroupsReady', function(e, root_groups) { + scope.offer_root_group = true; + scope.use_root_group = false; + root_groups.every(function(row) { + if (row.id === group_id) { + scope.offer_root_group = false; + return false; + } + return true; + }); + url = GetBasePath('groups') + group_id + '/'; + Rest.setUrl(url); + Rest.get() + .success(function(data) { + group = data; + vm.name = group.name; + scope.$emit('ShowDialog'); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Call to ' + url + ' failed. GET returned: ' + status + }); + }); + }); + + Wait('start'); + + GetRootGroups({ + scope: scope, + group_id: group_id, + inventory_id: $state.params.inventory_id, + callback: 'RootGroupsReady' + }); + + var restoreSearch = function() { + // Restore search params and related stuff, plus refresh + // groups and hosts lists + SearchInit({ + scope: $scope, + set: PreviousSearchParams.set, + list: PreviousSearchParams.list, + url: PreviousSearchParams.defaultUrl, + iterator: PreviousSearchParams.iterator, + sort_order: PreviousSearchParams.sort_order, + setWidgets: false + }); + $scope.refreshHostsOnGroupRefresh = true; + //$scope.search(InventoryGroups.iterator, null, true, false, true); + }; + + var cancel = function() { + restoreSearch(); // Restore all parent search stuff and refresh hosts and groups lists + scope.$destroy(); + $state.go('inventoryManage', {}, { + reload: true + }); + }; + + var allowSave = false; + scope['toggle_' + GroupList.iterator] = function(id) { + var count = 0, + list = GroupList; + scope[list.name].forEach(function(row, i) { + if (row.id === id) { + if (row.checked) { + scope[list.name][i].success_class = 'success'; + } else { + scope[list.name][i].success_class = ''; + } + } else { + scope[list.name][i].checked = 0; + scope[list.name][i].success_class = ''; + } + }); + // Check if any rows are checked + scope[list.name].forEach(function(row) { + if (row.checked) { + count++; + } + }); + if (count === 0) { + vm.allowSave = false; + } else { + vm.allowSave = true; + } + }; + + scope.toggleUseRootGroup = function() { + var list = GroupList; + if (scope.use_root_group) { + $('#group-copy-ok-button').removeAttr('disabled'); + } else { + // check for group selection + $('#group-copy-ok-button').attr('disabled', 'disabled'); + scope[list.name].every(function(row) { + if (row.checked === 1) { + $('#group-copy-ok-button').removeAttr('disabled'); + return false; + } + return true; + }); + } + }; + + var performCopy = function() { + var list = GroupList, + target, + url; + + Wait('start'); + + if (scope.use_root_group) { + target = null; + } else { + scope[list.name].every(function(row) { + if (row.checked === 1) { + target = row; + return false; + } + return true; + }); + } + + if (vm.copy_choice === 'move') { + // Respond to move + + // disassociate the group from the original parent + if (scope.removeGroupRemove) { + scope.removeGroupRemove(); + } + scope.removeGroupRemove = scope.$on('RemoveGroup', function() { + if (parent_group > 0) { + // Only remove a group from a parent when the parent is a group and not the inventory root + url = GetBasePath('groups') + parent_group + '/children/'; + Rest.setUrl(url); + Rest.post({ + id: group.id, + disassociate: 1 + }) + .success(function() { + vm.cancel(); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to remove ' + group.name + ' from group ' + parent_group + '. POST returned: ' + status + }); + }); + } else { + vm.cancel(); + } + }); + + // add the new group to the target + url = (target) ? + GetBasePath('groups') + target.id + '/children/' : + GetBasePath('inventory') + inventory_id + '/groups/'; + group = { + id: group.id, + name: group.name, + description: group.description, + inventory: inventory_id + }; + Rest.setUrl(url); + Rest.post(group) + .success(function() { + scope.$emit('RemoveGroup'); + }) + .error(function(data, status) { + var target_name = (target) ? target.name : 'inventory'; + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to add ' + group.name + ' to ' + target_name + '. POST returned: ' + status + }); + }); + } else { + // Respond to copy by adding the new group to the target + url = (target) ? + GetBasePath('groups') + target.id + '/children/' : + GetBasePath('inventory') + inventory_id + '/groups/'; + + group = { + id: group.id, + name: group.name, + description: group.description, + inventory: inventory_id + }; + + Rest.setUrl(url); + Rest.post(group) + .success(function() { + vm.cancel(); + }) + .error(function(data, status) { + var target_name = (target) ? target.name : 'inventory'; + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to add ' + group.name + ' to ' + target_name + '. POST returned: ' + status + }); + }); + } + }; + + var copy_choice = 'copy'; + + angular.extend(vm, { + cancel: cancel, + performCopy: performCopy, + copy_choice: copy_choice, + name: name, + allowSave: allowSave + }); +} + +export default ['$compile', '$state', '$scope', '$location', 'Rest', 'ProcessErrors', 'CreateDialog', 'GetBasePath', 'Wait', 'generateList', 'GroupList', 'SearchInit', + 'PaginateInit', 'GetRootGroups', 'ParamPass', 'Store', CopyGroupsCtrl +]; diff --git a/awx/ui/client/src/inventories/manage/copy/copy-groups.partial.html b/awx/ui/client/src/inventories/manage/copy/copy-groups.partial.html new file mode 100644 index 0000000000..d82ca6956f --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy-groups.partial.html @@ -0,0 +1,22 @@ +
+
+
{{vm.name}}
+
+
+ + +
+
+
+
+ + +
+
+
diff --git a/awx/ui/client/src/inventories/manage/copy/copy-hosts.controller.js b/awx/ui/client/src/inventories/manage/copy/copy-hosts.controller.js new file mode 100644 index 0000000000..3883fed6ad --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy-hosts.controller.js @@ -0,0 +1,239 @@ +function CopyHostsCtrl($compile, $state, $scope, Rest, ProcessErrors, CreateDialog, GetBasePath, Wait, GenerateList, GroupList, SearchInit, PaginateInit, ParamPass, Store) { + var vm = this; + var name; + + var host_id = $state.params.host_id; + var inventory_id = $state.params.inventory_id; + var url, host, group_scope, parent_scope, scope, parent_group; + + var params = ParamPass.get(); + if (params !== undefined) { + group_scope = params.group_scope; + parent_scope = params.host_scope; + parent_group = group_scope.selected_group_id; + scope = parent_scope.$new(); + } else { + group_scope = $scope.$new(); + parent_scope = $scope.$new(); + scope = parent_scope.$new(); + } + + var PreviousSearchParams = Store('group_current_search_params'); + + if (scope.removeHostCopyPostRefresh) { + scope.removeHostCopyPostRefresh(); + } + scope.removeHostCopyPostRefresh = scope.$on('PostRefresh', function() { + scope.copy_groups.forEach(function(row, i) { + scope.copy_groups[i].checked = '0'; + }); + Wait('stop'); + // prevent backspace from navigation when not in input or textarea field + $(document).on("keydown", function(e) { + if (e.which === 8 && !$(e.target).is('input[type="text"], textarea')) { + e.preventDefault(); + } + }); + }); + + if (scope.removeHostCopyDialogReady) { + scope.removeHostCopyDialogReady(); + } + scope.removeCopyDialogReady = scope.$on('HostCopyDialogReady', function() { + var url = GetBasePath('inventory') + inventory_id + '/groups/'; + GenerateList.inject(GroupList, { + mode: 'lookup', + id: 'copyMove-directive--copyHostSelect', + scope: scope + //, + //instructions: instructions + }); + SearchInit({ + scope: scope, + set: GroupList.name, + list: GroupList, + url: url + }); + PaginateInit({ + scope: scope, + list: GroupList, + url: url, + mode: 'lookup' + }); + scope.search(GroupList.iterator, null, true, false); + }); + + if (scope.removeShowDialog) { + scope.removeShowDialog(); + } + scope.removeShowDialog = scope.$on('ShowDialog', function() { + var d; + scope.name = host.name; + d = angular.element(document.getElementById('copyMove-directive--copyHostPanel')); + $compile(d)(scope); + scope.$emit('HostCopyDialogReady'); + }); + + Wait('start'); + + url = GetBasePath('hosts') + host_id + '/'; + Rest.setUrl(url); + Rest.get() + .success(function(data) { + host = data; + vm.name = host.name; + scope.$emit('ShowDialog'); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Call to ' + url + ' failed. GET returned: ' + status + }); + }); + + var restoreSearch = function() { + // Restore search params and related stuff, plus refresh + // groups and hosts lists + SearchInit({ + scope: $scope, + set: PreviousSearchParams.set, + list: PreviousSearchParams.list, + url: PreviousSearchParams.defaultUrl, + iterator: PreviousSearchParams.iterator, + sort_order: PreviousSearchParams.sort_order, + setWidgets: false + }); + $scope.refreshHostsOnGroupRefresh = true; + }; + + var cancel = function() { + $(document).off("keydown"); + restoreSearch(); // Restore all parent search stuff and refresh hosts and groups lists + scope.$destroy(); + $state.go('inventoryManage', {}, { + reload: true + }); + }; + + var allowSave = false; + scope['toggle_' + GroupList.iterator] = function(id) { + var count = 0, + list = GroupList; + scope[list.name].forEach(function(row, i) { + if (row.id === id) { + if (row.checked) { + scope[list.name][i].success_class = 'success'; + } else { + scope[list.name][i].success_class = ''; + } + } else { + scope[list.name][i].checked = 0; + scope[list.name][i].success_class = ''; + } + }); + // Check if any rows are checked + scope[list.name].forEach(function(row) { + if (row.checked) { + count++; + } + }); + if (count === 0) { + vm.allowSave = false; + } else { + vm.allowSave = true; + } + }; + + var performCopy = function() { + var list = GroupList, + target, + url; + + Wait('start'); + + if (scope.use_root_group) { + target = null; + } else { + scope[list.name].every(function(row) { + if (row.checked === 1) { + target = row; + return false; + } + return true; + }); + } + + if (vm.copy_choice === 'move') { + // Respond to move + // disassociate the host from the original parent + if (scope.removeHostRemove) { + scope.removeHostRemove(); + } + scope.removeHostRemove = scope.$on('RemoveHost', function() { + if (parent_group > 0) { + // Only remove a host from a parent when the parent is a group and not the inventory root + url = GetBasePath('groups') + parent_group + '/hosts/'; + Rest.setUrl(url); + Rest.post({ + id: host.id, + disassociate: 1 + }) + .success(function() { + vm.cancel(); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to remove ' + host.name + ' from group ' + parent_group + '. POST returned: ' + status + }); + }); + } else { + vm.cancel(); + } + }); + + // add the new host to the target + url = GetBasePath('groups') + target.id + '/hosts/'; + Rest.setUrl(url); + Rest.post(host) + .success(function() { + scope.$emit('RemoveHost'); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to add ' + host.name + ' to ' + target.name + '. POST returned: ' + status + }); + }); + } else { + // Respond to copy by adding the new host to the target + url = GetBasePath('groups') + target.id + '/hosts/'; + Rest.setUrl(url); + Rest.post(host) + .success(function() { + vm.cancel(); + }) + .error(function(data, status) { + ProcessErrors(scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to add ' + host.name + ' to ' + target.name + '. POST returned: ' + status + }); + }); + } + }; + + + var copy_choice = 'copy'; + + angular.extend(vm, { + copy_choice: copy_choice, + name: name, + cancel: cancel, + allowSave: allowSave, + performCopy: performCopy + }); +} + +export default ['$compile', '$state', '$scope', 'Rest', 'ProcessErrors', 'CreateDialog', 'GetBasePath', 'Wait', 'generateList', 'GroupList', 'SearchInit', + 'PaginateInit', 'ParamPass', 'Store', CopyHostsCtrl +]; diff --git a/awx/ui/client/src/inventories/manage/copy/copy-hosts.partial.html b/awx/ui/client/src/inventories/manage/copy/copy-hosts.partial.html new file mode 100644 index 0000000000..aa2990434a --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy-hosts.partial.html @@ -0,0 +1,23 @@ +
+
+
{{vm.name}}
+
+
+ + +
+
+
+
+
+ + +
+
+
diff --git a/awx/ui/client/src/inventories/manage/copy-move/copy-move.block.less b/awx/ui/client/src/inventories/manage/copy/copy.block.less similarity index 69% rename from awx/ui/client/src/inventories/manage/copy-move/copy-move.block.less rename to awx/ui/client/src/inventories/manage/copy/copy.block.less index aa865c165b..34b93417f6 100644 --- a/awx/ui/client/src/inventories/manage/copy-move/copy-move.block.less +++ b/awx/ui/client/src/inventories/manage/copy/copy.block.less @@ -4,6 +4,13 @@ .List-searchRow { width: 50%; } + + .ui-dialog-buttonpane.ui-widget-content { + border: none; + text-align: right; + margin-top: 15px; + } + .Form-header { width: 50%; margin-top: -20px; @@ -15,15 +22,9 @@ } } } -.copyMove-choices { + +.copyMove-directive--copyMoveChoices { float: right; width: 25%; text-align: right; } -.copyMove-buttons{ - height: 30px; - margin-top: 10px; -} -.copyMove-root{ - margin-top: 10px; -} diff --git a/awx/ui/client/src/inventories/manage/copy/copy.controller.js b/awx/ui/client/src/inventories/manage/copy/copy.controller.js new file mode 100644 index 0000000000..144f55da70 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy.controller.js @@ -0,0 +1,16 @@ +function inventoryManageCopyCtrl($state) { + var vm = this; + + var cancelPanel = function() { + $state.go('inventoryManage', {}, { + reload: true + }); + }; + + angular.extend(vm, { + cancelPanel: cancelPanel + }); +} + +export default ['$state', inventoryManageCopyCtrl +]; diff --git a/awx/ui/client/src/inventories/manage/copy/copy.partial.html b/awx/ui/client/src/inventories/manage/copy/copy.partial.html new file mode 100644 index 0000000000..ff19016e98 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy.partial.html @@ -0,0 +1,10 @@ +
+
+
+ +
+ +
+
diff --git a/awx/ui/client/src/inventories/manage/copy/copy.route.js b/awx/ui/client/src/inventories/manage/copy/copy.route.js new file mode 100644 index 0000000000..360cc30edc --- /dev/null +++ b/awx/ui/client/src/inventories/manage/copy/copy.route.js @@ -0,0 +1,54 @@ +/************************************************* + * Copyright (c) 2016 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ +import { + templateUrl +} from '../../../shared/template-url/template-url.factory'; + +import inventoryManageCopyCtrl from './copy.controller'; +import CopyGroupsCtrl from './copy-groups.controller'; +import CopyHostsCtrl from './copy-hosts.controller'; + +export default { + copy: { + name: 'inventoryManage.copy', + route: '/copy', + templateUrl: templateUrl('inventories/manage/copy/copy'), + ncyBreadcrumb: { + label: "COPY" + }, + controller: inventoryManageCopyCtrl, + controllerAs: 'vm', + bindToController: true, + }, + copyGroup: { + name: 'inventoryManage.copy.group', + route: '/group/:group_id?groups', + templateUrl: templateUrl('inventories/manage/copy/copy-groups'), + data: { + group_id: 'group_id', + }, + ncyBreadcrumb: { + label: "GROUP" + }, + controller: CopyGroupsCtrl, + controllerAs: 'vm', + bindToController: true + }, + copyHost: { + name: 'inventoryManage.copy.host', + route: '/host/:host_id?groups', + templateUrl: templateUrl('inventories/manage/copy/copy-hosts'), + data: { + host_id: 'host_id', + }, + ncyBreadcrumb: { + label: "HOST" + }, + controller: CopyHostsCtrl, + controllerAs: 'vm', + bindToController: true + } +}; diff --git a/awx/ui/client/src/inventories/manage/copy-move/main.js b/awx/ui/client/src/inventories/manage/copy/main.js similarity index 53% rename from awx/ui/client/src/inventories/manage/copy-move/main.js rename to awx/ui/client/src/inventories/manage/copy/main.js index d68348cba8..898d5f9ae1 100644 --- a/awx/ui/client/src/inventories/manage/copy-move/main.js +++ b/awx/ui/client/src/inventories/manage/copy/main.js @@ -4,11 +4,12 @@ * All Rights Reserved *************************************************/ -import {copyMoveGroup, copyMoveHost} from './copy-move.route'; +import route from './copy.route'; export default -angular.module('manageCopyMove', []) +angular.module('inventory-copy', []) .run(['$stateExtender', function($stateExtender) { - $stateExtender.addState(copyMoveGroup); - $stateExtender.addState(copyMoveHost); + $stateExtender.addState(route.copy); + $stateExtender.addState(route.copyGroup); + $stateExtender.addState(route.copyHost); }]); diff --git a/awx/ui/client/src/inventories/manage/groups/groups-add.controller.js b/awx/ui/client/src/inventories/manage/groups/groups-add.controller.js deleted file mode 100644 index 559d219dad..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups-add.controller.js +++ /dev/null @@ -1,215 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$state', '$stateParams', '$scope', 'GroupForm', 'CredentialList', 'inventoryScriptsListObject', 'ParseTypeChange', 'GenerateForm', 'inventoryData', 'LookUpInit', - 'GroupManageService', 'GetChoices', 'GetBasePath', 'CreateSelect2', 'GetSourceTypeOptions', - function($state, $stateParams, $scope, GroupForm, CredentialList, InventoryScriptsList, ParseTypeChange, GenerateForm, inventoryData, LookUpInit, - GroupManageService, GetChoices, GetBasePath, CreateSelect2, GetSourceTypeOptions){ - var generator = GenerateForm, - form = GroupForm(); - - $scope.formCancel = function(){ - $state.go('^'); - }; - $scope.formSave = function(){ - var params, source; - // group fields - var group = { - variables: $scope.variables === '---' || $scope.variables === '{}' ? null : $scope.variables, - name: $scope.name, - description: $scope.description, - inventory: inventoryData.id - }; - if ($scope.source){ - // inventory_source fields - params = { - instance_filters: $scope.instance_filters, - source_vars: $scope[$scope.source.value + '_variables'] === null ? null : $scope[$scope.source.value + '_variables'], - source_script: $scope.inventory_script, - source: $scope.source.value, - credential: $scope.credential, - overwrite: $scope.overwrite, - overwrite_vars: $scope.overwrite_vars, - update_on_launch: $scope.update_on_launch, - update_cache_timeout: $scope.update_cache_timeout || 0, - // comma-delimited strings - group_by: _.map($scope.group_by, 'value').join(','), - source_regions: _.map($scope.source_regions, 'value').join(',') - }; - source = $scope.source.value; - } - else{ - source = null; - } - switch(source){ - // no inventory source set, just create a new group - // '' is the value supplied for Manual source type - case null || '': - GroupManageService.post(group).then(res => { - // associate - if ($stateParams.group){ - return GroupManageService.associateGroup(res.data, _.last($stateParams.group)) - .then(() => $state.go('^', null, {reload: true})); - } - else{ - $state.go('^', null, {reload: true}); - } - }); - break; - // create a new group and create/associate an inventory source - // equal to case 'rax' || 'ec2' || 'azure' || 'azure_rm' || 'vmware' || 'foreman' || 'cloudforms' || 'openstack' || 'custom' - default: - GroupManageService.post(group) - // associate to group - .then(res => { - if ($stateParams.group){ - GroupManageService.associateGroup(res.data, _.last($stateParams.group)); - return res; - } - else {return res;} - // pass the original POST response and not the association response - }) - .then(res => GroupManageService.putInventorySource( - // put the received group ID into inventory source payload - // and pass the related endpoint - _.assign(params, {group: res.data.id}), res.data.related.inventory_source)) - .then(res => $state.go('inventoryManage.editGroup', {group_id: res.data.group}, {reload: true})); - break; - } - }; - $scope.sourceChange = function(source){ - source = source.value; - if (source === 'custom'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('inventory_script'), - form: form, - list: InventoryScriptsList, - field: 'inventory_script', - input_type: "radio" - }); - } - else if (source === 'ec2'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + '?kind=aws', - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - // equal to case 'rax' || 'azure' || 'azure_rm' || 'vmware' || 'foreman' || 'cloudforms' || 'openstack' || 'custom' - else{ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + (source === '' ? '' : '?kind=' + source), - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - // reset fields - $scope.group_by_choices = source === 'ec2' ? $scope.ec2_group_by : null; - $scope.source_region_choices = $scope[source + '_regions']; - $scope.cloudCredentialRequired = source !== 'manual' && source !== 'custom' ? true : false; - $scope.group_by = null; - $scope.source_regions = null; - $scope.credential = null; - $scope.credential_name = null; - initRegionSelect(); - }; - var initRegionSelect = function(){ - CreateSelect2({ - element: '#group_source_regions', - multiple: true - }); - CreateSelect2({ - element: '#group_group_by', - multiple: true - }); - }; - var initSourceSelect = function(){ - CreateSelect2({ - element: '#group_source', - multiple: false - }); - }; - var initSources = function(){ - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'rax_regions', - choice_name: 'rax_region_choices', - callback: 'choicesReadyGroup' - }); - - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'ec2_regions', - choice_name: 'ec2_region_choices', - callback: 'choicesReadyGroup' - }); - - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'gce_regions', - choice_name: 'gce_region_choices', - callback: 'choicesReadyGroup' - }); - - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'azure_regions', - choice_name: 'azure_region_choices', - callback: 'choicesReadyGroup' - }); - - // Load options for group_by - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'group_by', - variable: 'ec2_group_by', - choice_name: 'ec2_group_by_choices', - callback: 'choicesReadyGroup' - }); - GetSourceTypeOptions({ - scope: $scope, - variable: 'source_type_options', - //callback: 'sourceTypeOptionsReady' this callback is hard-coded into GetSourceTypeOptions(), included for ref - }); - }; - // region / source options callback - $scope.$on('choicesReadyGroup', function(){ - initRegionSelect(); - }); - - $scope.$on('sourceTypeOptionsReady', function(){ - initSourceSelect(); - }); - var init = function(){ - $scope.parseType = 'yaml'; - $scope.variables = '---'; - generator.inject(form, {mode: 'add', related: false, id: 'Inventory-groupManage--panel', scope: $scope}); - ParseTypeChange({ - scope: $scope, - field_id: 'group_variables', - variable: 'variables', - }); - initSources(); - }; - init(); - }]; diff --git a/awx/ui/client/src/inventories/manage/groups/groups-edit.controller.js b/awx/ui/client/src/inventories/manage/groups/groups-edit.controller.js deleted file mode 100644 index 91e11e1343..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups-edit.controller.js +++ /dev/null @@ -1,288 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$state', '$stateParams', '$scope', 'GroupForm', 'CredentialList', 'inventoryScriptsListObject', 'ToggleNotification', - 'ParseTypeChange', 'GenerateForm', 'LookUpInit', 'RelatedSearchInit', 'RelatedPaginateInit', 'NotificationsListInit', - 'GroupManageService','GetChoices', 'GetBasePath', 'CreateSelect2', 'GetSourceTypeOptions', 'groupData', 'inventorySourceData', - function($state, $stateParams, $scope, GroupForm, CredentialList, InventoryScriptsList, ToggleNotification, - ParseTypeChange, GenerateForm, LookUpInit, RelatedSearchInit, RelatedPaginateInit, NotificationsListInit, - GroupManageService, GetChoices, GetBasePath, CreateSelect2, GetSourceTypeOptions, groupData, inventorySourceData){ - var generator = GenerateForm, - form = GroupForm(); - $scope.formCancel = function(){ - $state.go('^'); - }; - $scope.formSave = function(){ - var params, source; - // group fields - var group = { - variables: $scope.variables === '---' || $scope.variables === '{}' ? null : $scope.variables, - name: $scope.name, - description: $scope.description, - inventory: $scope.inventory, - id: groupData.id - }; - if ($scope.source){ - // inventory_source fields - params = { - group: groupData.id, - source: $scope.source.value, - credential: $scope.credential, - overwrite: $scope.overwrite, - overwrite_vars: $scope.overwrite_vars, - source_script: $scope.inventory_script, - update_on_launch: $scope.update_on_launch, - update_cache_timeout: $scope.update_cache_timeout || 0, - // comma-delimited strings - group_by: _.map($scope.group_by, 'value').join(','), - source_regions: _.map($scope.source_regions, 'value').join(','), - instance_filters: $scope.instance_filters, - source_vars: $scope[$scope.source.value + '_variables'] === '' ? null : $scope[$scope.source.value + '_variables'] - }; - source = $scope.source.value; - } - else{ - source = null; - } - switch(source){ - // no inventory source set, just create a new group - // '' is the value supplied for Manual source type - case null || '': - GroupManageService.put(group).then(() => $state.go('^', null, {reload: true})); - break; - // create a new group and create/associate an inventory source - // equal to case 'rax' || 'ec2' || 'azure' || 'azure_rm' || 'vmware' || 'foreman' || 'cloudforms' || 'openstack' || 'custom' - default: - GroupManageService.put(group) - .then(() => GroupManageService.putInventorySource(params, groupData.related.inventory_source)) - .then(() => $state.go('^', null, {reload: true})); - break; - } - }; - $scope.toggleNotification = function(event, notifier_id, column) { - var notifier = this.notification; - try { - $(event.target).tooltip('hide'); - } - catch(e) { - // ignore - } - ToggleNotification({ - scope: $scope, - url: GetBasePath('inventory_sources'), - id: inventorySourceData.id, - notifier: notifier, - column: column, - callback: 'NotificationRefresh' - }); - }; - $scope.sourceChange = function(source){ - $scope.source = source; - if (source.value === 'custom'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('inventory_script'), - form: form, - list: InventoryScriptsList, - field: 'inventory_script', - input_type: "radio" - }); - } - else if (source.value === 'ec2'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + '?kind=aws', - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - else{ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + (source.value === '' ? '' : '?kind=' + (source.value)), - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - // reset fields - $scope.source_region_choices = $scope[source + '_regions']; - $scope.cloudCredentialRequired = source !== 'manual' && source !== 'custom' ? true : false; - $scope.group_by = null; - $scope.source_regions = null; - $scope.credential = null; - $scope.credential_name = null; - initRegionSelect(); - }; - var initRegionSelect = function(){ - CreateSelect2({ - element: '#group_source_regions', - multiple: true - }); - CreateSelect2({ - element: '#group_group_by', - multiple: true - }); - }; - var initSourceSelect = function(){ - $scope.source = _.find($scope.source_type_options, {value: inventorySourceData.source}); - CreateSelect2({ - element: '#group_source', - multiple: false - }); - }; - var initRegionData = function(){ - var source = $scope.source.value === 'azure_rm' ? 'azure' : $scope.source.value; - var regions = inventorySourceData.source_regions.split(','); - $scope.source_region_choices = $scope[source + '_regions']; - $scope.source_regions = _.map(regions, (region) => _.find($scope[source+'_regions'], {value: region})); - $scope.group_by_choices = source === 'ec2' ? $scope.ec2_group_by : null; - if (source ==='ec2'){ - var group_by = inventorySourceData.group_by.split(','); - $scope.group_by = _.map(group_by, (item) => _.find($scope.ec2_group_by, {value: item})); - } - initRegionSelect(); - }; - var initSources = function(){ - GetSourceTypeOptions({ - scope: $scope, - variable: 'source_type_options', - //callback: 'sourceTypeOptionsReady' this callback is hard-coded into GetSourceTypeOptions(), included for ref - }); - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'rax_regions', - choice_name: 'rax_region_choices', - callback: 'choicesReadyGroup' - }); - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'ec2_regions', - choice_name: 'ec2_region_choices', - callback: 'choicesReadyGroup' - }); - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'gce_regions', - choice_name: 'gce_region_choices', - callback: 'choicesReadyGroup' - }); - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'source_regions', - variable: 'azure_regions', - choice_name: 'azure_region_choices', - callback: 'choicesReadyGroup' - }); - GetChoices({ - scope: $scope, - url: GetBasePath('inventory_sources'), - field: 'group_by', - variable: 'ec2_group_by', - choice_name: 'ec2_group_by_choices', - callback: 'choicesReadyGroup' - }); - }; - // region / source options callback - $scope.$on('choicesReadyGroup', function(){ - if (angular.isObject($scope.source)){ - initRegionData(); - } - }); - - $scope.$on('sourceTypeOptionsReady', function(){ - initSourceSelect(); - }); - var init = function(){ - // instantiate expected $scope values from inventorySourceData & groupData - var relatedSets = form.relatedSets(groupData.related); - generator.inject(form, {mode: 'edit', related: false, id: 'Inventory-groupManage--panel', scope: $scope}); - _.assign($scope, - {credential: inventorySourceData.credential}, - {overwrite: inventorySourceData.overwrite}, - {overwrite_vars: inventorySourceData.overwrite_vars}, - {update_on_launch: inventorySourceData.update_on_launch}, - {update_cache_timeout: inventorySourceData.update_cache_timeout}, - {instance_filters: inventorySourceData.instance_filters}, - {inventory_script: inventorySourceData.source_script} - ); - if(inventorySourceData.source === ('ec2' || 'openstack' || 'custom' || 'vmware')){ - $scope[inventorySourceData.source + '_variables'] = inventorySourceData.source_vars; - } - if (inventorySourceData.credential){ - GroupManageService.getCredential(inventorySourceData.credential).then(res => $scope.credential_name = res.data.name); - } - $scope = angular.extend($scope, groupData); - $scope.variables = $scope.variables === (null || '') ? '---' : $scope.variables; - $scope.parseType = 'yaml'; - // instantiate lookup fields - if (inventorySourceData.source !== 'custom'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + (inventorySourceData.source === '' ? '' : '?kind=' + (inventorySourceData.source)), - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - else if (inventorySourceData.source === 'ec2'){ - LookUpInit({ - scope: $scope, - url: GetBasePath('credentials') + '?kind=aws', - form: form, - list: CredentialList, - field: 'credential', - input_type: "radio" - }); - } - // equal to case 'rax' || 'azure' || 'azure_rm' || 'vmware' || 'foreman' || 'cloudforms' || 'openstack' || 'custom' - else{ - $scope.inventory_script_name = inventorySourceData.summary_fields.source_script.name; - LookUpInit({ - scope: $scope, - url: GetBasePath('inventory_script'), - form: form, - list: InventoryScriptsList, - field: 'inventory_script', - input_type: "radio" - }); - } - ParseTypeChange({ - scope: $scope, - field_id: 'group_variables', - variable: 'variables', - }); - NotificationsListInit({ - scope: $scope, - url: GetBasePath('inventory_sources'), - id: inventorySourceData.id - }); - RelatedSearchInit({ - scope: $scope, - form: form, - relatedSets: relatedSets - }); - RelatedPaginateInit({ - scope: $scope, - relatedSets: relatedSets - }); - initSources(); - _.forEach(relatedSets, (value, key) => $scope.search(relatedSets[key].iterator)); - }; - init(); - }]; diff --git a/awx/ui/client/src/inventories/manage/groups/groups-list.controller.js b/awx/ui/client/src/inventories/manage/groups/groups-list.controller.js deleted file mode 100644 index e17a43f3be..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups-list.controller.js +++ /dev/null @@ -1,159 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - export default - ['$scope', '$rootScope', '$state', '$stateParams', 'InventoryGroups', 'generateList', 'InventoryUpdate', 'GroupManageService', 'GroupsCancelUpdate', 'ViewUpdateStatus', - 'InventoryManageService', 'groupsUrl', 'SearchInit', 'PaginateInit', 'GetSyncStatusMsg', 'GetHostsStatusMsg', - function($scope, $rootScope, $state, $stateParams, InventoryGroups, generateList, InventoryUpdate, GroupManageService, GroupsCancelUpdate, ViewUpdateStatus, - InventoryManageService, groupsUrl, SearchInit, PaginateInit, GetSyncStatusMsg, GetHostsStatusMsg){ - var list = InventoryGroups, - view = generateList, - pageSize = 20; - $scope.inventory_id = $stateParams.inventory_id; - $scope.groupSelect = function(id){ - var group = $stateParams.group === undefined ? [id] : _($stateParams.group).concat(id).value(); - $state.go('inventoryManage', {inventory_id: $stateParams.inventory_id, group: group}, {reload: true}); - }; - $scope.createGroup = function(){ - $state.go('inventoryManage.addGroup'); - }; - $scope.editGroup = function(id){ - $state.go('inventoryManage.editGroup', {group_id: id}); - }; - $scope.deleteGroup = function(group){ - $scope.toDelete = {}; - angular.extend($scope.toDelete, group); - if($scope.toDelete.total_groups === 0 && $scope.toDelete.total_hosts === 0) { - // This group doesn't have any child groups or hosts - the user is just trying to delete - // the group - $scope.deleteOption = "delete"; - } - $('#group-delete-modal').modal('show'); - }; - $scope.confirmDelete = function(){ - - // Bind an even listener for the modal closing. Trying to $state.go() before the modal closes - // will mean that these two things are running async and the modal may not finish closing before - // the state finishes transitioning. - $('#group-delete-modal').off('hidden.bs.modal').on('hidden.bs.modal', function () { - // Remove the event handler so that we don't end up with multiple bindings - $('#group-delete-modal').off('hidden.bs.modal'); - // Reload the inventory manage page and show that the group has been removed - $state.go('inventoryManage', null, {reload: true}); - }); - - switch($scope.deleteOption){ - case 'promote': - GroupManageService.promote($scope.toDelete.id, $stateParams.inventory_id) - .then(() => { - $('#group-delete-modal').modal('hide'); - }); - break; - case 'delete': - GroupManageService.delete($scope.toDelete.id).then(() => { - $('#group-delete-modal').modal('hide'); - }); - } - }; - $scope.updateGroup = function(group) { - GroupManageService.getInventorySource({group: group.id}).then(res =>InventoryUpdate({ - scope: $scope, - group_id: group.id, - url: res.data.results[0].related.update, - group_name: group.name, - group_source: res.data.results[0].source - })); - $scope.$emit('WatchUpdateStatus'); // init socket io conneciton and start watching for status updates - $rootScope.$on('JobStatusChange-inventory', (event, data) => { - switch(data.status){ - case 'failed' || 'successful': - $state.reload(); - break; - default: - var status = GetSyncStatusMsg({ - status: data.status, - has_inventory_sources: group.has_inventory_sources, - source: group.source - }); - group.status = data.status; - group.status_class = status.class; - group.status_tooltip = status.tooltip; - group.launch_tooltip = status.launch_tip; - group.launch_class = status.launch_class; - } - }); - }; - $scope.cancelUpdate = function (id) { - GroupsCancelUpdate({ scope: $scope, id: id }); - }; - $scope.viewUpdateStatus = function (id) { - ViewUpdateStatus({ - scope: $scope, - group_id: id - }); - }; - $scope.showFailedHosts = function() { - $state.go('inventoryManage', {failed: true}, {reload: true}); - }; - $scope.scheduleGroup = function(id) { - $state.go('inventoryManage.schedules', {id: id}); - }; - // $scope.$parent governed by InventoryManageController, for unified multiSelect options - $scope.$on('multiSelectList.selectionChanged', (event, selection) => { - $scope.$parent.groupsSelected = selection.length > 0 ? true : false; - $scope.$parent.groupsSelectedItems = selection.selectedItems; - }); - $scope.$on('PostRefresh', () => { - $scope.groups.forEach( (group, index) => { - var group_status, hosts_status; - group_status = GetSyncStatusMsg({ - status: group.summary_fields.inventory_source.status, - has_inventory_sources: group.has_inventory_sources, - source: ( (group.summary_fields.inventory_source) ? group.summary_fields.inventory_source.source : null ) - }); - hosts_status = GetHostsStatusMsg({ - active_failures: group.hosts_with_active_failures, - total_hosts: group.total_hosts, - inventory_id: $scope.inventory_id, - group_id: group.id - }); - _.assign($scope.groups[index], - {status_class: group_status.class}, - {status_tooltip: group_status.tooltip}, - {launch_tooltip: group_status.launch_tip}, - {launch_class: group_status.launch_class}, - {hosts_status_tip: hosts_status.tooltip}, - {hosts_status_class: hosts_status.class}, - {source: group.summary_fields.inventory_source ? group.summary_fields.inventory_source.source : null}, - {status: group.summary_fields.inventory_source ? group.summary_fields.inventory_source.status : null}); - }); - }); - $scope.copyMoveGroup = function(id){ - $state.go('inventoryManage.copyMoveGroup', {group_id: id, groups: $stateParams.groups}); - }; - - var init = function(){ - list.basePath = groupsUrl; - view.inject(list,{ - id: 'groups-list', - $scope: $scope, - mode: 'edit' - }); - SearchInit({ - scope: $scope, - list: list, - url: groupsUrl, - set: 'groups' - }); - PaginateInit({ - scope: $scope, - list: list, - url: groupsUrl, - pageSize: pageSize - }); - $scope.search(list.iterator); - }; - init(); - }]; diff --git a/awx/ui/client/src/inventories/manage/groups/groups-list.partial.html b/awx/ui/client/src/inventories/manage/groups/groups-list.partial.html deleted file mode 100644 index 50c687e18e..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups-list.partial.html +++ /dev/null @@ -1,73 +0,0 @@ -
- diff --git a/awx/ui/client/src/inventories/manage/groups/groups.block.less b/awx/ui/client/src/inventories/manage/groups/groups.block.less deleted file mode 100644 index 67deadef22..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups.block.less +++ /dev/null @@ -1,19 +0,0 @@ -.select2-selection.select2-selection--multiple.Form-dropDown{ - height: auto !important; -} -.GroupDelete-help--container{ - margin-right: auto; -} -.GroupDelete .Modal-header{ - margin-bottom: 0; -} -.GroupDelete .modal-body{ - padding-top: 20px; -} -.Inventory-groupManage{ - // ugly hack to avoid the surface area of changing form generator's default classes - .checkbox-inline{ - display: block; - padding-bottom: 5px; - } -} \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/groups/groups.route.js b/awx/ui/client/src/inventories/manage/groups/groups.route.js deleted file mode 100644 index 3f95c9a484..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups.route.js +++ /dev/null @@ -1,51 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ -import {templateUrl} from '../../../shared/template-url/template-url.factory'; -import addController from './groups-add.controller'; -import editController from './groups-edit.controller'; - -var ManageGroupsEdit = { - name: 'inventoryManage.editGroup', - route: '/edit-group?group_id', - ncyBreadcrumb: { - label: "EDIT {{group.name}}" - }, - data: { - mode: 'edit' - }, - resolve: { - groupData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService){ - return GroupManageService.get({id: $stateParams.group_id}).then(res => res.data.results[0]); - }], - inventorySourceData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService){ - return GroupManageService.getInventorySource({group: $stateParams.group_id}).then(res => res.data.results[0]); - }] - }, - views: { - 'form@inventoryManage': { - controller: editController, - templateUrl: templateUrl('inventories/manage/groups/groups-form'), - } - } -}; -var ManageGroupsAdd = { - name: 'inventoryManage.addGroup', - route: '/add-group', - // use a query string to break regex search - ncyBreadcrumb: { - label: "ADD GROUP" - }, - data: { - mode: 'add' - }, - views: { - 'form@inventoryManage': { - controller: addController, - templateUrl: templateUrl('inventories/manage/groups/groups-form'), - } - } -}; -export {ManageGroupsAdd, ManageGroupsEdit}; diff --git a/awx/ui/client/src/inventories/manage/groups/groups.service.js b/awx/ui/client/src/inventories/manage/groups/groups.service.js deleted file mode 100644 index 54ed90dfc7..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/groups.service.js +++ /dev/null @@ -1,113 +0,0 @@ -export default - ['$rootScope', 'Rest', 'GetBasePath', 'ProcessErrors', 'Wait', function($rootScope, Rest, GetBasePath, ProcessErrors, Wait){ - return { - stringifyParams: function(params){ - return _.reduce(params, (result, value, key) => { - return result + key + '=' + value + '&'; - }, ''); - }, - // cute abstractions via fn.bind() - url: function(){ - return ''; - }, - error: function(data, status) { - ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', - msg: 'Call to ' + this.url + '. GET returned: ' + status }); - }, - success: function(data){ - return data; - }, - // HTTP methods - get: function(params){ - Wait('start'); - this.url = GetBasePath('groups') + '?' + this.stringifyParams(params); - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - post: function(group){ - Wait('start'); - this.url = GetBasePath('groups'); - Rest.setUrl(this.url); - return Rest.post(group) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - put: function(group){ - Wait('start'); - this.url = GetBasePath('groups') + group.id; - Rest.setUrl(this.url); - return Rest.put(group) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - delete: function(id){ - Wait('start'); - this.url = GetBasePath('groups') + id; - Rest.setUrl(this.url); - return Rest.destroy() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - getCredential: function(id){ - Wait('start'); - this.url = GetBasePath('credentials') + id; - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - getInventorySource: function(params){ - Wait('start'); - this.url = GetBasePath('inventory_sources') + '?' + this.stringifyParams(params); - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - putInventorySource: function(params, url){ - Wait('start'); - this.url = url; - Rest.setUrl(this.url); - return Rest.put(params) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - // these relationship setters could be consolidated, but verbosity makes the operation feel more clear @ controller level - associateGroup: function(group, target){ - Wait('start'); - this.url = GetBasePath('groups') + target + '/children/'; - Rest.setUrl(this.url); - return Rest.post(group) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - disassociateGroup: function(group, parent){ - Wait('start'); - this.url = GetBasePath('groups') + parent + '/children/'; - Rest.setUrl(this.url); - return Rest.post({id: group, disassociate: 1}) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - promote: function(group, inventory){ - Wait('start'); - this.url = GetBasePath('inventory') + inventory + '/groups/'; - Rest.setUrl(this.url); - return Rest.post({id: group, disassociate: 1}) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - } - }; - }]; diff --git a/awx/ui/client/src/inventories/manage/groups/main.js b/awx/ui/client/src/inventories/manage/groups/main.js deleted file mode 100644 index ffade1862a..0000000000 --- a/awx/ui/client/src/inventories/manage/groups/main.js +++ /dev/null @@ -1,14 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - -import {ManageGroupsAdd, ManageGroupsEdit} from './groups.route'; - -export default - angular.module('manageGroups', []) - .run(['$stateExtender', function($stateExtender){ - $stateExtender.addState(ManageGroupsAdd); - $stateExtender.addState(ManageGroupsEdit); - }]); diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts-list.controller.js b/awx/ui/client/src/inventories/manage/hosts/hosts-list.controller.js deleted file mode 100644 index 13540fb489..0000000000 --- a/awx/ui/client/src/inventories/manage/hosts/hosts-list.controller.js +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - export default - ['$scope', '$rootScope', '$state', '$stateParams', 'InventoryHosts', 'generateList', 'InventoryManageService', 'HostManageService', - 'hostsUrl', 'SearchInit', 'PaginateInit', 'SetStatus', 'Prompt', 'Wait', 'inventoryData', - function($scope, $rootScope, $state, $stateParams, InventoryHosts, generateList, InventoryManageService, HostManageService, - hostsUrl, SearchInit, PaginateInit, SetStatus, Prompt, Wait, inventoryData){ - var list = InventoryHosts, - view = generateList, - pageSize = 20; - $scope.createHost = function(){ - $state.go('inventoryManage.addHost'); - }; - $scope.editHost = function(id){ - $state.go('inventoryManage.editHost', {host_id: id}); - }; - $scope.deleteHost = function(id, name){ - var body = '
Are you sure you want to permanently delete the host below from the inventory?
' + name + '
'; - var action = function(){ - delete $rootScope.promptActionBtnClass; - Wait('start'); - HostManageService.delete(id).then(() => { - $('#prompt-modal').modal('hide'); - $state.go($state.current.name, null, {reload: true}); - Wait('stop'); - }); - }; - // Prompt depends on having $rootScope.promptActionBtnClass available... - Prompt({ - hdr: 'Delete Host', - body: body, - action: action, - actionText: 'DELETE', - }); - $rootScope.promptActionBtnClass = 'Modal-errorButton'; - }; - $scope.copyMoveHost = function(id){ - $state.go('inventoryManage.copyMoveHost', {host_id: id}); - }; - $scope.systemTracking = function(){ - var hostIds = _.map($scope.$parent.hostsSelectedItems, (host) => host.id); - $state.go('systemTracking', { - inventory: inventoryData, - inventoryId: $stateParams.inventory_id, - hosts: $scope.$parent.hostsSelectedItems, - hostIds: hostIds - }); - }; - // $scope.$parent governed by InventoryManageController, for unified multiSelect options - $scope.$on('multiSelectList.selectionChanged', (event, selection) => { - $scope.$parent.hostsSelected = selection.length > 0 ? true : false; - $scope.$parent.hostsSelectedItems = selection.selectedItems; - $scope.$parent.systemTrackingDisabled = selection.length > 0 && selection.length < 3 ? false : true; - $scope.$parent.systemTrackingTooltip = selection.length === 1 ? "Compare host facts over time" : "Compare hosts' facts"; - }); - $scope.$on('PostRefresh', ()=>{ - _.forEach($scope.hosts, (host) => SetStatus({scope: $scope, host: host})); - }); - var init = function(){ - list.basePath = hostsUrl; - view.inject(list,{ - id: 'hosts-list', - scope: $scope, - mode: 'edit' - }); - SearchInit({ - scope: $scope, - list: list, - url: hostsUrl, - set: 'hosts' - }); - PaginateInit({ - scope: $scope, - list: list, - url: hostsUrl, - pageSize: pageSize - }); - $scope.search(list.iterator); - }; - init(); - }]; \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts.route.js b/awx/ui/client/src/inventories/manage/hosts/hosts.route.js deleted file mode 100644 index 54a9c3f7d0..0000000000 --- a/awx/ui/client/src/inventories/manage/hosts/hosts.route.js +++ /dev/null @@ -1,50 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ -import {templateUrl} from '../../../shared/template-url/template-url.factory'; -import addController from './hosts-add.controller'; -import editController from './hosts-edit.controller'; - -var ManageHostsEdit = { - name: 'inventoryManage.editHost', - route: '/edit-host?host_id', - ncyBreadcrumb: { - label: "EDIT {{host.name}}", - }, - data: { - mode: 'edit' - }, - resolve: { - host: ['$stateParams', 'HostManageService', function($stateParams, HostManageService){ - return HostManageService.get({id: $stateParams.host_id}).then(function(res){ - return res.data.results[0]; - }); - }] - }, - views: { - 'form@inventoryManage': { - controller: editController, - templateUrl: templateUrl('inventories/manage/hosts/hosts-form'), - } - } -}; -var ManageHostsAdd = { - name: 'inventoryManage.addHost', - route: '/add-host', - // use a query string to break regex search - ncyBreadcrumb: { - label: "ADD HOST" - }, - data: { - mode: 'add' - }, - views: { - 'form@inventoryManage': { - controller: addController, - templateUrl: templateUrl('inventories/manage/hosts/hosts-form'), - } - } -}; -export {ManageHostsAdd, ManageHostsEdit}; diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts.service.js b/awx/ui/client/src/inventories/manage/hosts/hosts.service.js deleted file mode 100644 index a85a159c8a..0000000000 --- a/awx/ui/client/src/inventories/manage/hosts/hosts.service.js +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$rootScope', 'Rest', 'GetBasePath', 'ProcessErrors', 'Wait', - function($rootScope, Rest, GetBasePath, ProcessErrors, Wait){ - return { - stringifyParams: function(params){ - return _.reduce(params, (result, value, key) => { - return result + key + '=' + value + '&'; - }, ''); - }, - // cute abstractions via fn.bind() - url: function(){ - return ''; - }, - error: function(data, status) { - ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', - msg: 'Call to ' + this.url + '. GET returned: ' + status }); - }, - success: function(data){ - return data; - }, - // HTTP methods - get: function(params){ - Wait('start'); - this.url = GetBasePath('hosts') + '?' + this.stringifyParams(params); - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - post: function(host){ - Wait('start'); - this.url = GetBasePath('hosts'); - Rest.setUrl(this.url); - return Rest.post(host) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - put: function(host){ - Wait('start'); - this.url = GetBasePath('hosts') + host.id; - Rest.setUrl(this.url); - return Rest.put(host) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - delete: function(id){ - Wait('start'); - this.url = GetBasePath('hosts') + id; - Rest.setUrl(this.url); - return Rest.destroy() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - // these relationship setters could be consolidated, but verbosity makes the operation feel more clear @ controller level - associateGroup: function(host, group){ - Wait('start'); - this.url = GetBasePath('groups') + group + '/hosts/'; - Rest.setUrl(this.url); - return Rest.post(host) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - disassociateGroup: function(host, group){ - Wait('start'); - this.url = GetBasePath('groups') + group + '/hosts/'; - Rest.setUrl(this.url); - return Rest.post({id: host.id, disassociate: 1}) - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - } - }; - }]; \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/inventory-manage.block.less b/awx/ui/client/src/inventories/manage/inventory-manage.block.less deleted file mode 100644 index 4bf257dffe..0000000000 --- a/awx/ui/client/src/inventories/manage/inventory-manage.block.less +++ /dev/null @@ -1,3 +0,0 @@ -.InventoryManage-container{ - margin-top: -40px; -} \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/inventory-manage.controller.js b/awx/ui/client/src/inventories/manage/inventory-manage.controller.js index 0588e8ed17..fab1b0334e 100644 --- a/awx/ui/client/src/inventories/manage/inventory-manage.controller.js +++ b/awx/ui/client/src/inventories/manage/inventory-manage.controller.js @@ -3,18 +3,532 @@ * * All Rights Reserved *************************************************/ - export default - ['$scope', '$state', function($scope, $state){ - $scope.groupsSelected = false; - $scope.hostsSelected = false; - $scope.hostsSelectedItems = []; - $scope.groupsSelectedItems = []; - $scope.setAdhocPattern = function(){ - var pattern = _($scope.groupsSelectedItems) - .concat($scope.hostsSelectedItems) - .map(function(item){ - return item.name; - }).value().join(':'); - $state.go('inventoryManage.adhoc', {pattern: pattern}); - }; - }]; \ No newline at end of file + +/** + * @ngdoc function + * @name controllers.function:Inventories + * @description This controller's for the Inventory page + */ + +function InventoriesManage($log, $scope, $rootScope, $location, + $state, $compile, generateList, ClearScope, Empty, Wait, Rest, Alert, + GetBasePath, ProcessErrors, InventoryGroups, + InjectHosts, Find, HostsReload, SearchInit, PaginateInit, GetSyncStatusMsg, + GetHostsStatusMsg, GroupsEdit, InventoryUpdate, GroupsCancelUpdate, + ViewUpdateStatus, GroupsDelete, Store, HostsEdit, HostsDelete, + EditInventoryProperties, ShowJobSummary, + InventoryGroupsHelp, HelpDialog, + GroupsCopy, HostsCopy, $stateParams, ParamPass) { + + var PreviousSearchParams, + url, + hostScope = $scope.$new(); + + ClearScope(); + + // TODO: only display adhoc button if the user has permission to use it. + // TODO: figure out how to get the action-list partial to update so that + // the tooltip can be changed based off things being selected or not. + $scope.adhocButtonTipContents = "Launch adhoc command for the inventory"; + + // watcher for the group list checkbox changes + $scope.$on('multiSelectList.selectionChanged', function(e, selection) { + if (selection.length > 0) { + $scope.groupsSelected = true; + // $scope.adhocButtonTipContents = "Launch adhoc command for the " + // + "selected groups and hosts."; + } else { + $scope.groupsSelected = false; + // $scope.adhocButtonTipContents = "Launch adhoc command for the " + // + "inventory."; + } + $scope.groupsSelectedItems = selection.selectedItems; + }); + + // watcher for the host list checkbox changes + hostScope.$on('multiSelectList.selectionChanged', function(e, selection) { + // you need this so that the event doesn't bubble to the watcher above + // for the host list + e.stopPropagation(); + var trackingButton = angular.element(document.querySelector('.system-tracking')); + trackingButton.html('SYSTEM TRACKING'); + if (selection.length === 0) { + $scope.hostsSelected = false; + } else if (selection.length === 1) { + $scope.systemTrackingTooltip = "Compare host over time"; + $scope.hostsSelected = true; + $scope.systemTrackingDisabled = false; + } else if (selection.length === 2) { + $scope.systemTrackingTooltip = "Compare hosts against each other"; + $scope.hostsSelected = true; + $scope.systemTrackingDisabled = false; + } else { + $scope.hostsSelected = true; + $scope.systemTrackingDisabled = true; + } + $scope.hostsSelectedItems = selection.selectedItems; + }); + + $scope.systemTracking = function() { + var hostIds = _.map($scope.hostsSelectedItems, function(x){ + return x.id; + }); + $state.transitionTo('systemTracking', + { inventory: $scope.inventory, + inventoryId: $scope.inventory.id, + hosts: $scope.hostsSelectedItems, + hostIds: hostIds + }); + }; + + // populates host patterns based on selected hosts/groups + $scope.populateAdhocForm = function() { + var host_patterns = "all"; + if ($scope.hostsSelected || $scope.groupsSelected) { + var allSelectedItems = []; + if ($scope.groupsSelectedItems) { + allSelectedItems = allSelectedItems.concat($scope.groupsSelectedItems); + } + if ($scope.hostsSelectedItems) { + allSelectedItems = allSelectedItems.concat($scope.hostsSelectedItems); + } + if (allSelectedItems) { + host_patterns = _.pluck(allSelectedItems, "name").join(":"); + } + } + $rootScope.hostPatterns = host_patterns; + $state.go('inventoryManage.adhoc'); + }; + + $scope.refreshHostsOnGroupRefresh = false; + $scope.selected_group_id = null; + + Wait('start'); + + + if ($scope.removeHostReloadComplete) { + $scope.removeHostReloadComplete(); + } + $scope.removeHostReloadComplete = $scope.$on('HostReloadComplete', function() { + if ($scope.initial_height) { + var host_height = $('#hosts-container .well').height(), + group_height = $('#group-list-container .well').height(), + new_height; + + if (host_height > group_height) { + new_height = host_height - (host_height - group_height); + } + else if (host_height < group_height) { + new_height = host_height + (group_height - host_height); + } + if (new_height) { + $('#hosts-container .well').height(new_height); + } + $scope.initial_height = null; + } + }); + + if ($scope.removeRowCountReady) { + $scope.removeRowCountReady(); + } + $scope.removeRowCountReady = $scope.$on('RowCountReady', function(e, rows) { + // Add hosts view + $scope.show_failures = false; + InjectHosts({ + group_scope: $scope, + host_scope: hostScope, + inventory_id: $scope.inventory.id, + tree_id: null, + group_id: null, + pageSize: rows + }); + + SearchInit({ scope: $scope, set: 'groups', list: InventoryGroups, url: $scope.inventory.related.root_groups }); + PaginateInit({ scope: $scope, list: InventoryGroups , url: $scope.inventory.related.root_groups, pageSize: rows }); + $scope.search(InventoryGroups.iterator, null, true); + }); + + if ($scope.removeInventoryLoaded) { + $scope.removeInventoryLoaded(); + } + $scope.removeInventoryLoaded = $scope.$on('InventoryLoaded', function() { + var rows; + generateList.inject(InventoryGroups, { + mode: 'edit', + id: 'group-list-container', + searchSize: 'col-lg-6 col-md-6 col-sm-6 col-xs-12', + scope: $scope + }); + + rows = 20; + hostScope.host_page_size = rows; + $scope.group_page_size = rows; + + $scope.show_failures = false; + InjectHosts({ + group_scope: $scope, + host_scope: hostScope, + inventory_id: $scope.inventory.id, + tree_id: null, + group_id: null, + pageSize: rows + }); + + // Load data + SearchInit({ + scope: $scope, + set: 'groups', + list: InventoryGroups, + url: $scope.inventory.related.root_groups + }); + + PaginateInit({ + scope: $scope, + list: InventoryGroups , + url: $scope.inventory.related.root_groups, + pageSize: rows + }); + + $scope.search(InventoryGroups.iterator, null, true); + + $scope.$emit('WatchUpdateStatus'); // init socket io conneciton and start watching for status updates + }); + + if ($scope.removePostRefresh) { + $scope.removePostRefresh(); + } + $scope.removePostRefresh = $scope.$on('PostRefresh', function(e, set) { + if (set === 'groups') { + $scope.groups.forEach( function(group, idx) { + var stat, hosts_status; + stat = GetSyncStatusMsg({ + status: group.summary_fields.inventory_source.status, + has_inventory_sources: group.has_inventory_sources, + source: ( (group.summary_fields.inventory_source) ? group.summary_fields.inventory_source.source : null ) + }); // from helpers/Groups.js + $scope.groups[idx].status_class = stat['class']; + $scope.groups[idx].status_tooltip = stat.tooltip; + $scope.groups[idx].launch_tooltip = stat.launch_tip; + $scope.groups[idx].launch_class = stat.launch_class; + hosts_status = GetHostsStatusMsg({ + active_failures: group.hosts_with_active_failures, + total_hosts: group.total_hosts, + inventory_id: $scope.inventory.id, + group_id: group.id + }); // from helpers/Groups.js + $scope.groups[idx].hosts_status_tip = hosts_status.tooltip; + $scope.groups[idx].show_failures = hosts_status.failures; + $scope.groups[idx].hosts_status_class = hosts_status['class']; + + $scope.groups[idx].source = (group.summary_fields.inventory_source) ? group.summary_fields.inventory_source.source : null; + $scope.groups[idx].status = (group.summary_fields.inventory_source) ? group.summary_fields.inventory_source.status : null; + + }); + if ($scope.refreshHostsOnGroupRefresh) { + $scope.refreshHostsOnGroupRefresh = false; + HostsReload({ + scope: hostScope, + group_id: $scope.selected_group_id, + inventory_id: $scope.inventory.id, + pageSize: hostScope.host_page_size + }); + } + else { + Wait('stop'); + } + } + }); + + // Load Inventory + url = GetBasePath('inventory') + $stateParams.inventory_id + '/'; + Rest.setUrl(url); + Rest.get() + .success(function (data) { + $scope.inventory = data; + $scope.$emit('InventoryLoaded'); + }) + .error(function (data, status) { + ProcessErrors($scope, data, status, null, { hdr: 'Error!', msg: 'Failed to retrieve inventory: ' + $stateParams.inventory_id + + ' GET returned status: ' + status }); + }); + + // start watching for real-time updates + if ($rootScope.removeWatchUpdateStatus) { + $rootScope.removeWatchUpdateStatus(); + } + $rootScope.removeWatchUpdateStatus = $rootScope.$on('JobStatusChange-inventory', function(e, data) { + var stat, group; + if (data.group_id) { + group = Find({ list: $scope.groups, key: 'id', val: data.group_id }); + if (data.status === "failed" || data.status === "successful") { + if (data.group_id === $scope.selected_group_id || group) { + // job completed, fefresh all groups + $log.debug('Update completed. Refreshing the tree.'); + $scope.refreshGroups(); + } + } + else if (group) { + // incremental update, just update + $log.debug('Status of group: ' + data.group_id + ' changed to: ' + data.status); + stat = GetSyncStatusMsg({ + status: data.status, + has_inventory_sources: group.has_inventory_sources, + source: group.source + }); + $log.debug('changing tooltip to: ' + stat.tooltip); + group.status = data.status; + group.status_class = stat['class']; + group.status_tooltip = stat.tooltip; + group.launch_tooltip = stat.launch_tip; + group.launch_class = stat.launch_class; + } + } + }); + + // Load group on selection + function loadGroups(url) { + SearchInit({ scope: $scope, set: 'groups', list: InventoryGroups, url: url }); + PaginateInit({ scope: $scope, list: InventoryGroups , url: url, pageSize: $scope.group_page_size }); + $scope.search(InventoryGroups.iterator, null, true, false, true); + } + + $scope.refreshHosts = function() { + HostsReload({ + scope: hostScope, + group_id: $scope.selected_group_id, + inventory_id: $scope.inventory.id, + pageSize: hostScope.host_page_size + }); + }; + + $scope.refreshGroups = function() { + $scope.refreshHostsOnGroupRefresh = true; + $scope.search(InventoryGroups.iterator, null, true, false, true); + }; + + $scope.restoreSearch = function() { + // Restore search params and related stuff, plus refresh + // groups and hosts lists + SearchInit({ + scope: $scope, + set: PreviousSearchParams.set, + list: PreviousSearchParams.list, + url: PreviousSearchParams.defaultUrl, + iterator: PreviousSearchParams.iterator, + sort_order: PreviousSearchParams.sort_order, + setWidgets: false + }); + $scope.refreshHostsOnGroupRefresh = true; + $scope.search(InventoryGroups.iterator, null, true, false, true); + }; + + $scope.groupSelect = function(id) { + var groups = [], group = Find({ list: $scope.groups, key: 'id', val: id }); + if($state.params.groups){ + groups.push($state.params.groups); + } + groups.push(group.id); + groups = groups.join(); + $state.transitionTo('inventoryManage', {inventory_id: $state.params.inventory_id, groups: groups}, { notify: false}); + loadGroups(group.related.children, group.id); + $scope.selected_group_id = group.id; + HostsReload({ + scope: hostScope, + group_id: $scope.selected_group_id, + inventory_id: $scope.inventory.id, + pageSize: hostScope.host_page_size + }); + }; + + $scope.createGroup = function () { + PreviousSearchParams = Store('group_current_search_params'); + var params = { + scope: $scope, + inventory_id: $scope.inventory.id, + group_id: $scope.selected_group_id, + mode: 'add' + }; + ParamPass.set(params); + $state.go('inventoryManage.addGroup'); + }; + + $scope.editGroup = function (id) { + PreviousSearchParams = Store('group_current_search_params'); + var params = { + scope: $scope, + inventory_id: $scope.inventory.id, + group_id: id, + mode: 'edit' + }; + ParamPass.set(params); + $state.go('inventoryManage.editGroup', {group_id: id}); + }; + + // Launch inventory sync + $scope.updateGroup = function (id) { + var group = Find({ list: $scope.groups, key: 'id', val: id }); + if (group) { + if (Empty(group.source)) { + // if no source, do nothing. + } else if (group.status === 'updating') { + Alert('Update in Progress', 'The inventory update process is currently running for group ' + + group.name + ' Click the button to monitor the status.', 'alert-info', null, null, null, null, true); + } else { + Wait('start'); + Rest.setUrl(group.related.inventory_source); + Rest.get() + .success(function (data) { + InventoryUpdate({ + scope: $scope, + url: data.related.update, + group_name: data.summary_fields.group.name, + group_source: data.source, + group_id: group.id, + }); + }) + .error(function (data, status) { + ProcessErrors($scope, data, status, null, { hdr: 'Error!', msg: 'Failed to retrieve inventory source: ' + + group.related.inventory_source + ' GET returned status: ' + status }); + }); + } + } + }; + + $scope.cancelUpdate = function (id) { + GroupsCancelUpdate({ scope: $scope, id: id }); + }; + + $scope.viewUpdateStatus = function (id) { + ViewUpdateStatus({ + scope: $scope, + group_id: id + }); + }; + + $scope.scheduleGroup = function(id) { + $state.go('inventoryManageSchedules', { + inventory_id: $scope.inventory.id, id: id + }); + }; + + $scope.copyGroup = function(id) { + PreviousSearchParams = Store('group_current_search_params'); + var params = { + scope: $scope + }; + ParamPass.set(params); + $location.search('groups', null); + $state.go('inventoryManage.copy.group', {group_id: id}); + }; + + $scope.deleteGroup = function (id) { + GroupsDelete({ + scope: $scope, + group_id: id, + inventory_id: $scope.inventory.id + }); + }; + + $scope.editInventoryProperties = function () { + // EditInventoryProperties({ scope: $scope, inventory_id: $scope.inventory.id }); + $location.path('/inventories/' + $scope.inventory.id + '/'); + }; + + hostScope.createHost = function () { + var params = { + host_scope: hostScope, + group_scope: $scope, + mode: 'add', + host_id: null, + selected_group_id: $scope.selected_group_id, + inventory_id: $scope.inventory.id + }; + ParamPass.set(params); + $state.go('inventoryManage.addHost'); + }; + + hostScope.editHost = function (host_id) { + var params = { + host_scope: hostScope, + group_scope: $scope, + mode: 'edit', + host_id: host_id, + inventory_id: $scope.inventory.id + }; + ParamPass.set(params); + $state.go('inventoryManage.editHost', {host_id: host_id}); + }; + + hostScope.deleteHost = function (host_id, host_name) { + HostsDelete({ + parent_scope: $scope, + host_scope: hostScope, + host_id: host_id, + host_name: host_name + }); + }; + + hostScope.copyHost = function(id) { + PreviousSearchParams = Store('group_current_search_params'); + var params = { + group_scope: $scope, + host_scope: hostScope, + host_id: id + }; + + ParamPass.set(params); + + $state.go('inventoryManage.copy.host', {host_id: id}); + }; + + hostScope.showJobSummary = function (job_id) { + ShowJobSummary({ + job_id: job_id + }); + }; + + $scope.showGroupHelp = function (params) { + var opts = { + defn: InventoryGroupsHelp + }; + if (params) { + opts.autoShow = params.autoShow || false; + } + HelpDialog(opts); + } +; + $scope.showHosts = function (group_id, show_failures) { + // Clicked on group + if (group_id !== null) { + Wait('start'); + hostScope.show_failures = show_failures; + $scope.groupSelect(group_id); + hostScope.hosts = []; + $scope.show_failures = show_failures; // turn on failed hosts + // filter in hosts view + } else { + Wait('stop'); + } + }; + + if ($scope.removeGroupDeleteCompleted) { + $scope.removeGroupDeleteCompleted(); + } + $scope.removeGroupDeleteCompleted = $scope.$on('GroupDeleteCompleted', + function() { + $scope.refreshGroups(); + } + ); +} + +export default [ + '$log', '$scope', '$rootScope', '$location', + '$state', '$compile', 'generateList', 'ClearScope', 'Empty', 'Wait', + 'Rest', 'Alert', 'GetBasePath', 'ProcessErrors', + 'InventoryGroups', 'InjectHosts', 'Find', 'HostsReload', + 'SearchInit', 'PaginateInit', 'GetSyncStatusMsg', 'GetHostsStatusMsg', + 'GroupsEdit', 'InventoryUpdate', 'GroupsCancelUpdate', 'ViewUpdateStatus', + 'GroupsDelete', 'Store', 'HostsEdit', 'HostsDelete', + 'EditInventoryProperties', 'ShowJobSummary', 'InventoryGroupsHelp', 'HelpDialog', 'GroupsCopy', + 'HostsCopy', '$stateParams', 'ParamPass', InventoriesManage +]; diff --git a/awx/ui/client/src/inventories/manage/inventory-manage.partial.html b/awx/ui/client/src/inventories/manage/inventory-manage.partial.html index 41e8084a42..7daf685f3f 100644 --- a/awx/ui/client/src/inventories/manage/inventory-manage.partial.html +++ b/awx/ui/client/src/inventories/manage/inventory-manage.partial.html @@ -1,10 +1,152 @@ -
-
+
+
-
-
+
+
+
+
+
+
+ + + + + + + + + + +
+
+
diff --git a/awx/ui/client/src/inventories/manage/inventory-manage.route.js b/awx/ui/client/src/inventories/manage/inventory-manage.route.js index 317f584930..674297bb0a 100644 --- a/awx/ui/client/src/inventories/manage/inventory-manage.route.js +++ b/awx/ui/client/src/inventories/manage/inventory-manage.route.js @@ -6,71 +6,18 @@ import {templateUrl} from '../../shared/template-url/template-url.factory'; import InventoriesManage from './inventory-manage.controller'; -import BreadcrumbsController from './breadcrumbs/breadcrumbs.controller'; -import HostsListController from './hosts/hosts-list.controller'; -import GroupsListController from './groups/groups-list.controller'; export default { name: 'inventoryManage', - url: '/inventories/:inventory_id/manage?{group:int}{failed}', + url: '/inventories/:inventory_id/manage?groups', + templateUrl: templateUrl('inventories/manage/inventory-manage'), + controller: InventoriesManage, data: { activityStream: true, activityStreamTarget: 'inventory', activityStreamId: 'inventory_id' }, - params:{ - group:{ - array: true - }, - failed:{ - value: 'false', - squash: true - } - }, ncyBreadcrumb: { - skip: true // Never display this state in ncy-breadcrumb. - }, - // enforce uniqueness in group param - onEnter: function($stateParams){ - $stateParams.group = _.uniq($stateParams.group); - }, - resolve: { - groupsUrl: ['InventoryManageService', '$stateParams', function(InventoryManageService, $stateParams){ - return !$stateParams.group ? - InventoryManageService.rootGroupsUrl($stateParams.inventory_id) : - InventoryManageService.childGroupsUrl(_.last($stateParams.group)); - }], - hostsUrl: ['InventoryManageService', '$stateParams', function(InventoryManageService, $stateParams){ - // at the root group level - return !$stateParams.group ? - InventoryManageService.rootHostsUrl($stateParams.inventory_id, $stateParams.failed) : - InventoryManageService.childHostsUrl(_.last($stateParams.group, $stateParams.failed)); - }], - inventoryData: ['InventoryManageService', '$stateParams', function(InventoryManageService, $stateParams){ - return InventoryManageService.getInventory($stateParams.inventory_id).then(res => res.data); - }], - breadCrumbData: ['InventoryManageService', '$stateParams', function(InventoryManageService, $stateParams){ - return ( (!$stateParams.group) ? false : InventoryManageService.getBreadcrumbs($stateParams.group).then(res => res.data.results)); - }] - }, - views:{ - // target the ui-view with name "groupBreadcrumbs" at the root template level - 'groupBreadcrumbs@': { - controller: BreadcrumbsController, - templateUrl: templateUrl('inventories/manage/breadcrumbs/breadcrumbs') - }, - '': { - templateUrl: templateUrl('inventories/manage/inventory-manage'), - controller: InventoriesManage - }, - // target ui-views with name@inventoryManage template level - 'groupsList@inventoryManage': { - templateUrl: templateUrl('inventories/manage/groups/groups-list'), - controller: GroupsListController - }, - 'hostsList@inventoryManage': { - template: '
', - controller: HostsListController - } + label: "INVENTORY MANAGE" } }; diff --git a/awx/ui/client/src/inventories/manage/inventory-manage.service.js b/awx/ui/client/src/inventories/manage/inventory-manage.service.js deleted file mode 100644 index d61d27e758..0000000000 --- a/awx/ui/client/src/inventories/manage/inventory-manage.service.js +++ /dev/null @@ -1,63 +0,0 @@ -/************************************************* - * Copyright (c) 2016 Ansible, Inc. - * - * All Rights Reserved - *************************************************/ - - export default - ['$rootScope', 'Rest', 'GetBasePath', 'ProcessErrors', 'Wait', - function($rootScope, Rest, GetBasePath, ProcessErrors, Wait){ - return { - // cute abstractions via fn.bind() - url: function(){ - return ''; - }, - error: function(data, status) { - ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', - msg: 'Call to ' + this.url + '. GET returned: ' + status }); - }, - success: function(data){ - return data; - }, - // data getters - getInventory: function(id){ - Wait('start'); - this.url = GetBasePath('inventory') + id; - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)) - .finally(Wait('stop')); - }, - getBreadcrumbs: function(groups){ - Wait('start'); - this.url = GetBasePath('groups') + '?' + _.map(groups, function(item){ - return '&or__id=' + item; - }).join(''); - Rest.setUrl(this.url); - return Rest.get() - .success(this.success.bind(this)) - .error(this.error.bind(this)); - }, - // these methods generate a query string to pass to PaginateInit(), SearchInit() - // always supply trailing slashes and ? prefix - rootHostsUrl: function(id, failed){ - var url = GetBasePath('inventory') + id + '/hosts' + - (failed === 'true' ? '?has_active_failures=true' : '?'); - return url; - }, - childHostsUrl: function(id, failed){ - var url = GetBasePath('groups') + id + '/hosts' + - (failed === 'true' ? '?has_active_failures=true' : '?'); - return url; - }, - childGroupsUrl: function(id){ - var url = GetBasePath('groups') + id + '/children?'; - return url; - }, - rootGroupsUrl: function(id){ - var url = GetBasePath('inventory') + id+ '/root_groups/'; - return url; - } - }; - }]; diff --git a/awx/ui/client/src/inventories/manage/main.js b/awx/ui/client/src/inventories/manage/main.js index df2b14469e..435db696f7 100644 --- a/awx/ui/client/src/inventories/manage/main.js +++ b/awx/ui/client/src/inventories/manage/main.js @@ -1,28 +1,21 @@ /************************************************* - * Copyright (c) 2016 Ansible, Inc. + * Copyright (c) 2015 Ansible, Inc. * * All Rights Reserved *************************************************/ import route from './inventory-manage.route'; -import InventoryManageService from './inventory-manage.service'; -import HostManageService from './hosts/hosts.service'; -import GroupManageService from './groups/groups.service'; -import hosts from './hosts/main'; -import groups from './groups/main'; -import adhoc from './adhoc/main'; -import copyMove from './copy-move/main'; + +import manageHosts from './manage-hosts/main'; +import manageGroups from './manage-groups/main'; +import copy from './copy/main'; export default angular.module('inventoryManage', [ - hosts.name, - groups.name, - copyMove.name, - adhoc.name + manageHosts.name, + manageGroups.name, + copy.name, ]) - .service('InventoryManageService', InventoryManageService) - .service('HostManageService', HostManageService) - .service('GroupManageService', GroupManageService) .run(['$stateExtender', function($stateExtender) { $stateExtender.addState(route); }]); diff --git a/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.controller.js b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.controller.js new file mode 100644 index 0000000000..6bad2c274a --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.controller.js @@ -0,0 +1,574 @@ +/************************************************* + * Copyright (c) 2016 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ + +function manageGroupsDirectiveController($filter, $location, $log, + $stateParams, $compile, $state, $scope, Rest, Alert, GroupForm, + GenerateForm, Prompt, ProcessErrors, GetBasePath, SetNodeName, + ParseTypeChange, GetSourceTypeOptions, InventoryUpdate, LookUpInit, Empty, + Wait, GetChoices, UpdateGroup, SourceChange, Find, ParseVariableString, + ToJSON, GroupsScheduleListInit, SetSchedulesInnerDialogSize, + CreateSelect2, ToggleNotification, NotificationsListInit, + RelatedSearchInit, RelatedPaginateInit) { + + var vm = this; + + var group_id = $stateParams.group_id, + mode = $state.current.data.mode, + inventory_id = $stateParams.inventory_id, + generator = GenerateForm, + group_created = false, + defaultUrl, + master = {}, + form = GroupForm(), + relatedSets = {}, + choicesReady, group; + + if (mode === 'edit') { + defaultUrl = GetBasePath('groups') + group_id + '/'; + } else { + defaultUrl = (group_id !== undefined) ? GetBasePath('groups') + group_id + '/children/' : + GetBasePath('inventory') + inventory_id + '/groups/'; + } + + Rest.setUrl(defaultUrl); + Rest.get() + .success(function(data) { + group = data; + for (var fld in form.fields) { + if (data[fld]) { + $scope[fld] = data[fld]; + master[fld] = $scope[fld]; + } + } + if(mode === 'edit') { + $scope.variable_url = data.related.variable_data; + $scope.source_url = data.related.inventory_source; + $scope.source_id = data.related.inventory_source.split('/')[4]; + $scope.$emit('LoadSourceData'); + } + }) + .error(function(data, status) { + ProcessErrors($scope, data, status, { + hdr: 'Error!', + msg: 'Failed to retrieve group: ' + defaultUrl + '. GET status: ' + status + }); + }); + + + $scope.parseType = 'yaml'; + + generator.inject(form, { + mode: mode, + id: 'group-manage-panel', + scope: $scope, + related: false, + cancelButton: false + }); + + generator.reset(); + + GetSourceTypeOptions({ + scope: $scope, + variable: 'source_type_options' + }); + + $scope.source = form.fields.source['default']; + $scope.sourcePathRequired = false; + $scope[form.fields.source_vars.parseTypeName] = 'yaml'; + $scope.update_cache_timeout = 0; + $scope.parseType = 'yaml'; + + + function initSourceChange() { + $scope.showSchedulesTab = (mode === 'edit' && $scope.source && $scope.source.value !== "manual") ? true : false; + SourceChange({ + scope: $scope, + form: form + }); + } + + // JT -- this gets called after the properties & properties variables are loaded, and is emitted from (groupLoaded) + if ($scope.removeLoadSourceData) { + $scope.removeLoadSourceData(); + } + $scope.removeLoadSourceData = $scope.$on('LoadSourceData', function() { + ParseTypeChange({ + scope: $scope, + variable: 'variables', + parse_variable: 'parseType', + field_id: 'group_variables' + }); + + NotificationsListInit({ + scope: $scope, + url: GetBasePath('inventory_sources'), + id: $scope.source_id + }); + + if ($scope.source_url) { + // get source data + Rest.setUrl($scope.source_url); + Rest.get() + .success(function(data) { + var fld, i, j, flag, found, set, opts, list; + for (fld in form.fields) { + if (fld === 'checkbox_group') { + for (i = 0; i < form.fields[fld].fields.length; i++) { + flag = form.fields[fld].fields[i]; + if (data[flag.name] !== undefined) { + $scope[flag.name] = data[flag.name]; + master[flag.name] = $scope[flag.name]; + } + } + } + if (fld === 'source') { + found = false; + data.source = (data.source === "") ? "manual" : data.source; + for (i = 0; i < $scope.source_type_options.length; i++) { + if ($scope.source_type_options[i].value === data.source) { + $scope.source = $scope.source_type_options[i]; + found = true; + } + } + if (!found || $scope.source.value === "manual") { + $scope.groupUpdateHide = true; + } else { + $scope.groupUpdateHide = false; + } + master.source = $scope.source; + } else if (fld === 'source_vars') { + // Parse source_vars, converting to YAML. + $scope.source_vars = ParseVariableString(data.source_vars); + master.source_vars = $scope.variables; + } else if (fld === "inventory_script") { + // the API stores it as 'source_script', we call it inventory_script + data.summary_fields.inventory_script = data.summary_fields.source_script; + $scope.inventory_script = data.source_script; + master.inventory_script = $scope.inventory_script; + } else if (fld === "source_regions") { + if (data[fld] === "") { + $scope[fld] = data[fld]; + master[fld] = $scope[fld]; + } else { + $scope[fld] = data[fld].split(","); + master[fld] = $scope[fld]; + } + } else if (data[fld] !== undefined && + fld !== "description" && + fld !== "name" && + fld !== "variables") { + $scope[fld] = data[fld]; + master[fld] = $scope[fld]; + } + + if (form.fields[fld].sourceModel && data.summary_fields && + data.summary_fields[form.fields[fld].sourceModel]) { + $scope[form.fields[fld].sourceModel + '_' + form.fields[fld].sourceField] = + data.summary_fields[form.fields[fld].sourceModel][form.fields[fld].sourceField]; + master[form.fields[fld].sourceModel + '_' + form.fields[fld].sourceField] = + data.summary_fields[form.fields[fld].sourceModel][form.fields[fld].sourceField]; + } + } + relatedSets = form.relatedSets(data.related); + RelatedSearchInit({ + scope: $scope, + form: form, + relatedSets: relatedSets + }); + + RelatedPaginateInit({ + scope: $scope, + relatedSets: relatedSets + }); + initSourceChange(); + + if (data.source_regions) { + if (data.source === 'ec2' || + data.source === 'rax' || + data.source === 'gce' || + data.source === 'azure') { + if (data.source === 'ec2') { + set = $scope.ec2_regions; + } else if (data.source === 'rax') { + set = $scope.rax_regions; + } else if (data.source === 'gce') { + set = $scope.gce_regions; + } else if (data.source === 'azure') { + set = $scope.azure_regions; + } + opts = []; + list = data.source_regions.split(','); + for (i = 0; i < list.length; i++) { + for (j = 0; j < set.length; j++) { + if (list[i] === set[j].value) { + opts.push({ + id: set [j].value, + text: set [j].label + }); + } + } + } + master.source_regions = opts; + CreateSelect2({ + element: "group_source_regions", + multiple: true, + opts: opts + }); + + } + } else { + // If empty, default to all + master.source_regions = [{ + id: 'all', + text: 'All' + }]; + } + if (data.group_by && data.source === 'ec2') { + set = $scope.ec2_group_by; + opts = []; + list = data.group_by.split(','); + for (i = 0; i < list.length; i++) { + for (j = 0; j < set.length; j++) { + if (list[i] === set[j].value) { + opts.push({ + id: set [j].value, + text: set [j].label + }); + } + } + } + master.group_by = opts; + CreateSelect2({ + element: "#group_group_by", + multiple: true, + opts: opts + }); + } + + $scope.group_update_url = data.related.update; + for (set in relatedSets) { + $scope.search(relatedSets[set].iterator); + } + }) + .error(function(data, status) { + $scope.source = ""; + ProcessErrors($scope, data, status, null, { + hdr: 'Error!', + msg: 'Failed to retrieve inventory source. GET status: ' + status + }); + }); + } + }); + + if ($scope.remove$scopeSourceTypeOptionsReady) { + $scope.remove$scopeSourceTypeOptionsReady(); + } + $scope.remove$scopeSourceTypeOptionsReady = $scope.$on('sourceTypeOptionsReady', function() { + if (mode === 'add') { + $scope.source = Find({ + list: $scope.source_type_options, + key: 'value', + val: '' + }); + $scope.showSchedulesTab = false; + } + }); + + choicesReady = 0; + + if ($scope.removeChoicesReady) { + $scope.removeChoicesReady(); + } + $scope.removeChoicesReady = $scope.$on('choicesReadyGroup', function() { + CreateSelect2({ + element: '#group_source', + multiple: false + }); + $scope.$emit('LoadSourceData'); + + choicesReady++; + if (choicesReady === 5) { + if (mode !== 'edit') { + $scope.variables = "---"; + master.variables = $scope.variables; + } + } + }); + + // Load options for source regions + GetChoices({ + scope: $scope, + url: GetBasePath('inventory_sources'), + field: 'source_regions', + variable: 'rax_regions', + choice_name: 'rax_region_choices', + callback: 'choicesReadyGroup' + }); + + GetChoices({ + scope: $scope, + url: GetBasePath('inventory_sources'), + field: 'source_regions', + variable: 'ec2_regions', + choice_name: 'ec2_region_choices', + callback: 'choicesReadyGroup' + }); + + GetChoices({ + scope: $scope, + url: GetBasePath('inventory_sources'), + field: 'source_regions', + variable: 'gce_regions', + choice_name: 'gce_region_choices', + callback: 'choicesReadyGroup' + }); + + GetChoices({ + scope: $scope, + url: GetBasePath('inventory_sources'), + field: 'source_regions', + variable: 'azure_regions', + choice_name: 'azure_region_choices', + callback: 'choicesReadyGroup' + }); + + // Load options for group_by + GetChoices({ + scope: $scope, + url: GetBasePath('inventory_sources'), + field: 'group_by', + variable: 'ec2_group_by', + choice_name: 'ec2_group_by_choices', + callback: 'choicesReadyGroup' + }); + + //Wait('start'); + + if ($scope.removeAddTreeRefreshed) { + $scope.removeAddTreeRefreshed(); + } + $scope.removeAddTreeRefreshed = $scope.$on('GroupTreeRefreshed', function() { + // Clean up + Wait('stop'); + + if ($scope.searchCleanUp) { + $scope.searchCleanup(); + } + try { + //$('#group-modal-dialog').dialog('close'); + } catch (e) { + // ignore + } + }); + + if ($scope.removeSaveComplete) { + $scope.removeSaveComplete(); + } + $scope.removeSaveComplete = $scope.$on('SaveComplete', function(e, error) { + if (!error) { + $scope.formCancel(); + } + }); + + if ($scope.removeFormSaveSuccess) { + $scope.removeFormSaveSuccess(); + } + $scope.removeFormSaveSuccess = $scope.$on('formSaveSuccess', function() { + + // Source data gets stored separately from the group. Validate and store Source + // related fields, then call SaveComplete to wrap things up. + + var parseError = false, + regions, r, i, + group_by, + data = { + group: group_id, + source: (($scope.source && $scope.source.value !== 'manual') ? $scope.source.value : ''), + source_path: $scope.source_path, + credential: $scope.credential, + overwrite: $scope.overwrite, + overwrite_vars: $scope.overwrite_vars, + source_script: $scope.inventory_script, + update_on_launch: $scope.update_on_launch, + update_cache_timeout: ($scope.update_cache_timeout || 0) + }; + + // Create a string out of selected list of regions + if ($scope.source_regions) { + regions = $('#group_source_regions').select2("data"); + r = []; + for (i = 0; i < regions.length; i++) { + r.push(regions[i].id); + } + data.source_regions = r.join(); + } + + if ($scope.source && ($scope.source.value === 'ec2')) { + data.instance_filters = $scope.instance_filters; + // Create a string out of selected list of regions + group_by = $('#group_group_by').select2("data"); + r = []; + for (i = 0; i < group_by.length; i++) { + r.push(group_by[i].id); + } + data.group_by = r.join(); + } + + if ($scope.source && ($scope.source.value === 'ec2')) { + // for ec2, validate variable data + data.source_vars = ToJSON($scope.envParseType, $scope.source_vars, true); + } + + if ($scope.source && ($scope.source.value === 'custom')) { + data.source_vars = ToJSON($scope.envParseType, $scope.extra_vars, true); + } + + if ($scope.source && ($scope.source.value === 'vmware' || + $scope.source.value === 'openstack')) { + data.source_vars = ToJSON($scope.envParseType, $scope.inventory_variables, true); + } + + // the API doesn't expect the credential to be passed with a custom inv script + if ($scope.source && $scope.source.value === 'custom') { + delete(data.credential); + } + + if (!parseError) { + Rest.setUrl($scope.source_url); + Rest.put(data) + .success(function() { + $scope.$emit('SaveComplete', false); + }) + .error(function(data, status) { + $('#group_tabs a:eq(1)').tab('show'); + ProcessErrors($scope, data, status, form, { + hdr: 'Error!', + msg: 'Failed to update group inventory source. PUT status: ' + status + }); + }); + } + }); + $scope.toggleNotification = function(event, notifier_id, column) { + var notifier = this.notification; + try { + $(event.target).tooltip('hide'); + } + catch(e) { + // ignore + } + ToggleNotification({ + scope: $scope, + url: GetBasePath('inventory_sources'), + id: $scope.source_id, + notifier: notifier, + column: column, + callback: 'NotificationRefresh' + }); + }; + // Cancel + $scope.formCancel = function() { + Wait('stop'); + $state.go('inventoryManage', {}, {reload: true}); + }; + + // Save + $scope.saveGroup = function() { + Wait('start'); + var fld, data, json_data; + + try { + + json_data = ToJSON($scope.parseType, $scope.variables, true); + + data = {}; + for (fld in form.fields) { + data[fld] = $scope[fld]; + } + + data.inventory = inventory_id; + + Rest.setUrl(defaultUrl); + if (mode === 'edit' || (mode === 'add' && group_created)) { + Rest.put(data) + .success(function() { + $scope.$emit('formSaveSuccess'); + }) + .error(function(data, status) { + $('#group_tabs a:eq(0)').tab('show'); + ProcessErrors($scope, data, status, form, { + hdr: 'Error!', + msg: 'Failed to update group: ' + group_id + '. PUT status: ' + status + }); + }); + } else { + Rest.post(data) + .success(function(data) { + group_created = true; + group_id = data.id; + $scope.source_url = data.related.inventory_source; + $scope.source_id = $scope.source_url.split('/')[4]; + $scope.$emit('formSaveSuccess'); + }) + .error(function(data, status) { + $('#group_tabs a:eq(0)').tab('show'); + ProcessErrors($scope, data, status, form, { + hdr: 'Error!', + msg: 'Failed to create group: ' + group_id + '. POST status: ' + status + }); + }); + } + } catch (e) { + // ignore. ToJSON will have already alerted the user + } + }; + + // Start the update process + $scope.updateGroup = function() { + if ($scope.source === "manual" || $scope.source === null) { + Alert('Missing Configuration', 'The selected group is not configured for updates. You must first edit the group, provide Source settings, ' + + 'and then run an update.', 'alert-info'); + } else if ($scope.status === 'updating') { + Alert('Update in Progress', 'The inventory update process is currently running for group ' + + $filter('sanitize')($scope.summary_fields.group.name) + '. Use the Refresh button to monitor the status.', 'alert-info', null, null, null, null, true); + } else { + InventoryUpdate({ + scope: $scope, + group_id: group_id, + url: $scope.group_update_url, + group_name: $scope.name, + group_source: $scope.source.value + }); + } + }; + + // Change the lookup and regions when the source changes + $scope.sourceChange = function() { + $scope.credential_name = ""; + $scope.credential = ""; + if ($scope.credential_name_api_error) { + delete $scope.credential_name_api_error; + } + initSourceChange(); + }; + + + angular.extend(vm, { + formCancel : $scope.formCancel, + saveGroup: $scope.saveGroup + }); +} + +export default ['$filter', '$location', '$log', '$stateParams', + '$compile', '$state', '$scope', 'Rest', 'Alert', 'GroupForm', + 'GenerateForm','Prompt', 'ProcessErrors', 'GetBasePath', 'SetNodeName', + 'ParseTypeChange', 'GetSourceTypeOptions', 'InventoryUpdate', 'LookUpInit', + 'Empty', 'Wait', 'GetChoices', 'UpdateGroup', 'SourceChange', 'Find', + 'ParseVariableString', 'ToJSON', 'GroupsScheduleListInit', + 'SetSchedulesInnerDialogSize', 'CreateSelect2', + 'ToggleNotification', 'NotificationsListInit', 'RelatedSearchInit', + 'RelatedPaginateInit', + manageGroupsDirectiveController +]; diff --git a/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.js b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.js new file mode 100644 index 0000000000..b4c3fbff73 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.js @@ -0,0 +1,25 @@ +/************************************************* + * Copyright (c) 2015 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ + +/* jshint unused: vars */ +import manageGroupsDirectiveController from './manage-groups.directive.controller'; + +export default ['templateUrl', 'ParamPass', + function(templateUrl, ParamPass) { + return { + restrict: 'EA', + scope: true, + replace: true, + templateUrl: templateUrl('inventories/manage/manage-groups/directive/manage-groups.directive'), + link: function(scope, element, attrs) { + + }, + controller: manageGroupsDirectiveController, + controllerAs: 'vm', + bindToController: true + }; + } +]; diff --git a/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.partial.html b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.partial.html new file mode 100644 index 0000000000..889e561114 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-groups/directive/manage-groups.directive.partial.html @@ -0,0 +1,5 @@ +
+
+
+
+
diff --git a/awx/ui/client/src/inventories/manage/manage-groups/main.js b/awx/ui/client/src/inventories/manage/manage-groups/main.js new file mode 100644 index 0000000000..b015b64628 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-groups/main.js @@ -0,0 +1,16 @@ +/************************************************* + * Copyright (c) 2015 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ + +import route from './manage-groups.route'; +import manageGroupsDirective from './directive/manage-groups.directive'; + +export default + angular.module('manage-groups', []) + .directive('manageGroups', manageGroupsDirective) + .run(['$stateExtender', function($stateExtender) { + $stateExtender.addState(route.edit); + $stateExtender.addState(route.add); + }]); diff --git a/awx/ui/client/src/inventories/manage/groups/groups-form.partial.html b/awx/ui/client/src/inventories/manage/manage-groups/manage-groups.partial.html similarity index 77% rename from awx/ui/client/src/inventories/manage/groups/groups-form.partial.html rename to awx/ui/client/src/inventories/manage/manage-groups/manage-groups.partial.html index 45ebffb9e3..e39e0984ac 100644 --- a/awx/ui/client/src/inventories/manage/groups/groups-form.partial.html +++ b/awx/ui/client/src/inventories/manage/manage-groups/manage-groups.partial.html @@ -1,4 +1,5 @@
+
diff --git a/awx/ui/client/src/inventories/manage/manage-groups/manage-groups.route.js b/awx/ui/client/src/inventories/manage/manage-groups/manage-groups.route.js new file mode 100644 index 0000000000..8fb8b16952 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-groups/manage-groups.route.js @@ -0,0 +1,36 @@ +/************************************************* + * Copyright (c) 2016 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ +import { + templateUrl +} from '../../../shared/template-url/template-url.factory'; + +export default { + edit: { + name: 'inventoryManage.editGroup', + route: '/:group_id/editGroup', + templateUrl: templateUrl('inventories/manage/manage-groups/manage-groups'), + data: { + group_id: 'group_id', + mode: 'edit' + }, + ncyBreadcrumb: { + label: "INVENTORY EDIT GROUPS" + } + }, + + add: { + name: 'inventoryManage.addGroup', + route: '/addGroup', + templateUrl: templateUrl('inventories/manage/manage-groups/manage-groups'), + ncyBreadcrumb: { + label: "INVENTORY ADD GROUP" + }, + data: { + mode: 'add' + } + }, + +}; diff --git a/awx/ui/client/src/inventories/manage/hosts/main.js b/awx/ui/client/src/inventories/manage/manage-hosts/main.js similarity index 70% rename from awx/ui/client/src/inventories/manage/hosts/main.js rename to awx/ui/client/src/inventories/manage/manage-hosts/main.js index 0d6aeedd1c..90d5cf3e70 100644 --- a/awx/ui/client/src/inventories/manage/hosts/main.js +++ b/awx/ui/client/src/inventories/manage/manage-hosts/main.js @@ -4,10 +4,12 @@ * All Rights Reserved *************************************************/ -import {ManageHostsAdd, ManageHostsEdit} from './hosts.route'; +import {ManageHostsAdd, ManageHostsEdit} from './manage-hosts.route'; +import service from './manage-hosts.service'; export default angular.module('manageHosts', []) + .service('ManageHostsService', service) .run(['$stateExtender', function($stateExtender){ $stateExtender.addState(ManageHostsAdd); $stateExtender.addState(ManageHostsEdit); diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts-add.controller.js b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-add.controller.js similarity index 66% rename from awx/ui/client/src/inventories/manage/hosts/hosts-add.controller.js rename to awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-add.controller.js index 1eefe86020..620a68f1ac 100644 --- a/awx/ui/client/src/inventories/manage/hosts/hosts-add.controller.js +++ b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-add.controller.js @@ -5,16 +5,16 @@ *************************************************/ export default - ['$state', '$stateParams', '$scope', 'HostForm', 'ParseTypeChange', 'GenerateForm', 'HostManageService', - function($state, $stateParams, $scope, HostForm, ParseTypeChange, GenerateForm, HostManageService){ + ['$state', '$stateParams', '$scope', 'HostForm', 'ParseTypeChange', 'GenerateForm', 'ManageHostsService', + function($state, $stateParams, $scope, HostForm, ParseTypeChange, GenerateForm, ManageHostsService){ var generator = GenerateForm, form = HostForm; $scope.parseType = 'yaml'; $scope.extraVars = '---'; $scope.formCancel = function(){ - $state.go('^'); + $state.go('^', null, {reload: true}); }; - $scope.toggleHostEnabled = function(){ + $scope.toggleEnabled = function(){ $scope.host.enabled = !$scope.host.enabled; }; $scope.formSave = function(){ @@ -25,16 +25,8 @@ enabled: $scope.host.enabled, inventory: $stateParams.inventory_id }; - HostManageService.post(params).then(function(res){ - // assign the host to current group if not at the root level - if ($stateParams.group){ - HostManageService.associateGroup(res.data, _.last($stateParams.group)).then(function(){ - $state.go('inventoryManage', null, {reload: true}); - }); - } - else{ - $state.go('inventoryManage', null, {reload: true}); - } + ManageHostsService.post(params).then(function(){ + $state.go('^', null, {reload: true}); }); }; var init = function(){ diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts-edit.controller.js b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-edit.controller.js similarity index 88% rename from awx/ui/client/src/inventories/manage/hosts/hosts-edit.controller.js rename to awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-edit.controller.js index 8e764d95d5..de733124fa 100644 --- a/awx/ui/client/src/inventories/manage/hosts/hosts-edit.controller.js +++ b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts-edit.controller.js @@ -5,13 +5,13 @@ *************************************************/ export default - ['$state', '$stateParams', '$scope', 'HostForm', 'ParseTypeChange', 'GenerateForm', 'HostManageService', 'host', - function($state, $stateParams, $scope, HostForm, ParseTypeChange, GenerateForm, HostManageService, host){ + ['$state', '$stateParams', '$scope', 'HostForm', 'ParseTypeChange', 'GenerateForm', 'ManageHostsService', 'host', + function($state, $stateParams, $scope, HostForm, ParseTypeChange, GenerateForm, ManageHostsService, host){ var generator = GenerateForm, form = HostForm; $scope.parseType = 'yaml'; $scope.formCancel = function(){ - $state.go('^'); + $state.go('^', null, {reload: true}); }; $scope.toggleHostEnabled = function(){ $scope.host.enabled = !$scope.host.enabled; @@ -24,7 +24,7 @@ description: $scope.description, enabled: $scope.host.enabled }; - HostManageService.put(host).then(function(){ + ManageHostsService.put(host).then(function(){ $state.go('^', null, {reload: true}); }); }; diff --git a/awx/ui/client/src/inventories/manage/hosts/hosts-form.partial.html b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.partial.html similarity index 100% rename from awx/ui/client/src/inventories/manage/hosts/hosts-form.partial.html rename to awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.partial.html diff --git a/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.route.js b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.route.js new file mode 100644 index 0000000000..bf349a9e1c --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.route.js @@ -0,0 +1,41 @@ +/************************************************* + * Copyright (c) 2016 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ +import {templateUrl} from '../../../shared/template-url/template-url.factory'; +import addController from './manage-hosts-add.controller'; +import editController from './manage-hosts-edit.controller'; + +var ManageHostsEdit = { + name: 'inventoryManage.editHost', + route: '/host/:host_id', + controller: editController, + templateUrl: templateUrl('inventories/manage/manage-hosts/manage-hosts'), + ncyBreadcrumb: { + label: "INVENTORY EDIT HOSTS" + }, + data: { + mode: 'edit' + }, + resolve: { + host: ['$stateParams', 'ManageHostsService', function($stateParams, ManageHostsService){ + return ManageHostsService.get({id: $stateParams.host_id}).then(function(res){ + return res.data.results[0]; + }); + }] + } +}; +var ManageHostsAdd = { + name: 'inventoryManage.addHost', + route: '/host/add', + controller: addController, + templateUrl: templateUrl('inventories/manage/manage-hosts/manage-hosts'), + ncyBreadcrumb: { + label: "INVENTORY ADD HOST" + }, + data: { + mode: 'add' + } +}; +export {ManageHostsAdd, ManageHostsEdit}; diff --git a/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.service.js b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.service.js new file mode 100644 index 0000000000..c7a64cb60d --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage-hosts/manage-hosts.service.js @@ -0,0 +1,53 @@ +/************************************************* + * Copyright (c) 2016 Ansible, Inc. + * + * All Rights Reserved + *************************************************/ + + export default + ['$rootScope', 'Rest', 'GetBasePath', 'ProcessErrors', + function($rootScope, Rest, GetBasePath, ProcessErrors){ + return { + stringifyParams: function(params){ + return _.reduce(params, (result, value, key) => { + return result + key + '=' + value + '&'; + }, ''); + }, + get: function(params){ + var url = GetBasePath('hosts') + '?' + this.stringifyParams(params); + Rest.setUrl(url); + return Rest.get() + .success(function(res){ + return res; + }) + .error(function(data, status) { + ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', + msg: 'Call to ' + url + '. GET returned: ' + status }); + }); + }, + post: function(params){ + var url = GetBasePath('hosts'); + Rest.setUrl(url); + return Rest.post(params) + .success(function(res){ + return res; + }) + .error(function(data, status) { + ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', + msg: 'Call to ' + url + '. GET returned: ' + status }); + }); + }, + put: function(host){ + var url = GetBasePath('hosts') + host.id; + Rest.setUrl(url); + return Rest.put(host) + .success(function(res){ + return res; + }) + .error(function(data, status) { + ProcessErrors($rootScope, data, status, null, { hdr: 'Error!', + msg: 'Call to ' + url + '. GET returned: ' + status }); + }); + } + }; + }]; \ No newline at end of file diff --git a/awx/ui/client/src/inventories/manage/manage.block.less b/awx/ui/client/src/inventories/manage/manage.block.less new file mode 100644 index 0000000000..772423c2e4 --- /dev/null +++ b/awx/ui/client/src/inventories/manage/manage.block.less @@ -0,0 +1,18 @@ +#Inventory-groupManage--panel, +#Inventory-hostManage--panel { + .ui-dialog-buttonpane.ui-widget-content { + border: none; + text-align: right; + } + + #host-panel-form, + #properties-tab { + .Form-header { + margin-top: -20px; + } + } + + .Form-textArea { + width: 100%; + } +} diff --git a/awx/ui/client/src/inventory-scripts/edit/edit.controller.js b/awx/ui/client/src/inventory-scripts/edit/edit.controller.js index 5b585ec49d..a9515d60a5 100644 --- a/awx/ui/client/src/inventory-scripts/edit/edit.controller.js +++ b/awx/ui/client/src/inventory-scripts/edit/edit.controller.js @@ -61,11 +61,10 @@ export default data.summary_fields[form.fields[fld].sourceModel][form.fields[fld].sourceField]; } } - $scope.canEdit = data.script !== null; + $scope.canEdit = data['script'] !== null; if (!$scope.canEdit) { $scope.script = "Script contents hidden"; } - $scope.inventory_script_obj = data; Wait('stop'); }) .error(function (data, status) { diff --git a/awx/ui/client/src/inventory-scripts/edit/edit.route.js b/awx/ui/client/src/inventory-scripts/edit/edit.route.js index 968b049afa..7acc9c6c05 100644 --- a/awx/ui/client/src/inventory-scripts/edit/edit.route.js +++ b/awx/ui/client/src/inventory-scripts/edit/edit.route.js @@ -12,10 +12,6 @@ export default { templateUrl: templateUrl('inventory-scripts/edit/edit'), controller: 'inventoryScriptsEditController', params: {inventory_script: null}, - ncyBreadcrumb: { - parent: 'inventoryScripts', - label: "{{inventory_script_obj.name}}" - }, resolve: { inventory_script: [ '$state', diff --git a/awx/ui/client/src/inventory-scripts/list/list.controller.js b/awx/ui/client/src/inventory-scripts/list/list.controller.js index c7a2b3e404..293bd7c4a4 100644 --- a/awx/ui/client/src/inventory-scripts/list/list.controller.js +++ b/awx/ui/client/src/inventory-scripts/list/list.controller.js @@ -7,11 +7,11 @@ export default [ '$rootScope','Wait', 'generateList', 'inventoryScriptsListObject', 'GetBasePath' , 'SearchInit' , 'PaginateInit', - 'Rest' , 'ProcessErrors', 'Prompt', '$state', '$location', + 'Rest' , 'ProcessErrors', 'Prompt', '$state', function( $rootScope,Wait, GenerateList, inventoryScriptsListObject, GetBasePath, SearchInit, PaginateInit, - Rest, ProcessErrors, Prompt, $state, $location + Rest, ProcessErrors, Prompt, $state ) { var scope = $rootScope.$new(), defaultUrl = GetBasePath('inventory_scripts'), @@ -59,9 +59,6 @@ export default Rest.destroy() .success(function () { scope.search(list.iterator); - if (new RegExp('/' + id + '$').test($location.$$url)) { - $state.go('^'); - } }) .error(function (data, status) { ProcessErrors(scope, data, status, null, { hdr: 'Error!', diff --git a/awx/ui/client/src/job-detail/host-event/host-event-codemirror.partial.html b/awx/ui/client/src/job-detail/host-event/host-event-codemirror.partial.html deleted file mode 100644 index 7c744d2169..0000000000 --- a/awx/ui/client/src/job-detail/host-event/host-event-codemirror.partial.html +++ /dev/null @@ -1,2 +0,0 @@ - diff --git a/awx/ui/client/src/job-detail/host-event/host-event-details.partial.html b/awx/ui/client/src/job-detail/host-event/host-event-details.partial.html index 60cd44a9b7..f650b4335a 100644 --- a/awx/ui/client/src/job-detail/host-event/host-event-details.partial.html +++ b/awx/ui/client/src/job-detail/host-event/host-event-details.partial.html @@ -1,5 +1,8 @@
-
EVENT
+
+
EVENT
+ +
HOST diff --git a/awx/ui/client/src/job-detail/host-event/host-event-json.partial.html b/awx/ui/client/src/job-detail/host-event/host-event-json.partial.html new file mode 100644 index 0000000000..a574043dbd --- /dev/null +++ b/awx/ui/client/src/job-detail/host-event/host-event-json.partial.html @@ -0,0 +1,2 @@ + \ No newline at end of file diff --git a/awx/ui/client/src/job-detail/host-event/host-event-modal.partial.html b/awx/ui/client/src/job-detail/host-event/host-event-modal.partial.html index a48f9de95e..919617a333 100644 --- a/awx/ui/client/src/job-detail/host-event/host-event-modal.partial.html +++ b/awx/ui/client/src/job-detail/host-event/host-event-modal.partial.html @@ -12,25 +12,24 @@
- - - - + + +
-
+
- - - + + +
-
+ \ No newline at end of file diff --git a/awx/ui/client/src/job-detail/host-event/host-event-stdout.partial.html b/awx/ui/client/src/job-detail/host-event/host-event-stdout.partial.html new file mode 100644 index 0000000000..29f3966e86 --- /dev/null +++ b/awx/ui/client/src/job-detail/host-event/host-event-stdout.partial.html @@ -0,0 +1,2 @@ + \ No newline at end of file diff --git a/awx/ui/client/src/job-detail/host-event/host-event.block.less b/awx/ui/client/src/job-detail/host-event/host-event.block.less index 4df56a4d8c..c18360ca8d 100644 --- a/awx/ui/client/src/job-detail/host-event/host-event.block.less +++ b/awx/ui/client/src/job-detail/host-event/host-event.block.less @@ -2,38 +2,6 @@ @import "awx/ui/client/src/shared/branding/colors.default.less"; @import "awx/ui/client/src/shared/layouts/one-plus-two.less"; -@media screen and (min-width: 768px){ - .HostEvent .modal-dialog{ - width: 700px; - } -} -.HostEvent .CodeMirror{ - overflow-x: hidden; -} -.HostEvent-controls button.HostEvent-close{ - color: #FFFFFF; - text-transform: uppercase; - padding-left: 15px; - padding-right: 15px; - background-color: @default-link; - &:hover{ - background-color: @default-link-hov; - } -} -.HostEvent-body{ - margin-bottom: 10px; -} -.HostEvent-tab--selected{ - background-color: #D7D7D7 !important; - border-color: #D7D7D7 !important; -} -.HostEvent-view--container{ - width: 100%; - display: flex; - flex-direction: row; - flex-wrap: nowrap; - justify-content: space-between; -} .HostEvent .modal-footer{ border: 0; margin-top: 0px; @@ -62,8 +30,7 @@ } .HostEvent-title{ color: @default-interface-txt; - font-weight: 600; - margin-bottom: 8px; + font-weight: 600; } .HostEvent .modal-body{ max-height: 500px; @@ -76,12 +43,11 @@ } .HostEvent-field{ margin-bottom: 8px; - flex: 0 1 12em; } .HostEvent-field--label{ - text-transform: uppercase; - flex: 0 1 80px; - max-width: 80px; + .OnePlusTwo-left--detailsLabel; + width: 80px; + margin-right: 20px; font-size: 12px; word-wrap: break-word; } @@ -89,20 +55,21 @@ .OnePlusTwo-left--detailsRow; } .HostEvent-field--content{ - flex: 0 1 13em; + .OnePlusTwo-left--detailsContent; } .HostEvent-details--left, .HostEvent-details--right{ - flex: 1 1 47%; + vertical-align:top; + width:265px; + display: inline-block; } .HostEvent-details--left{ - margin-right: 40px; + margin-right: 10px; } .HostEvent-details--right{ .HostEvent-field--label{ - flex: 0 1 25em; + width: auto; } .HostEvent-field--content{ - flex: 0 1 15em; - align-self: flex-end; + text-align: right; } -} +} \ No newline at end of file diff --git a/awx/ui/client/src/job-detail/host-event/host-event.controller.js b/awx/ui/client/src/job-detail/host-event/host-event.controller.js index f86452b005..280c7256a6 100644 --- a/awx/ui/client/src/job-detail/host-event/host-event.controller.js +++ b/awx/ui/client/src/job-detail/host-event/host-event.controller.js @@ -6,8 +6,8 @@ export default - ['$stateParams', '$scope', '$state', 'Wait', 'JobDetailService', 'hostEvent', 'hostResults', - function($stateParams, $scope, $state, Wait, JobDetailService, hostEvent, hostResults){ + ['$stateParams', '$scope', '$state', 'Wait', 'JobDetailService', 'hostEvent', + function($stateParams, $scope, $state, Wait, JobDetailService, hostEvent){ $scope.processEventStatus = JobDetailService.processEventStatus; $scope.hostResults = []; @@ -17,24 +17,15 @@ if (typeof value === 'object'){return false;} else {return true;} }; - $scope.isStdOut = function(){ - if ($state.current.name === 'jobDetails.host-event.stdout' || $state.current.name === 'jobDetaisl.histe-event.stderr'){ - return 'StandardOut-preContainer StandardOut-preContent'; - } - }; - /*ignore jslint start*/ - var initCodeMirror = function(el, data, mode){ - var container = document.getElementById(el); - var editor = CodeMirror.fromTextArea(container, { // jshint ignore:line + //var CodeMirror; + var codeMirror = function(el, json){ + var container = $(el)[0]; + var editor = codeMirror.fromTextArea(container, { lineNumbers: true, - mode: mode - }); + mode: {name: "javascript", json: true} + }); editor.setSize("100%", 300); - editor.getDoc().setValue(data); - }; - /*ignore jslint end*/ - $scope.isActiveState = function(name){ - return $state.current.name === name; + editor.getDoc().setValue(JSON.stringify(json, null, 4)); }; $scope.getActiveHostIndex = function(){ @@ -65,44 +56,23 @@ }; var init = function(){ - $scope.event = _.cloneDeep(hostEvent); - $scope.hostResults = hostResults; - $scope.json = JobDetailService.processJson(hostEvent); - - // grab standard out & standard error if present, and remove from the results displayed in the details panel - if (hostEvent.event_data.res.stdout){ - $scope.stdout = hostEvent.event_data.res.stdout; - delete $scope.event.event_data.res.stdout; - } - if (hostEvent.event_data.res.stderr){ - $scope.stderr = hostEvent.event_data.res.stderr; - delete $scope.event.event_data.res.stderr; - } - // instantiate Codemirror - // try/catch pattern prevents the abstract-state controller from complaining about element being null + $scope.event = hostEvent; + JobDetailService.getJobEventChildren($stateParams.taskId).success(function(res){ + $scope.hostResults = res.results; + }); + $scope.json = JobDetailService.processJson($scope.event); if ($state.current.name === 'jobDetail.host-event.json'){ - try{ - initCodeMirror('HostEvent-codemirror', JSON.stringify($scope.json, null, 4), {name: "javascript", json: true}); - } - catch(err){ - // element with id HostEvent-codemirror is not the view controlled by this instance of HostEventController + codeMirror('#HostEvent-json', $scope.json); + } + try { + $scope.stdout = JobDetailService + .processJson($scope.event.event_data.res); + if ($state.current.name === 'jobDetail.host-event.stdout'){ + codeMirror('#HostEvent-stdout', $scope.stdout); } } - else if ($state.current.name === 'jobDetail.host-event.stdout'){ - try{ - initCodeMirror('HostEvent-codemirror', $scope.stdout, 'shell'); - } - catch(err){ - // element with id HostEvent-codemirror is not the view controlled by this instance of HostEventController - } - } - else if ($state.current.name === 'jobDetail.host-event.stderr'){ - try{ - initCodeMirror('HostEvent-codemirror', $scope.stderr, 'shell'); - } - catch(err){ - // element with id HostEvent-codemirror is not the view controlled by this instance of HostEventController - } + catch(err){ + $scope.sdout = null; } $('#HostEvent').modal('show'); }; diff --git a/awx/ui/client/src/job-detail/host-event/host-event.route.js b/awx/ui/client/src/job-detail/host-event/host-event.route.js index 885034b747..c1e14bd91a 100644 --- a/awx/ui/client/src/job-detail/host-event/host-event.route.js +++ b/awx/ui/client/src/job-detail/host-event/host-event.route.js @@ -11,18 +11,14 @@ var hostEventModal = { url: '/task/:taskId/host-event/:eventId', controller: 'HostEventController', templateUrl: templateUrl('job-detail/host-event/host-event-modal'), - 'abstract': true, resolve: { hostEvent: ['JobDetailService','$stateParams', function(JobDetailService, $stateParams) { return JobDetailService.getRelatedJobEvents($stateParams.id, { id: $stateParams.eventId }).then(function(res){ return res.data.results[0];}); - }], - hostResults: ['JobDetailService', '$stateParams', function(JobDetailService, $stateParams){ - return JobDetailService.getJobEventChildren($stateParams.taskId).then(res => res.data.results); }] }, - onExit: function() { + onExit: function(){ // close the modal // using an onExit event to handle cases where the user navs away using the url bar / back and not modal "X" $('#HostEvent').modal('hide'); @@ -36,29 +32,21 @@ var hostEventModal = { name: 'jobDetail.host-event.details', url: '/details', controller: 'HostEventController', - templateUrl: templateUrl('job-detail/host-event/host-event-details') + templateUrl: templateUrl('job-detail/host-event/host-event-details'), }; var hostEventJson = { name: 'jobDetail.host-event.json', url: '/json', controller: 'HostEventController', - templateUrl: templateUrl('job-detail/host-event/host-event-codemirror') + templateUrl: templateUrl('job-detail/host-event/host-event-json') }; var hostEventStdout = { - name: 'jobDetail.host-event.stdout', + name: 'jobDetail.host-event.stdout', url: '/stdout', controller: 'HostEventController', - templateUrl: templateUrl('job-detail/host-event/host-event-codemirror') + templateUrl: templateUrl('job-detail/host-event/host-event-stdout') }; - var hostEventStderr = { - name: 'jobDetail.host-event.stderr', - url: '/stderr', - controller: 'HostEventController', - templateUrl: templateUrl('job-detail/host-event/host-event-codemirror') - }; - - - export {hostEventDetails, hostEventJson, hostEventModal, hostEventStdout, hostEventStderr}; + export {hostEventDetails, hostEventJson, hostEventStdout, hostEventModal}; diff --git a/awx/ui/client/src/job-detail/host-event/main.js b/awx/ui/client/src/job-detail/host-event/main.js index 4379427ff8..0670181f09 100644 --- a/awx/ui/client/src/job-detail/host-event/main.js +++ b/awx/ui/client/src/job-detail/host-event/main.js @@ -5,7 +5,7 @@ *************************************************/ import {hostEventModal, hostEventDetails, - hostEventJson, hostEventStdout, hostEventStderr} from './host-event.route'; + hostEventJson, hostEventStdout} from './host-event.route'; import controller from './host-event.controller'; export default @@ -17,5 +17,4 @@ $stateExtender.addState(hostEventDetails); $stateExtender.addState(hostEventJson); $stateExtender.addState(hostEventStdout); - $stateExtender.addState(hostEventStderr); - }]); + }]); \ No newline at end of file diff --git a/awx/ui/client/src/job-detail/host-events/host-events.block.less b/awx/ui/client/src/job-detail/host-events/host-events.block.less index 7923b24a7b..f5e4137059 100644 --- a/awx/ui/client/src/job-detail/host-events/host-events.block.less +++ b/awx/ui/client/src/job-detail/host-events/host-events.block.less @@ -9,17 +9,6 @@ margin-top: 0px; padding-top: 5px; } -button.HostEvents-close{ - width: 70px; - color: #FFFFFF; - text-transform: uppercase; - padding-left: 15px; - padding-right: 15px; - background-color: @default-link; - &:hover{ - background-color: @default-link-hov; - } -} .HostEvents-status--ok{ color: @green; } @@ -39,6 +28,9 @@ button.HostEvents-close{ max-width: 420px; display: inline-block; } +.HostEvents-close{ + width: 70px; +} .HostEvents-filter--form{ padding-top: 15px; padding-bottom: 15px; diff --git a/awx/ui/client/src/job-detail/host-events/host-events.partial.html b/awx/ui/client/src/job-detail/host-events/host-events.partial.html index 0234712e8e..7fb46f3234 100644 --- a/awx/ui/client/src/job-detail/host-events/host-events.partial.html +++ b/awx/ui/client/src/job-detail/host-events/host-events.partial.html @@ -1,11 +1,11 @@