prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Database is open while the server is idle
  ### Observed behavior
  After kolibri starts, the db is kept open, with the journal file created, even if the server is idle, not receiving any query. This has produced corruptions in the db in the past.
  
  ### Expected behavior
  Once the server starts, the db should be closed and not journal should appear while there are not requests  nor jobs happening.
  
  ### User-facing consequences
  
  Possible corruption of the main db
  
  
  ### Steps to reproduce
  
  1. Start Kolibri
  2. don't do any request 
  3. check the files db.sqlite3-wal and db.sqlite3-shm exist in the kolibri folder.
  
  ### Context
  
  Tell us about your environment, including:
   * Kolibri version 0.13.0 
   * Linux
  
  
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `kolibri/utils/sanity_checks.py`
  Content:
  ```
  1 import logging
  2 import os
  3 import shutil
  4 import sys
  5 
  6 import portend
  7 from django.apps import apps
  8 from django.core.management import call_command
  9 from django.db.utils import OperationalError
  10 
  11 from .conf import OPTIONS
  12 from .server import get_status
  13 from .server import LISTEN_ADDRESS
  14 from .server import NotRunning
  15 
  16 logger = logging.getLogger(__name__)
  17 
  18 PORT_AVAILABILITY_CHECK_TIMEOUT = 2
  19 
  20 
  21 def check_other_kolibri_running(port):
  22     """
  23     Make sure there are no other Kolibri instances running before starting the server.
  24     """
  25     try:
  26         # Check if there are other kolibri instances running
  27         # If there are, then we need to stop users from starting kolibri again.
  28         get_status()
  29         logger.error(
  30             "There is another Kolibri server running. "
  31             "Please use `kolibri stop` and try again."
  32         )
  33         sys.exit(1)
  34 
  35     except NotRunning:
  36         # In case that something other than Kolibri occupies the port,
  37         # check the port's availability.
  38         check_port_availability(LISTEN_ADDRESS, port)
  39 
  40 
  41 def check_port_availability(host, port):
  42     """
  43     Make sure the port is available for the server to start.
  44     """
  45     try:
  46         portend.free(host, port, timeout=PORT_AVAILABILITY_CHECK_TIMEOUT)
  47     except portend.Timeout:
  48         # Bypass check when socket activation is used
  49         # https://manpages.debian.org/testing/libsystemd-dev/sd_listen_fds.3.en.html#ENVIRONMENT
  50         if not os.environ.get("LISTEN_PID", None):
  51             # Port is occupied
  52             logger.error(
  53                 "Port {} is occupied.\n"
  54                 "Please check that you do not have other processes "
  55                 "running on this port and try again.\n".format(port)
  56             )
  57             sys.exit(1)
  58 
  59 
  60 def check_content_directory_exists_and_writable():
  61     """
  62     Make sure the content directory of Kolibri exists and is writable.
  63     """
  64     content_directory = OPTIONS["Paths"]["CONTENT_DIR"]
  65 
  66     # Check if the content directory exists
  67     if not os.path.exists(content_directory):
  68         try:
  69             os.makedirs(content_directory)
  70         except OSError:
  71             logger.error(
  72                 "The content directory {} does not exist and cannot be created.".format(
  73                     content_directory
  74                 )
  75             )
  76             sys.exit(1)
  77 
  78     # Check if the directory is writable
  79     if not os.access(content_directory, os.W_OK):
  80         logger.error(
  81             "The content directory {} is not writable.".format(content_directory)
  82         )
  83         sys.exit(1)
  84 
  85 
  86 def check_log_file_location():
  87     """
  88     Starting from Kolibri v0.12.4, log files are going to be renamed and moved
  89     from KOLIBRI_HOME directory to KOLIBRI_HOME/logs directory.
  90     """
  91     home = os.environ["KOLIBRI_HOME"]
  92     log_location_update = {}
  93 
  94     # Old log file names
  95     old_daemon_log = "server.log"
  96     old_kolibri_log = "kolibri.log"
  97     old_debug_log = "debug.log"
  98 
  99     # New log file names
  100     log_location_update[old_daemon_log] = "daemon.txt"
  101     log_location_update[old_kolibri_log] = "kolibri.txt"
  102     log_location_update[old_debug_log] = "debug.txt"
  103 
  104     for log in log_location_update:
  105         old_log_path = os.path.join(home, log)
  106         if os.path.exists(old_log_path):
  107             new_log_path = os.path.join(home, "logs", log_location_update[log])
  108             shutil.move(old_log_path, new_log_path)
  109 
  110 
  111 def migrate_databases():
  112     """
  113     Try to migrate all active databases. This should not be called unless Django has
  114     been initialized.
  115     """
  116     from django.conf import settings
  117 
  118     for database in settings.DATABASES:
  119         call_command("migrate", interactive=False, database=database)
  120 
  121     # load morango fixtures needed for certificate related operations
  122     call_command("loaddata", "scopedefinitions")
  123 
  124 
  125 def check_database_is_migrated():
  126     """
  127     Use a check that the database instance id model is initialized to check if the database
  128     is in a proper state to be used. This must only be run after django initialization.
  129     """
  130     apps.check_apps_ready()
  131     from morango.models import InstanceIDModel
  132 
  133     try:
  134         InstanceIDModel.get_or_create_current_instance()[0]
  135         return
  136     except OperationalError:
  137         try:
  138             migrate_databases()
  139             return
  140         except Exception as e:
  141             logging.error(
  142                 "Tried to migrate the database but another error occurred: {}".format(e)
  143             )
  144     except Exception as e:
  145         logging.error(
  146             "Tried to check that the database was accessible and an error occurred: {}".format(
  147                 e
  148             )
  149         )
  150     sys.exit(1)
  151
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/kolibri/utils/sanity_checks.py b/kolibri/utils/sanity_checks.py
  --- a/kolibri/utils/sanity_checks.py
  +++ b/kolibri/utils/sanity_checks.py
  @@ -128,10 +128,12 @@
       is in a proper state to be used. This must only be run after django initialization.
       """
       apps.check_apps_ready()
  +    from django.db import connection
       from morango.models import InstanceIDModel
   
       try:
           InstanceIDModel.get_or_create_current_instance()[0]
  +        connection.close()
           return
       except OperationalError:
           try:
  
verification_info: {"golden_diff": "diff --git a/kolibri/utils/sanity_checks.py b/kolibri/utils/sanity_checks.py\n--- a/kolibri/utils/sanity_checks.py\n+++ b/kolibri/utils/sanity_checks.py\n@@ -128,10 +128,12 @@\n     is in a proper state to be used. This must only be run after django initialization.\n     \"\"\"\n     apps.check_apps_ready()\n+    from django.db import connection\n     from morango.models import InstanceIDModel\n \n     try:\n         InstanceIDModel.get_or_create_current_instance()[0]\n+        connection.close()\n         return\n     except OperationalError:\n         try:\n", "issue": "Database is open while the server is idle\n### Observed behavior\r\nAfter kolibri starts, the db is kept open, with the journal file created, even if the server is idle, not receiving any query. This has produced corruptions in the db in the past.\r\n\r\n### Expected behavior\r\nOnce the server starts, the db should be closed and not journal should appear while there are not requests  nor jobs happening.\r\n\r\n### User-facing consequences\r\n\r\nPossible corruption of the main db\r\n\r\n\r\n### Steps to reproduce\r\n\r\n1. Start Kolibri\r\n2. don't do any request \r\n3. check the files db.sqlite3-wal and db.sqlite3-shm exist in the kolibri folder.\r\n\r\n### Context\r\n\r\nTell us about your environment, including:\r\n * Kolibri version 0.13.0 \r\n * Linux\r\n\r\n\r\n\n", "before_files": [{"content": "import logging\nimport os\nimport shutil\nimport sys\n\nimport portend\nfrom django.apps import apps\nfrom django.core.management import call_command\nfrom django.db.utils import OperationalError\n\nfrom .conf import OPTIONS\nfrom .server import get_status\nfrom .server import LISTEN_ADDRESS\nfrom .server import NotRunning\n\nlogger = logging.getLogger(__name__)\n\nPORT_AVAILABILITY_CHECK_TIMEOUT = 2\n\n\ndef check_other_kolibri_running(port):\n    \"\"\"\n    Make sure there are no other Kolibri instances running before starting the server.\n    \"\"\"\n    try:\n        # Check if there are other kolibri instances running\n        # If there are, then we need to stop users from starting kolibri again.\n        get_status()\n        logger.error(\n            \"There is another Kolibri server running. \"\n            \"Please use `kolibri stop` and try again.\"\n        )\n        sys.exit(1)\n\n    except NotRunning:\n        # In case that something other than Kolibri occupies the port,\n        # check the port's availability.\n        check_port_availability(LISTEN_ADDRESS, port)\n\n\ndef check_port_availability(host, port):\n    \"\"\"\n    Make sure the port is available for the server to start.\n    \"\"\"\n    try:\n        portend.free(host, port, timeout=PORT_AVAILABILITY_CHECK_TIMEOUT)\n    except portend.Timeout:\n        # Bypass check when socket activation is used\n        # https://manpages.debian.org/testing/libsystemd-dev/sd_listen_fds.3.en.html#ENVIRONMENT\n        if not os.environ.get(\"LISTEN_PID\", None):\n            # Port is occupied\n            logger.error(\n                \"Port {} is occupied.\\n\"\n                \"Please check that you do not have other processes \"\n                \"running on this port and try again.\\n\".format(port)\n            )\n            sys.exit(1)\n\n\ndef check_content_directory_exists_and_writable():\n    \"\"\"\n    Make sure the content directory of Kolibri exists and is writable.\n    \"\"\"\n    content_directory = OPTIONS[\"Paths\"][\"CONTENT_DIR\"]\n\n    # Check if the content directory exists\n    if not os.path.exists(content_directory):\n        try:\n            os.makedirs(content_directory)\n        except OSError:\n            logger.error(\n                \"The content directory {} does not exist and cannot be created.\".format(\n                    content_directory\n                )\n            )\n            sys.exit(1)\n\n    # Check if the directory is writable\n    if not os.access(content_directory, os.W_OK):\n        logger.error(\n            \"The content directory {} is not writable.\".format(content_directory)\n        )\n        sys.exit(1)\n\n\ndef check_log_file_location():\n    \"\"\"\n    Starting from Kolibri v0.12.4, log files are going to be renamed and moved\n    from KOLIBRI_HOME directory to KOLIBRI_HOME/logs directory.\n    \"\"\"\n    home = os.environ[\"KOLIBRI_HOME\"]\n    log_location_update = {}\n\n    # Old log file names\n    old_daemon_log = \"server.log\"\n    old_kolibri_log = \"kolibri.log\"\n    old_debug_log = \"debug.log\"\n\n    # New log file names\n    log_location_update[old_daemon_log] = \"daemon.txt\"\n    log_location_update[old_kolibri_log] = \"kolibri.txt\"\n    log_location_update[old_debug_log] = \"debug.txt\"\n\n    for log in log_location_update:\n        old_log_path = os.path.join(home, log)\n        if os.path.exists(old_log_path):\n            new_log_path = os.path.join(home, \"logs\", log_location_update[log])\n            shutil.move(old_log_path, new_log_path)\n\n\ndef migrate_databases():\n    \"\"\"\n    Try to migrate all active databases. This should not be called unless Django has\n    been initialized.\n    \"\"\"\n    from django.conf import settings\n\n    for database in settings.DATABASES:\n        call_command(\"migrate\", interactive=False, database=database)\n\n    # load morango fixtures needed for certificate related operations\n    call_command(\"loaddata\", \"scopedefinitions\")\n\n\ndef check_database_is_migrated():\n    \"\"\"\n    Use a check that the database instance id model is initialized to check if the database\n    is in a proper state to be used. This must only be run after django initialization.\n    \"\"\"\n    apps.check_apps_ready()\n    from morango.models import InstanceIDModel\n\n    try:\n        InstanceIDModel.get_or_create_current_instance()[0]\n        return\n    except OperationalError:\n        try:\n            migrate_databases()\n            return\n        except Exception as e:\n            logging.error(\n                \"Tried to migrate the database but another error occurred: {}\".format(e)\n            )\n    except Exception as e:\n        logging.error(\n            \"Tried to check that the database was accessible and an error occurred: {}\".format(\n                e\n            )\n        )\n    sys.exit(1)\n", "path": "kolibri/utils/sanity_checks.py"}], "after_files": [{"content": "import logging\nimport os\nimport shutil\nimport sys\n\nimport portend\nfrom django.apps import apps\nfrom django.core.management import call_command\nfrom django.db.utils import OperationalError\n\nfrom .conf import OPTIONS\nfrom .server import get_status\nfrom .server import LISTEN_ADDRESS\nfrom .server import NotRunning\n\nlogger = logging.getLogger(__name__)\n\nPORT_AVAILABILITY_CHECK_TIMEOUT = 2\n\n\ndef check_other_kolibri_running(port):\n    \"\"\"\n    Make sure there are no other Kolibri instances running before starting the server.\n    \"\"\"\n    try:\n        # Check if there are other kolibri instances running\n        # If there are, then we need to stop users from starting kolibri again.\n        get_status()\n        logger.error(\n            \"There is another Kolibri server running. \"\n            \"Please use `kolibri stop` and try again.\"\n        )\n        sys.exit(1)\n\n    except NotRunning:\n        # In case that something other than Kolibri occupies the port,\n        # check the port's availability.\n        check_port_availability(LISTEN_ADDRESS, port)\n\n\ndef check_port_availability(host, port):\n    \"\"\"\n    Make sure the port is available for the server to start.\n    \"\"\"\n    try:\n        portend.free(host, port, timeout=PORT_AVAILABILITY_CHECK_TIMEOUT)\n    except portend.Timeout:\n        # Bypass check when socket activation is used\n        # https://manpages.debian.org/testing/libsystemd-dev/sd_listen_fds.3.en.html#ENVIRONMENT\n        if not os.environ.get(\"LISTEN_PID\", None):\n            # Port is occupied\n            logger.error(\n                \"Port {} is occupied.\\n\"\n                \"Please check that you do not have other processes \"\n                \"running on this port and try again.\\n\".format(port)\n            )\n            sys.exit(1)\n\n\ndef check_content_directory_exists_and_writable():\n    \"\"\"\n    Make sure the content directory of Kolibri exists and is writable.\n    \"\"\"\n    content_directory = OPTIONS[\"Paths\"][\"CONTENT_DIR\"]\n\n    # Check if the content directory exists\n    if not os.path.exists(content_directory):\n        try:\n            os.makedirs(content_directory)\n        except OSError:\n            logger.error(\n                \"The content directory {} does not exist and cannot be created.\".format(\n                    content_directory\n                )\n            )\n            sys.exit(1)\n\n    # Check if the directory is writable\n    if not os.access(content_directory, os.W_OK):\n        logger.error(\n            \"The content directory {} is not writable.\".format(content_directory)\n        )\n        sys.exit(1)\n\n\ndef check_log_file_location():\n    \"\"\"\n    Starting from Kolibri v0.12.4, log files are going to be renamed and moved\n    from KOLIBRI_HOME directory to KOLIBRI_HOME/logs directory.\n    \"\"\"\n    home = os.environ[\"KOLIBRI_HOME\"]\n    log_location_update = {}\n\n    # Old log file names\n    old_daemon_log = \"server.log\"\n    old_kolibri_log = \"kolibri.log\"\n    old_debug_log = \"debug.log\"\n\n    # New log file names\n    log_location_update[old_daemon_log] = \"daemon.txt\"\n    log_location_update[old_kolibri_log] = \"kolibri.txt\"\n    log_location_update[old_debug_log] = \"debug.txt\"\n\n    for log in log_location_update:\n        old_log_path = os.path.join(home, log)\n        if os.path.exists(old_log_path):\n            new_log_path = os.path.join(home, \"logs\", log_location_update[log])\n            shutil.move(old_log_path, new_log_path)\n\n\ndef migrate_databases():\n    \"\"\"\n    Try to migrate all active databases. This should not be called unless Django has\n    been initialized.\n    \"\"\"\n    from django.conf import settings\n\n    for database in settings.DATABASES:\n        call_command(\"migrate\", interactive=False, database=database)\n\n    # load morango fixtures needed for certificate related operations\n    call_command(\"loaddata\", \"scopedefinitions\")\n\n\ndef check_database_is_migrated():\n    \"\"\"\n    Use a check that the database instance id model is initialized to check if the database\n    is in a proper state to be used. This must only be run after django initialization.\n    \"\"\"\n    apps.check_apps_ready()\n    from django.db import connection\n    from morango.models import InstanceIDModel\n\n    try:\n        InstanceIDModel.get_or_create_current_instance()[0]\n        connection.close()\n        return\n    except OperationalError:\n        try:\n            migrate_databases()\n            return\n        except Exception as e:\n            logging.error(\n                \"Tried to migrate the database but another error occurred: {}\".format(e)\n            )\n    except Exception as e:\n        logging.error(\n            \"Tried to check that the database was accessible and an error occurred: {}\".format(\n                e\n            )\n        )\n    sys.exit(1)\n", "path": "kolibri/utils/sanity_checks.py"}]}