settings.py 13 KB

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