1#
2# BitBake Toaster Implementation
3#
4# Copyright (C) 2013        Intel Corporation
5#
6# SPDX-License-Identifier: GPL-2.0-only
7#
8
9# Django settings for Toaster project.
10
11import os
12from pathlib import Path
13from toastermain.logs import LOGGING_SETTINGS
14
15DEBUG = True
16
17# Set to True to see the SQL queries in console
18SQL_DEBUG = False
19if os.environ.get("TOASTER_SQLDEBUG", None) is not None:
20    SQL_DEBUG = True
21
22
23ADMINS = (
24    # ('Your Name', 'your_email@example.com'),
25)
26
27MANAGERS = ADMINS
28
29TOASTER_SQLITE_DEFAULT_DIR = os.environ.get('TOASTER_DIR')
30
31DATABASES = {
32    'default': {
33        # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
34        'ENGINE': 'django.db.backends.sqlite3',
35        # DB name or full path to database file if using sqlite3.
36        'NAME': "%s/toaster.sqlite" % TOASTER_SQLITE_DEFAULT_DIR,
37        'USER': '',
38        'PASSWORD': '',
39        #'HOST': '127.0.0.1', # e.g. mysql server
40        #'PORT': '3306', # e.g. mysql port
41    }
42}
43
44# New in Django 3.2
45DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
46
47# Needed when Using sqlite especially to add a longer timeout for waiting
48# for the database lock to be  released
49# https://docs.djangoproject.com/en/1.6/ref/databases/#database-is-locked-errors
50if 'sqlite' in DATABASES['default']['ENGINE']:
51    DATABASES['default']['OPTIONS'] = { 'timeout': 20 }
52
53# Update as of django 1.8.16 release, the '*' is needed to allow us to connect while running
54# on hosts without explicitly setting the fqdn for the toaster server.
55# See https://docs.djangoproject.com/en/dev/ref/settings/ for info on ALLOWED_HOSTS
56# Previously this setting was not enforced if DEBUG was set but it is now.
57# The previous behavior was such that ALLOWED_HOSTS defaulted to ['localhost','127.0.0.1','::1']
58# and if you bound to 0.0.0.0:<port #> then accessing toaster as localhost or fqdn would both work.
59# To have that same behavior, with a fqdn explicitly enabled you would set
60# ALLOWED_HOSTS= ['localhost','127.0.0.1','::1','myserver.mycompany.com'] for
61# Django >= 1.8.16. By default, we are not enforcing this restriction in
62# DEBUG mode.
63if DEBUG is True:
64    # this will allow connection via localhost,hostname, or fqdn
65    ALLOWED_HOSTS = ['*']
66
67# Local time zone for this installation. Choices can be found here:
68# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
69# although not all choices may be available on all operating systems.
70# In a Windows environment this must be set to your system time zone.
71
72# Always use local computer's time zone, find
73import hashlib
74if 'TZ' in os.environ:
75    TIME_ZONE = os.environ['TZ']
76else:
77    # need to read the /etc/localtime file which is the libc standard
78    # and do a reverse-mapping to /usr/share/zoneinfo/;
79    # since the timezone may match any number of identical timezone definitions,
80
81    zonefilelist = {}
82    ZONEINFOPATH = '/usr/share/zoneinfo/'
83    for dirpath, dirnames, filenames in os.walk(ZONEINFOPATH):
84        for fn in filenames:
85            filepath = os.path.join(dirpath, fn)
86            zonename = filepath.lstrip(ZONEINFOPATH).strip()
87            try:
88                import pytz
89                from pytz.exceptions import UnknownTimeZoneError
90                try:
91                    if pytz.timezone(zonename) is not None:
92                        with open(filepath, 'rb') as f:
93                            zonefilelist[hashlib.md5(f.read()).hexdigest()] = zonename
94                except UnknownTimeZoneError as ValueError:
95                    # we expect timezone failures here, just move over
96                    pass
97            except ImportError:
98                with open(filepath, 'rb') as f:
99                    zonefilelist[hashlib.md5(f.read()).hexdigest()] = zonename
100
101    with open('/etc/localtime', 'rb') as f:
102        TIME_ZONE = zonefilelist[hashlib.md5(f.read()).hexdigest()]
103
104# Language code for this installation. All choices can be found here:
105# http://www.i18nguy.com/unicode/language-identifiers.html
106LANGUAGE_CODE = 'en-us'
107
108SITE_ID = 1
109
110# If you set this to False, Django will make some optimizations so as not
111# to load the internationalization machinery.
112USE_I18N = True
113
114# If you set this to False, Django will not use timezone-aware datetimes.
115USE_TZ = True
116
117# Absolute filesystem path to the directory that will hold user-uploaded files.
118# Example: "/var/www/example.com/media/"
119MEDIA_ROOT = ''
120
121# URL that handles the media served from MEDIA_ROOT. Make sure to use a
122# trailing slash.
123# Examples: "http://example.com/media/", "http://media.example.com/"
124MEDIA_URL = ''
125
126# Absolute path to the directory static files should be collected to.
127# Don't put anything in this directory yourself; store your static files
128# in apps' "static/" subdirectories and in STATICFILES_DIRS.
129# Example: "/var/www/example.com/static/"
130STATIC_ROOT = ''
131
132# URL prefix for static files.
133# Example: "http://example.com/static/", "http://static.example.com/"
134STATIC_URL = '/static/'
135
136# Additional locations of static files
137STATICFILES_DIRS = (
138    # Put strings here, like "/home/html/static" or "C:/www/django/static".
139    # Always use forward slashes, even on Windows.
140    # Don't forget to use absolute paths, not relative paths.
141)
142
143# List of finder classes that know how to find static files in
144# various locations.
145STATICFILES_FINDERS = (
146    'django.contrib.staticfiles.finders.FileSystemFinder',
147    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
148#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
149)
150
151# Make this unique, and don't share it with anybody.
152SECRET_KEY = 'NOT_SUITABLE_FOR_HOSTED_DEPLOYMENT'
153
154TMPDIR = os.environ.get('TOASTER_DJANGO_TMPDIR', '/tmp')
155
156class InvalidString(str):
157    def __mod__(self, other):
158        from django.template.base import TemplateSyntaxError
159        raise TemplateSyntaxError(
160            "Undefined variable or unknown value for: \"%s\"" % other)
161
162TEMPLATES = [
163    {
164        'BACKEND': 'django.template.backends.django.DjangoTemplates',
165        'DIRS': [
166            # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
167            # Always use forward slashes, even on Windows.
168            # Don't forget to use absolute paths, not relative paths.
169        ],
170        'OPTIONS': {
171            'context_processors': [
172                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
173                # list if you haven't customized them:
174                'django.contrib.auth.context_processors.auth',
175                'django.template.context_processors.debug',
176                'django.template.context_processors.i18n',
177                'django.template.context_processors.media',
178                'django.template.context_processors.static',
179                'django.template.context_processors.tz',
180                'django.contrib.messages.context_processors.messages',
181                # Custom
182                'django.template.context_processors.request',
183                'toastergui.views.managedcontextprocessor',
184
185            ],
186            'loaders': [
187                # List of callables that know how to import templates from various sources.
188                'django.template.loaders.filesystem.Loader',
189                'django.template.loaders.app_directories.Loader',
190                #'django.template.loaders.eggs.Loader',
191            ],
192            # https://docs.djangoproject.com/en/4.2/ref/templates/api/#how-invalid-variables-are-handled
193            # Generally, string_if_invalid should only be enabled in order to debug
194            # a specific template problem, then cleared once debugging is complete.
195            # If you assign a value other than '' to string_if_invalid,
196            # you will experience rendering problems with these templates and sites.
197            #  'string_if_invalid': InvalidString("%s"),
198            'string_if_invalid': "",
199            'debug': DEBUG,
200        },
201    },
202]
203
204MIDDLEWARE = [
205    'django.middleware.common.CommonMiddleware',
206    'django.contrib.sessions.middleware.SessionMiddleware',
207    'django.middleware.csrf.CsrfViewMiddleware',
208    'django.contrib.auth.middleware.AuthenticationMiddleware',
209    'django.contrib.messages.middleware.MessageMiddleware',
210    'django.contrib.auth.middleware.AuthenticationMiddleware',
211    'django.contrib.messages.middleware.MessageMiddleware',
212    'django.contrib.sessions.middleware.SessionMiddleware',
213]
214
215CACHES = {
216    #        'default': {
217    #            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
218    #            'LOCATION': '127.0.0.1:11211',
219    #        },
220           'default': {
221               'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
222               'LOCATION': '%s/toaster_cache_%d' % (TMPDIR, os.getuid()),
223               'TIMEOUT': 1,
224            }
225          }
226
227
228from os.path import dirname as DN
229SITE_ROOT=DN(DN(os.path.abspath(__file__)))
230
231import subprocess
232TOASTER_BRANCH = subprocess.Popen('git branch | grep "^* " | tr -d "* "', cwd = SITE_ROOT, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
233TOASTER_REVISION = subprocess.Popen('git rev-parse HEAD ', cwd = SITE_ROOT, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
234
235ROOT_URLCONF = 'toastermain.urls'
236
237# Python dotted path to the WSGI application used by Django's runserver.
238WSGI_APPLICATION = 'toastermain.wsgi.application'
239
240
241INSTALLED_APPS = (
242    'django.contrib.auth',
243    'django.contrib.contenttypes',
244    'django.contrib.messages',
245    'django.contrib.sessions',
246    'django.contrib.admin',
247    'django.contrib.staticfiles',
248
249    # Uncomment the next line to enable admin documentation:
250    # 'django.contrib.admindocs',
251    'django.contrib.humanize',
252    'bldcollector',
253    'toastermain',
254
255    # 3rd-lib
256    "log_viewer",
257)
258
259
260INTERNAL_IPS = ['127.0.0.1', '192.168.2.28']
261
262# Load django-fresh is TOASTER_DEVEL is set, and the module is available
263FRESH_ENABLED = False
264if os.environ.get('TOASTER_DEVEL', None) is not None:
265    try:
266        import fresh
267        MIDDLEWARE = ["fresh.middleware.FreshMiddleware",] + MIDDLEWARE
268        INSTALLED_APPS = INSTALLED_APPS + ('fresh',)
269        FRESH_ENABLED = True
270    except:
271        pass
272
273DEBUG_PANEL_ENABLED = False
274if os.environ.get('TOASTER_DEVEL', None) is not None:
275    try:
276        import debug_toolbar, debug_panel
277        MIDDLEWARE = ['debug_panel.middleware.DebugPanelMiddleware',] + MIDDLEWARE
278        #MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware',]
279        INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar','debug_panel',)
280        DEBUG_PANEL_ENABLED = True
281
282        # this cache backend will be used by django-debug-panel
283        CACHES['debug-panel'] = {
284                'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
285                'LOCATION': '/var/tmp/debug-panel-cache',
286                'TIMEOUT': 300,
287                'OPTIONS': {
288                    'MAX_ENTRIES': 200
289                }
290        }
291
292    except:
293        pass
294
295
296SOUTH_TESTS_MIGRATE = False
297
298
299# We automatically detect and install applications here if
300# they have a 'models.py' or 'views.py' file
301import os
302currentdir = os.path.dirname(__file__)
303for t in os.walk(os.path.dirname(currentdir)):
304    modulename = os.path.basename(t[0])
305    #if we have a virtualenv skip it to avoid incorrect imports
306    if 'VIRTUAL_ENV' in os.environ and os.environ['VIRTUAL_ENV'] in t[0]:
307        continue
308
309    if ("views.py" in t[2] or "models.py" in t[2]) and not modulename in INSTALLED_APPS:
310        INSTALLED_APPS = INSTALLED_APPS + (modulename,)
311
312# A sample logging configuration. The only tangible logging
313# performed by this configuration is to send an email to
314# the site admins on every HTTP 500 error when DEBUG=False.
315# See http://docs.djangoproject.com/en/dev/topics/logging for
316# more details on how to customize your logging configuration.
317LOGGING = LOGGING_SETTINGS
318
319# Build paths inside the project like this: BASE_DIR / 'subdir'.
320BUILDDIR = os.environ.get("BUILDDIR", TMPDIR)
321
322# LOG VIEWER
323# https://pypi.org/project/django-log-viewer/
324LOG_VIEWER_FILES_PATTERN = '*.log*'
325LOG_VIEWER_FILES_DIR = os.path.join(BUILDDIR, "toaster_logs/")
326LOG_VIEWER_PAGE_LENGTH = 25      # total log lines per-page
327LOG_VIEWER_MAX_READ_LINES = 100000  # total log lines will be read
328LOG_VIEWER_PATTERNS = ['INFO', 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL']
329
330# Optionally you can set the next variables in order to customize the admin:
331LOG_VIEWER_FILE_LIST_TITLE = "Logs list"
332
333if DEBUG and SQL_DEBUG:
334    LOGGING['loggers']['django.db.backends'] = {
335            'level': 'DEBUG',
336            'handlers': ['console'],
337        }
338
339
340# If we're using sqlite, we need to tweak the performance a bit
341from django.db.backends.signals import connection_created
342def activate_synchronous_off(sender, connection, **kwargs):
343    if connection.vendor == 'sqlite':
344        cursor = connection.cursor()
345        cursor.execute('PRAGMA synchronous = 0;')
346connection_created.connect(activate_synchronous_off)
347#
348
349