mirror of
https://github.com/ZwareBear/awx.git
synced 2026-05-14 15:58:38 -05:00
Configure Tower in Tower:
* Add separate Django app for configuration: awx.conf. * Migrate from existing main.TowerSettings model to conf.Setting. * Add settings wrapper to allow get/set/del via django.conf.settings. * Update existing references to tower_settings to use django.conf.settings. * Add a settings registry to allow for each Django app to register configurable settings. * Support setting validation and conversion using Django REST Framework fields. * Add /api/v1/settings/ to display a list of setting categories. * Add /api/v1/settings/<slug>/ to display all settings in a category as a single object. * Allow PUT/PATCH to update setting singleton, DELETE to reset to defaults. * Add "all" category to display all settings across categories. * Add "changed" category to display only settings configured in the database. * Support per-user settings via "user" category (/api/v1/settings/user/). * Support defaults for user settings via "user-defaults" category (/api/v1/settings/user-defaults/). * Update serializer metadata to support category, category_slug and placeholder on OPTIONS responses. * Update serializer metadata to handle child fields of a list/dict. * Hide raw data form in browsable API for OPTIONS and DELETE. * Combine existing licensing code into single "TaskEnhancer" class. * Move license helper functions from awx.api.license into awx.conf.license. * Update /api/v1/config/ to read/verify/update license using TaskEnhancer and settings wrapper. * Add support for caching settings accessed via settings wrapper. * Invalidate cached settings when Setting model changes or is deleted. * Preload all database settings into cache on first access via settings wrapper. * Add support for read-only settings than can update their value depending on other settings. * Use setting_changed signal whenever a setting changes. * Register configurable authentication, jobs, system and ui settings. * Register configurable LDAP, RADIUS and social auth settings. * Add custom fields and validators for URL, LDAP, RADIUS and social auth settings. * Rewrite existing validator for Credential ssh_private_key to support validating private keys, certs or combinations of both. * Get all unit/functional tests working with above changes. * Add "migrate_to_database_settings" command to determine settings to be migrated into the database and comment them out when set in Python settings files. * Add support for migrating license key from file to database. * Remove database-configuable settings from local_settings.py example files. * Update setup role to no longer install files for database-configurable settings. f 94ff6ee More settings work. f af4c4e0 Even more db settings stuff. f 96ea9c0 More settings, attempt at singleton serializer for settings. f 937c760 More work on singleton/category views in API, add code to comment out settings in Python files, work on command to migrate settings to database. f 425b0d3 Minor fixes for sprint demo. f ea402a4 Add support for read-only settings, cleanup license engine, get license support working with DB settings. f ec289e4 Rename migration, minor fixmes, update setup role. f 603640b Rewrite key/cert validator, finish adding social auth fields, hook up signals for setting_changed, use None to imply a setting is not set. f 67d1b5a Get functional/unit tests passing. f 2919b62 Flake8 fixes. f e62f421 Add redbaron to requirements, get file to database migration working (except for license). f c564508 Add support for migrating license file. f 982f767 Add support for regex in social map fields.
This commit is contained in:
@@ -6,6 +6,7 @@ import urllib
|
||||
import logging
|
||||
|
||||
# Django
|
||||
from django.conf import settings
|
||||
from django.utils.timezone import now as tz_now
|
||||
from django.utils.encoding import smart_text
|
||||
|
||||
@@ -16,7 +17,6 @@ from rest_framework import HTTP_HEADER_ENCODING
|
||||
|
||||
# AWX
|
||||
from awx.main.models import UnifiedJob, AuthToken
|
||||
from awx.main.conf import tower_settings
|
||||
|
||||
logger = logging.getLogger('awx.api.authentication')
|
||||
|
||||
@@ -93,7 +93,7 @@ class TokenAuthentication(authentication.TokenAuthentication):
|
||||
|
||||
# Token invalidated due to session limit config being reduced
|
||||
# Session limit reached invalidation will also take place on authentication
|
||||
if tower_settings.AUTH_TOKEN_PER_USER != -1:
|
||||
if settings.AUTH_TOKEN_PER_USER != -1:
|
||||
if not token.in_valid_tokens(now=now):
|
||||
token.invalidate(reason='limit_reached')
|
||||
raise exceptions.AuthenticationFailed(AuthToken.reason_long('limit_reached'))
|
||||
@@ -123,6 +123,8 @@ class TokenGetAuthentication(TokenAuthentication):
|
||||
class LoggedBasicAuthentication(authentication.BasicAuthentication):
|
||||
|
||||
def authenticate(self, request):
|
||||
if not settings.AUTH_BASIC_ENABLED:
|
||||
return
|
||||
ret = super(LoggedBasicAuthentication, self).authenticate(request)
|
||||
if ret:
|
||||
username = ret[0].username if ret[0] else '<none>'
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Django
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
# Tower
|
||||
from awx.conf import fields, register
|
||||
|
||||
|
||||
register(
|
||||
'AUTH_TOKEN_EXPIRATION',
|
||||
field_class=fields.IntegerField,
|
||||
min_value=60,
|
||||
label=_('Idle Time Force Log Out'),
|
||||
help_text=_('Number of seconds that a user is inactive before they will need to login again.'),
|
||||
category=_('Authentication'),
|
||||
category_slug='authentication',
|
||||
)
|
||||
|
||||
register(
|
||||
'AUTH_TOKEN_PER_USER',
|
||||
field_class=fields.IntegerField,
|
||||
min_value=-1,
|
||||
label=_('Maximum number of simultaneous logins'),
|
||||
help_text=_('Maximum number of simultaneous logins a user may have. To disable enter -1.'),
|
||||
category=_('Authentication'),
|
||||
category_slug='authentication',
|
||||
)
|
||||
|
||||
register(
|
||||
'AUTH_BASIC_ENABLED',
|
||||
field_class=fields.BooleanField,
|
||||
label=_('Enable HTTP Basic Auth'),
|
||||
help_text=_('Enable HTTP Basic Auth for the API Browser.'),
|
||||
category=_('Authentication'),
|
||||
category_slug='authentication',
|
||||
)
|
||||
@@ -150,6 +150,7 @@ class APIView(views.APIView):
|
||||
'new_in_230': getattr(self, 'new_in_230', False),
|
||||
'new_in_240': getattr(self, 'new_in_240', False),
|
||||
'new_in_300': getattr(self, 'new_in_300', False),
|
||||
'new_in_310': getattr(self, 'new_in_310', False),
|
||||
}
|
||||
|
||||
def get_description(self, html=False):
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
from rest_framework.exceptions import APIException
|
||||
|
||||
from awx.main.task_engine import TaskSerializer
|
||||
from awx.main.utils import memoize
|
||||
|
||||
|
||||
class LicenseForbids(APIException):
|
||||
status_code = 402
|
||||
default_detail = 'Your Tower license does not allow that.'
|
||||
|
||||
|
||||
@memoize()
|
||||
def get_license(show_key=False, bypass_database=False):
|
||||
"""Return a dictionary representing the license currently in
|
||||
place on this Tower instance.
|
||||
"""
|
||||
license_reader = TaskSerializer()
|
||||
if bypass_database:
|
||||
return license_reader.from_file(show_key=show_key)
|
||||
return license_reader.from_database(show_key=show_key)
|
||||
|
||||
|
||||
def feature_enabled(name, bypass_database=False):
|
||||
"""Return True if the requested feature is enabled, False otherwise.
|
||||
If the feature does not exist, raise KeyError.
|
||||
"""
|
||||
license = get_license(bypass_database=bypass_database)
|
||||
|
||||
# Sanity check: If there is no license, the feature is considered
|
||||
# to be off.
|
||||
if 'features' not in license:
|
||||
return False
|
||||
|
||||
# Return the correct feature flag.
|
||||
return license['features'].get(name, False)
|
||||
|
||||
def feature_exists(name):
|
||||
"""Return True if the requested feature is enabled, False otherwise.
|
||||
If the feature does not exist, raise KeyError.
|
||||
"""
|
||||
license = get_license()
|
||||
|
||||
# Sanity check: If there is no license, the feature is considered
|
||||
# to be off.
|
||||
if 'features' not in license:
|
||||
return False
|
||||
|
||||
return name in license['features']
|
||||
@@ -6,7 +6,7 @@ import sys
|
||||
from optparse import make_option
|
||||
from django.core.management.base import BaseCommand
|
||||
from awx.main.ha import is_ha_environment
|
||||
from awx.main.task_engine import TaskSerializer
|
||||
from awx.main.task_engine import TaskEnhancer
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
@@ -27,8 +27,7 @@ class Command(BaseCommand):
|
||||
|
||||
def handle(self, *args, **kwargs):
|
||||
# Get the license data.
|
||||
license_reader = TaskSerializer()
|
||||
license_data = license_reader.from_database()
|
||||
license_data = TaskEnhancer().validate_enhancements()
|
||||
|
||||
# Does the license have features, at all?
|
||||
# If there is no license yet, then all features are clearly off.
|
||||
|
||||
+15
-10
@@ -29,7 +29,8 @@ class Metadata(metadata.SimpleMetadata):
|
||||
text_attrs = [
|
||||
'read_only', 'label', 'help_text',
|
||||
'min_length', 'max_length',
|
||||
'min_value', 'max_value'
|
||||
'min_value', 'max_value',
|
||||
'category', 'category_slug',
|
||||
]
|
||||
|
||||
for attr in text_attrs:
|
||||
@@ -37,6 +38,10 @@ class Metadata(metadata.SimpleMetadata):
|
||||
if value is not None and value != '':
|
||||
field_info[attr] = force_text(value, strings_only=True)
|
||||
|
||||
placeholder = getattr(field, 'placeholder', serializers.empty)
|
||||
if placeholder is not serializers.empty:
|
||||
field_info['placeholder'] = placeholder
|
||||
|
||||
# Update help text for common fields.
|
||||
serializer = getattr(field, 'parent', None)
|
||||
if serializer:
|
||||
@@ -52,9 +57,10 @@ class Metadata(metadata.SimpleMetadata):
|
||||
'modified': 'Timestamp when this {} was last modified.',
|
||||
}
|
||||
if field.field_name in field_help_text:
|
||||
opts = serializer.Meta.model._meta.concrete_model._meta
|
||||
verbose_name = smart_text(opts.verbose_name)
|
||||
field_info['help_text'] = field_help_text[field.field_name].format(verbose_name)
|
||||
if hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'):
|
||||
opts = serializer.Meta.model._meta.concrete_model._meta
|
||||
verbose_name = smart_text(opts.verbose_name)
|
||||
field_info['help_text'] = field_help_text[field.field_name].format(verbose_name)
|
||||
|
||||
# Indicate if a field has a default value.
|
||||
# FIXME: Still isn't showing all default values?
|
||||
@@ -140,11 +146,10 @@ class Metadata(metadata.SimpleMetadata):
|
||||
# For GET method, remove meta attributes that aren't relevant
|
||||
# when reading a field and remove write-only fields.
|
||||
if method == 'GET':
|
||||
meta.pop('required', None)
|
||||
meta.pop('read_only', None)
|
||||
meta.pop('default', None)
|
||||
meta.pop('min_length', None)
|
||||
meta.pop('max_length', None)
|
||||
attrs_to_remove = ('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder')
|
||||
for attr in attrs_to_remove:
|
||||
meta.pop(attr, None)
|
||||
meta.get('child', {}).pop(attr, None)
|
||||
if meta.pop('write_only', False):
|
||||
actions['GET'].pop(field)
|
||||
|
||||
@@ -160,7 +165,7 @@ class Metadata(metadata.SimpleMetadata):
|
||||
|
||||
# Add version number in which view was added to Tower.
|
||||
added_in_version = '1.2'
|
||||
for version in ('3.0.0', '2.4.0', '2.3.0', '2.2.0', '2.1.0', '2.0.0', '1.4.8', '1.4.5', '1.4', '1.3'):
|
||||
for version in ('3.1.0', '3.0.0', '2.4.0', '2.3.0', '2.2.0', '2.1.0', '2.0.0', '1.4.8', '1.4.5', '1.4', '1.3'):
|
||||
if getattr(view, 'new_in_%s' % version.replace('.', ''), False):
|
||||
added_in_version = version
|
||||
break
|
||||
|
||||
+10
-4
@@ -3,6 +3,7 @@
|
||||
|
||||
# Django REST Framework
|
||||
from rest_framework import renderers
|
||||
from rest_framework.request import override_method
|
||||
|
||||
|
||||
class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer):
|
||||
@@ -30,6 +31,8 @@ class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer):
|
||||
# Set a flag on the view to indiciate to the view/serializer that we're
|
||||
# creating a raw data form for the browsable API. Store the original
|
||||
# request method to determine how to populate the raw data form.
|
||||
if request.method in {'OPTIONS', 'DELETE'}:
|
||||
return
|
||||
try:
|
||||
setattr(view, '_raw_data_form_marker', True)
|
||||
setattr(view, '_raw_data_request_method', request.method)
|
||||
@@ -41,10 +44,13 @@ class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer):
|
||||
def get_rendered_html_form(self, data, view, method, request):
|
||||
# Never show auto-generated form (only raw form).
|
||||
obj = getattr(view, 'object', None)
|
||||
if not self.show_form_for_method(view, method, request, obj):
|
||||
return
|
||||
if method in ('DELETE', 'OPTIONS'):
|
||||
return True # Don't actually need to return a form
|
||||
if obj is None and hasattr(view, 'get_object') and hasattr(view, 'retrieve'):
|
||||
obj = view.get_object()
|
||||
with override_method(view, request, method) as request:
|
||||
if not self.show_form_for_method(view, method, request, obj):
|
||||
return
|
||||
if method in ('DELETE', 'OPTIONS'):
|
||||
return True # Don't actually need to return a form
|
||||
|
||||
def get_filter_form(self, data, view, request):
|
||||
# Don't show filter form in browsable API.
|
||||
|
||||
+6
-59
@@ -40,9 +40,8 @@ from awx.main.models import * # noqa
|
||||
from awx.main.access import get_user_capabilities
|
||||
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.conf import tower_settings
|
||||
|
||||
from awx.api.license import feature_enabled
|
||||
from awx.conf.license import feature_enabled
|
||||
from awx.api.fields import BooleanNullField, CharNullField, ChoiceNullField, EncryptedPasswordField, VerbatimField
|
||||
|
||||
logger = logging.getLogger('awx.api.serializers')
|
||||
@@ -622,9 +621,9 @@ class UnifiedJobSerializer(BaseSerializer):
|
||||
|
||||
def get_result_stdout(self, obj):
|
||||
obj_size = obj.result_stdout_size
|
||||
if obj_size > tower_settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
if obj_size > settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
return "Standard Output too large to display (%d bytes), only download supported for sizes over %d bytes" % (obj_size,
|
||||
tower_settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
return obj.result_stdout
|
||||
|
||||
|
||||
@@ -679,9 +678,9 @@ class UnifiedJobStdoutSerializer(UnifiedJobSerializer):
|
||||
|
||||
def get_result_stdout(self, obj):
|
||||
obj_size = obj.result_stdout_size
|
||||
if obj_size > tower_settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
if obj_size > settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
return "Standard Output too large to display (%d bytes), only download supported for sizes over %d bytes" % (obj_size,
|
||||
tower_settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
return obj.result_stdout
|
||||
|
||||
def get_types(self):
|
||||
@@ -2099,7 +2098,7 @@ class AdHocCommandSerializer(UnifiedJobSerializer):
|
||||
# Load module name choices dynamically from DB settings.
|
||||
if field_name == 'module_name':
|
||||
field_class = serializers.ChoiceField
|
||||
module_name_choices = [(x, x) for x in tower_settings.AD_HOC_COMMANDS]
|
||||
module_name_choices = [(x, x) for x in settings.AD_HOC_COMMANDS]
|
||||
module_name_default = 'command' if 'command' in [x[0] for x in module_name_choices] else ''
|
||||
field_kwargs['choices'] = module_name_choices
|
||||
field_kwargs['required'] = bool(not module_name_default)
|
||||
@@ -2844,58 +2843,6 @@ class ActivityStreamSerializer(BaseSerializer):
|
||||
return summary_fields
|
||||
|
||||
|
||||
class TowerSettingsSerializer(BaseSerializer):
|
||||
|
||||
value = VerbatimField()
|
||||
|
||||
class Meta:
|
||||
model = TowerSettings
|
||||
fields = ('key', 'description', 'category', 'value', 'value_type', 'user')
|
||||
read_only_fields = ('description', 'category', 'value_type', 'user')
|
||||
|
||||
def __init__(self, instance=None, data=serializers.empty, **kwargs):
|
||||
if instance is None and data is not serializers.empty and 'key' in data:
|
||||
try:
|
||||
instance = TowerSettings.objects.get(key=data['key'])
|
||||
except TowerSettings.DoesNotExist:
|
||||
pass
|
||||
super(TowerSettingsSerializer, self).__init__(instance, data, **kwargs)
|
||||
|
||||
def to_representation(self, obj):
|
||||
ret = super(TowerSettingsSerializer, self).to_representation(obj)
|
||||
ret['value'] = getattr(obj, 'value_converted', obj.value)
|
||||
return ret
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if data['key'] not in settings.TOWER_SETTINGS_MANIFEST:
|
||||
raise serializers.ValidationError({'key': ['Key {0} is not a valid settings key.'.format(data['key'])]})
|
||||
ret = super(TowerSettingsSerializer, self).to_internal_value(data)
|
||||
manifest_val = settings.TOWER_SETTINGS_MANIFEST[data['key']]
|
||||
ret['description'] = manifest_val['description']
|
||||
ret['category'] = manifest_val['category']
|
||||
ret['value_type'] = manifest_val['type']
|
||||
return ret
|
||||
|
||||
def validate(self, attrs):
|
||||
manifest = settings.TOWER_SETTINGS_MANIFEST
|
||||
if attrs['key'] not in manifest:
|
||||
raise serializers.ValidationError(dict(key=["Key {0} is not a valid settings key.".format(attrs['key'])]))
|
||||
|
||||
if attrs['value_type'] == 'json':
|
||||
attrs['value'] = json.dumps(attrs['value'])
|
||||
elif attrs['value_type'] == 'list':
|
||||
try:
|
||||
attrs['value'] = ','.join(map(force_text, attrs['value']))
|
||||
except TypeError:
|
||||
attrs['value'] = force_text(attrs['value'])
|
||||
elif attrs['value_type'] == 'bool':
|
||||
attrs['value'] = force_text(bool(attrs['value']))
|
||||
else:
|
||||
attrs['value'] = force_text(attrs['value'])
|
||||
|
||||
return super(TowerSettingsSerializer, self).validate(attrs)
|
||||
|
||||
|
||||
class AuthTokenSerializer(serializers.Serializer):
|
||||
|
||||
username = serializers.CharField()
|
||||
|
||||
@@ -7,3 +7,4 @@
|
||||
{% if new_in_230 %}> _New in Ansible Tower 2.3.0_{% endif %}
|
||||
{% if new_in_240 %}> _New in Ansible Tower 2.4.0_{% endif %}
|
||||
{% if new_in_300 %}> _New in Ansible Tower 3.0.0_{% endif %}
|
||||
{% if new_in_310 %}> _New in Ansible Tower 3.1.0_{% endif %}
|
||||
|
||||
+1
-5
@@ -319,10 +319,6 @@ activity_stream_urls = patterns('awx.api.views',
|
||||
url(r'^(?P<pk>[0-9]+)/$', 'activity_stream_detail'),
|
||||
)
|
||||
|
||||
settings_urls = patterns('awx.api.views',
|
||||
url(r'^$', 'settings_list'),
|
||||
url(r'^reset/$', 'settings_reset'))
|
||||
|
||||
v1_urls = patterns('awx.api.views',
|
||||
url(r'^$', 'api_v1_root_view'),
|
||||
url(r'^ping/$', 'api_v1_ping_view'),
|
||||
@@ -332,7 +328,7 @@ v1_urls = patterns('awx.api.views',
|
||||
url(r'^me/$', 'user_me_list'),
|
||||
url(r'^dashboard/$', 'dashboard_view'),
|
||||
url(r'^dashboard/graphs/jobs/$','dashboard_jobs_graph_view'),
|
||||
url(r'^settings/', include(settings_urls)),
|
||||
url(r'^settings/', include('awx.conf.urls')),
|
||||
url(r'^schedules/', include(schedule_urls)),
|
||||
url(r'^organizations/', include(organization_urls)),
|
||||
url(r'^users/', include(user_urls)),
|
||||
|
||||
+25
-105
@@ -3,14 +3,12 @@
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
import os
|
||||
import cgi
|
||||
import datetime
|
||||
import dateutil
|
||||
import time
|
||||
import socket
|
||||
import sys
|
||||
import errno
|
||||
import logging
|
||||
from base64 import b64encode
|
||||
from collections import OrderedDict
|
||||
@@ -18,7 +16,6 @@ from collections import OrderedDict
|
||||
# Django
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.cache import cache
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.core.exceptions import FieldError
|
||||
from django.db.models import Q, Count
|
||||
@@ -57,7 +54,6 @@ import ansiconv
|
||||
from social.backends.utils import load_backends
|
||||
|
||||
# AWX
|
||||
from awx.main.task_engine import TaskSerializer, TASK_FILE, TEMPORARY_TASK_FILE
|
||||
from awx.main.tasks import send_notifications
|
||||
from awx.main.access import get_user_queryset
|
||||
from awx.main.ha import is_ha_environment
|
||||
@@ -65,7 +61,7 @@ from awx.api.authentication import TaskAuthentication, TokenGetAuthentication
|
||||
from awx.api.utils.decorators import paginated
|
||||
from awx.api.generics import get_view_name
|
||||
from awx.api.generics import * # noqa
|
||||
from awx.api.license import feature_enabled, feature_exists, LicenseForbids
|
||||
from awx.conf.license import get_license, feature_enabled, feature_exists, LicenseForbids
|
||||
from awx.main.models import * # noqa
|
||||
from awx.main.utils import * # noqa
|
||||
from awx.api.permissions import * # noqa
|
||||
@@ -73,7 +69,6 @@ from awx.api.renderers import * # noqa
|
||||
from awx.api.serializers import * # noqa
|
||||
from awx.api.metadata import RoleMetadata
|
||||
from awx.main.utils import emit_websocket_notification
|
||||
from awx.main.conf import tower_settings
|
||||
|
||||
logger = logging.getLogger('awx.api.views')
|
||||
|
||||
@@ -119,7 +114,7 @@ class ApiV1RootView(APIView):
|
||||
data['authtoken'] = reverse('api:auth_token_view')
|
||||
data['ping'] = reverse('api:api_v1_ping_view')
|
||||
data['config'] = reverse('api:api_v1_config_view')
|
||||
data['settings'] = reverse('api:settings_list')
|
||||
data['settings'] = reverse('api:setting_category_list')
|
||||
data['me'] = reverse('api:user_me_list')
|
||||
data['dashboard'] = reverse('api:dashboard_view')
|
||||
data['organizations'] = reverse('api:organization_list')
|
||||
@@ -189,12 +184,15 @@ class ApiV1ConfigView(APIView):
|
||||
def get(self, request, format=None):
|
||||
'''Return various sitewide configuration settings.'''
|
||||
|
||||
license_reader = TaskSerializer()
|
||||
license_data = license_reader.from_database(show_key=request.user.is_superuser or request.user.is_system_auditor)
|
||||
if request.user.is_superuser or request.user.is_system_auditor:
|
||||
license_data = get_license(show_key=True)
|
||||
else:
|
||||
license_data = get_license(show_key=False)
|
||||
if license_data and 'features' in license_data and 'activity_streams' in license_data['features']:
|
||||
license_data['features']['activity_streams'] &= tower_settings.ACTIVITY_STREAM_ENABLED
|
||||
# FIXME: Make the final setting value dependent on the feature?
|
||||
license_data['features']['activity_streams'] &= settings.ACTIVITY_STREAM_ENABLED
|
||||
|
||||
pendo_state = tower_settings.PENDO_TRACKING_STATE if tower_settings.PENDO_TRACKING_STATE in ('off', 'anonymous', 'detailed') else 'off'
|
||||
pendo_state = settings.PENDO_TRACKING_STATE if settings.PENDO_TRACKING_STATE in ('off', 'anonymous', 'detailed') else 'off'
|
||||
|
||||
data = dict(
|
||||
time_zone=settings.TIME_ZONE,
|
||||
@@ -245,19 +243,18 @@ class ApiV1ConfigView(APIView):
|
||||
except Exception:
|
||||
# FIX: Log
|
||||
return Response({"error": "Invalid JSON"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
license_reader = TaskSerializer()
|
||||
try:
|
||||
license_data = license_reader.from_string(data_actual)
|
||||
from awx.main.task_engine import TaskEnhancer
|
||||
license_data = json.loads(data_actual)
|
||||
license_data = TaskEnhancer(**license_data).validate_enhancements()
|
||||
except Exception:
|
||||
# FIX: Log
|
||||
return Response({"error": "Invalid License"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# If the license is valid, write it to disk.
|
||||
# If the license is valid, write it to the database.
|
||||
if license_data['valid_key']:
|
||||
tower_settings.LICENSE = data_actual
|
||||
tower_settings.TOWER_URL_BASE = "{}://{}".format(request.scheme, request.get_host())
|
||||
# Clear cache when license is updated.
|
||||
cache.clear()
|
||||
settings.LICENSE = data_actual
|
||||
settings.TOWER_URL_BASE = "{}://{}".format(request.scheme, request.get_host())
|
||||
return Response(license_data)
|
||||
|
||||
return Response({"error": "Invalid license"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
@@ -266,26 +263,14 @@ class ApiV1ConfigView(APIView):
|
||||
if not request.user.is_superuser:
|
||||
return Response(None, status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
# Remove license file
|
||||
has_error = None
|
||||
for fname in (TEMPORARY_TASK_FILE, TASK_FILE):
|
||||
try:
|
||||
os.remove(fname)
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
has_error = e.errno
|
||||
break
|
||||
|
||||
TowerSettings.objects.filter(key="LICENSE").delete()
|
||||
# Clear cache when license is updated.
|
||||
cache.clear()
|
||||
|
||||
# Only stop mongod if license removal succeeded
|
||||
if has_error is None:
|
||||
try:
|
||||
settings.LICENSE = {}
|
||||
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||
else:
|
||||
except:
|
||||
# FIX: Log
|
||||
return Response({"error": "Failed to remove license (%s)" % has_error}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class DashboardView(APIView):
|
||||
|
||||
view_name = "Dashboard"
|
||||
@@ -554,7 +539,7 @@ class AuthTokenView(APIView):
|
||||
# Note: This header is normally added in the middleware whenever an
|
||||
# auth token is included in the request header.
|
||||
headers = {
|
||||
'Auth-Token-Timeout': int(tower_settings.AUTH_TOKEN_EXPIRATION)
|
||||
'Auth-Token-Timeout': int(settings.AUTH_TOKEN_EXPIRATION)
|
||||
}
|
||||
return Response({'token': token.key, 'expires': token.expires}, headers=headers)
|
||||
if 'username' in request.data:
|
||||
@@ -3590,9 +3575,9 @@ class UnifiedJobStdout(RetrieveAPIView):
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
unified_job = self.get_object()
|
||||
obj_size = unified_job.result_stdout_size
|
||||
if request.accepted_renderer.format != 'txt_download' and obj_size > tower_settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
if request.accepted_renderer.format != 'txt_download' and obj_size > settings.STDOUT_MAX_BYTES_DISPLAY:
|
||||
response_message = "Standard Output too large to display (%d bytes), only download supported for sizes over %d bytes" % (obj_size,
|
||||
tower_settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
settings.STDOUT_MAX_BYTES_DISPLAY)
|
||||
if request.accepted_renderer.format == 'json':
|
||||
return Response({'range': {'start': 0, 'end': 1, 'absolute_end': 1}, 'content': response_message})
|
||||
else:
|
||||
@@ -3689,8 +3674,8 @@ class NotificationTemplateTest(GenericAPIView):
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
obj = self.get_object()
|
||||
notification = obj.generate_notification("Tower Notification Test {} {}".format(obj.id, tower_settings.TOWER_URL_BASE),
|
||||
{"body": "Ansible Tower Test Notification {} {}".format(obj.id, tower_settings.TOWER_URL_BASE)})
|
||||
notification = obj.generate_notification("Tower Notification Test {} {}".format(obj.id, settings.TOWER_URL_BASE),
|
||||
{"body": "Ansible Tower Test Notification {} {}".format(obj.id, settings.TOWER_URL_BASE)})
|
||||
if not notification:
|
||||
return Response({}, status=status.HTTP_400_BAD_REQUEST)
|
||||
else:
|
||||
@@ -3765,71 +3750,6 @@ class ActivityStreamDetail(RetrieveAPIView):
|
||||
# Okay, let it through.
|
||||
return super(ActivityStreamDetail, self).get(request, *args, **kwargs)
|
||||
|
||||
class SettingsList(ListCreateAPIView):
|
||||
|
||||
model = TowerSettings
|
||||
serializer_class = TowerSettingsSerializer
|
||||
authentication_classes = [TokenGetAuthentication] + api_settings.DEFAULT_AUTHENTICATION_CLASSES
|
||||
new_in_300 = True
|
||||
filter_backends = ()
|
||||
|
||||
def get_queryset(self):
|
||||
class SettingsIntermediary(object):
|
||||
def __init__(self, key, description, category, value,
|
||||
value_type, user=None):
|
||||
self.key = key
|
||||
self.description = description
|
||||
self.category = category
|
||||
self.value = value
|
||||
self.value_type = value_type
|
||||
self.user = user
|
||||
|
||||
if not self.request.user.is_superuser:
|
||||
# NOTE: Shortcutting the rbac class due to the merging of the settings manifest and the database
|
||||
# we'll need to extend this more in the future when we have user settings
|
||||
return []
|
||||
all_defined_settings = {}
|
||||
for s in TowerSettings.objects.all():
|
||||
all_defined_settings[s.key] = SettingsIntermediary(s.key,
|
||||
s.description,
|
||||
s.category,
|
||||
s.value_converted,
|
||||
s.value_type,
|
||||
s.user)
|
||||
manifest_settings = settings.TOWER_SETTINGS_MANIFEST
|
||||
settings_actual = []
|
||||
for settings_key in manifest_settings:
|
||||
if settings_key in all_defined_settings:
|
||||
settings_actual.append(all_defined_settings[settings_key])
|
||||
else:
|
||||
m_entry = manifest_settings[settings_key]
|
||||
settings_actual.append(SettingsIntermediary(settings_key,
|
||||
m_entry['description'],
|
||||
m_entry['category'],
|
||||
m_entry['default'],
|
||||
m_entry['type']))
|
||||
return settings_actual
|
||||
|
||||
def delete(self, request, *args, **kwargs):
|
||||
if not request.user.can_access(self.model, 'delete', None):
|
||||
raise PermissionDenied()
|
||||
TowerSettings.objects.all().delete()
|
||||
return Response()
|
||||
|
||||
class SettingsReset(APIView):
|
||||
|
||||
view_name = "Reset a settings value"
|
||||
new_in_300 = True
|
||||
|
||||
def post(self, request):
|
||||
# NOTE: Extend more with user settings
|
||||
if not request.user.can_access(TowerSettings, 'delete', None):
|
||||
raise PermissionDenied()
|
||||
settings_key = request.data.get('key', None)
|
||||
if settings_key is not None:
|
||||
TowerSettings.objects.filter(key=settings_key).delete()
|
||||
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
class RoleList(ListAPIView):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user