<commit_before># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2020 ScyllaDB
import datetime
import pprint
import re
import typing
from functools import cached_property

import yaml
import requests

from sdcm.sct_events import Severity
from sdcm.sct_events.database import ScyllaHousekeepingServiceEvent
from sdcm.tester import ClusterTester
from sdcm.utils.housekeeping import HousekeepingDB
from sdcm.utils.common import get_latest_scylla_release, ScyllaProduct

STRESS_CMD: str = "/usr/bin/cassandra-stress"


BACKENDS = {
    "aws": ["Ec2Snitch", "Ec2MultiRegionSnitch"],
    "gce": ["GoogleCloudSnitch"],
    "azure": ["AzureSnitch"],
    "docker": ["GossipingPropertyFileSnitch", "SimpleSnitch"]
}


class ArtifactsTest(ClusterTester):
    REPO_TABLE = "housekeeping.repo"
    CHECK_VERSION_TABLE = "housekeeping.checkversion"

    def setUp(self) -> None:
        super().setUp()

        self.housekeeping = HousekeepingDB.from_keystore_creds()
        self.housekeeping.connect()

    def tearDown(self) -> None:
        if getattr(self, "housekeeping", None):
            self.housekeeping.close()

        super().tearDown()

    def check_scylla_version_in_housekeepingdb(self, prev_id: int, expected_status_code: str,
                                               new_row_expected: bool, backend: str) -> int:
        """
        Validate reported version
        prev_id: check if new version is created
        """
        assert self.node.uuid, "Node UUID wasn't created"

        row = self.housekeeping.get_most_recent_record(query=f"SELECT id, version, ip, statuscode "
                                                             f"FROM {self.CHECK_VERSION_TABLE} "
                                                             f"WHERE uuid = %s", args=(self.node.uuid,))
        self.log.debug("Last row in %s for uuid '%s': %s", self.CHECK_VERSION_TABLE, self.node.uuid, row)

        public_ip_address = self.node.host_public_ip_address if backend == 'docker' else self.node.public_ip_address
        self.log.debug("public_ip_address = %s", public_ip_address)

        # Validate public IP address
        assert public_ip_address == row[2], (
            f"Wrong IP address is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {self.node.public_ip_address}, got: {row[2]}")

        # Validate reported node version
        assert row[1] == self.node.scylla_version, (
            f"Wrong version is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {self.node.public_ip_address}, got: {row[2]}")

        # Validate expected status code
        assert row[3] == expected_status_code, (
            f"Wrong statuscode is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {expected_status_code}, got: {row[3]}")

        if prev_id:
            # Validate row id
            if new_row_expected:
                assert row[0] > prev_id, f"New row wasn't saved in {self.CHECK_VERSION_TABLE}"
            else:
                assert row[0] == prev_id, f"New row was saved in {self.CHECK_VERSION_TABLE} unexpectedly"

        return row[0] if row else 0

    @property
    def node(self):
        if self.db_cluster is None or not self.db_cluster.nodes:
            raise ValueError('DB cluster has not been initiated')
        return self.db_cluster.nodes[0]

    @cached_property
    def write_back_cache(self) -> int | None:
        res = self.node.remoter.run("cat /etc/scylla.d/perftune.yaml", ignore_status=True)
        if res.ok:
            return yaml.safe_load(res.stdout).get("write_back_cache")
        return None

    def check_cluster_name(self):
        with self.node.remote_scylla_yaml() as scylla_yaml:
            yaml_cluster_name = scylla_yaml.cluster_name

        self.assertTrue(self.db_cluster.name == yaml_cluster_name,
                        f"Cluster name is not as expected. Cluster name in scylla.yaml: {yaml_cluster_name}. "
                        f"Cluster name: {self.db_cluster.name}")

    def run_cassandra_stress(self, args: str):
        result = self.node.remoter.run(
            f"{self.node.add_install_prefix(STRESS_CMD)} {args} -node {self.node.ip_address}")
        assert "java.io.IOException" not in result.stdout
        assert "java.io.IOException" not in result.stderr

    def check_scylla(self):
        self.node.run_nodetool("status")
        self.run_cassandra_stress("write n=10000 -mode cql3 native -pop seq=1..10000")
        self.run_cassandra_stress("mixed duration=1m -mode cql3 native -rate threads=10 -pop seq=1..10000")

    def check_housekeeping_service_status(self, backend: str):
        housekeeping_service_name = "scylla-housekeeping" if backend == "docker" else "scylla-housekeeping-restart"
        status_out = self.node.get_service_status(housekeeping_service_name, ignore_status=True)
        # When the test runs with OEL81 operation system error "TMOUT: readonly variable" is printed from /etc/bashrc.
        # Ignore it
        if status_out.stderr and "TMOUT" not in status_out.stderr:
            ScyllaHousekeepingServiceEvent(message=f"scylla-housekeeping-restart service error: {status_out.stderr}",
                                           severity=Severity.ERROR).publish()
            return

        status = status_out.stdout.strip()
        # Expected output:
        #     "scylla-housekeeping-restart.service: Succeeded" - ubuntu, centos
        #     "RUNNING" - docker
        #     "Started Scylla Housekeeping restart mode" - other
        if "scylla-housekeeping-restart.service: Succeeded" in status or \
                "Started Scylla Housekeeping restart mode" in status or \
                "RUNNING" in status:
            ScyllaHousekeepingServiceEvent(message="scylla-housekeeping-restart service running",
                                           severity=Severity.NORMAL).publish()
        else:
            ScyllaHousekeepingServiceEvent(message=f"scylla-housekeeping-restart service is not running: {status}",
                                           severity=Severity.ERROR).publish()

    def verify_users(self):
        # We can't ship the image with Scylla internal users inside. So we
        # need to verify that mistakenly we didn't create all the users that we have project wide in the image
        self.log.info("Checking that all existent users except centos were created after boot")
        uptime = self.node.remoter.run(cmd="uptime -s").stdout.strip()
        datetime_format = "%Y-%m-%d %H:%M:%S"
        instance_start_time = datetime.datetime.strptime(uptime, datetime_format)
        self.log.info("Instance started at: %s", instance_start_time)
        out = self.node.remoter.run(cmd="ls -ltr --full-time /home", verbose=True).stdout.strip()
        for line in out.splitlines():
            splitted_line = line.split()
            if len(splitted_line) <= 2:
                continue
            user = splitted_line[-1]
            if user == "centos":
                self.log.info("Skipping user %s since it is a default image user.", user)
                continue
            self.log.info("Checking user: '%s'", user)
            if datetime_str := re.search(r"(\d+-\d+-\d+ \d+:\d+:\d+).", line):
                datetime_user_created = datetime.datetime.strptime(datetime_str.group(1), datetime_format)
                self.log.info("User '%s' created at '%s'", user, datetime_user_created)
                if datetime_user_created < instance_start_time and not user == "centos":
                    AssertionError("User %s was created in the image. Only user centos should exist in the image")
            else:
                raise AssertionError(f"Unable to parse/find timestamp of the user {user} creation in {line}")
        self.log.info("All users except image user 'centos' were created after the boot.")

    def verify_node_health(self):
        self.node.check_node_health()

    def verify_snitch(self, backend_name: str):
        """
        Verify that the snitch used in the cluster is appropriate for
        the backend used.
        """
        if not self.params["use_preinstalled_scylla"]:
            self.log.info("Skipping verifying the snitch due to the 'use_preinstalled_scylla' being set to False")
            return

        describecluster_snitch = self.get_describecluster_info().snitch
        with self.node.remote_scylla_yaml() as scylla_yaml:
            scylla_yaml_snitch = scylla_yaml.endpoint_snitch
        expected_snitches = BACKENDS[backend_name]

        snitch_patterns = [re.compile(f"({snitch})") for snitch in expected_snitches]
        snitch_matches_describecluster = [pattern.search(describecluster_snitch) for pattern in snitch_patterns]
        snitch_matches_scylla_yaml = [pattern.search(scylla_yaml_snitch) for pattern in snitch_patterns]

        with self.subTest('verify snitch against describecluster output'):
            self.assertTrue(any(snitch_matches_describecluster),
                            msg=f"Expected snitch matches for describecluster to not be empty, but was. Snitch "
                                f"matches: {snitch_matches_describecluster}"
                            )

        with self.subTest('verify snitch against scylla.yaml configuration'):
            self.assertTrue(any(snitch_matches_scylla_yaml),
                            msg=f"Expected snitch matches for scylla yaml to not be empty, but was. Snitch "
                                f"matches: {snitch_matches_scylla_yaml}"
                            )

    def verify_write_back_cache_param(self) -> None:
        if self.params["cluster_backend"] in ("gce", "azure") and self.params["use_preinstalled_scylla"]:
            expected_write_back_cache_param = 0
        else:
            expected_write_back_cache_param = None
        self.assertEqual(self.write_back_cache, expected_write_back_cache_param)

    def verify_docker_locale_settings(self) -> None:
        run = self.node.remoter.run
        expected_locale_settings = {
            "LC_ALL": "en_US.UTF-8",
            "LANG": "en_US.UTF-8",
            "LANGUAGE": "en_US:en",
        }

        locale_settings_raw = run("locale").stdout.split(sep="\n")
        locale_settings = [setting.split(sep="=") for setting in locale_settings_raw if setting]
        locale_settings = {setting[0]: setting[1].strip("\"") for setting in locale_settings if len(setting) == 2}

        for setting_key, expected_value in expected_locale_settings.items():
            configured_value = locale_settings.get(setting_key)
            self.assertEqual(configured_value, expected_value)

    def verify_docker_latest_match_release(self) -> None:
        for product in typing.get_args(ScyllaProduct):
            latest_version = get_latest_scylla_release(product=product)

            url = 'https://hub.docker.com/v2/repositories/scylladb/{}/tags/{}'
            docker_latest = requests.get(url.format(product, 'latest')).json()
            docker_release = requests.get(url.format(product, latest_version)).json()
            self.log.debug('latest info: %s', pprint.pformat(docker_latest))
            self.log.debug('%s info: %s ', latest_version, pprint.pformat(docker_release))

            latest_digests = set(image['digest'] for image in docker_latest['images'])
            release_digests = set(image['digest'] for image in docker_release['images'])

            assert latest_digests == release_digests, \
                f"latest != {latest_version}, images digest differs [{latest_digests}] != [{release_digests}]"

    def verify_nvme_write_cache(self) -> None:
        if self.write_back_cache is None or self.node.parent_cluster.is_additional_data_volume_used():
            return
        expected_write_cache_value = "write back" if self.write_back_cache else "write through"

        run = self.node.remoter.sudo
        nvme_devices = re.findall(r"nvme[\d]+n[\d\w]+", run("ls -1 /dev/nvme*").stdout)
        self.assertGreater(len(nvme_devices), 0)

        for nvme_device in nvme_devices:
            self.log.info("Expected write cache for %s is %r", nvme_device, expected_write_cache_value)
            write_cache = run(f"cat /sys/block/{nvme_device}/queue/write_cache").stdout.strip()
            self.assertEqual(write_cache, expected_write_cache_value)

    def verify_xfs_online_discard_enabled(self) -> None:
        run = self.node.remoter.sudo

        self.log.info("Verify XFS mount options for /var/lib/scylla contain `discard'")
        mount_options = run("findmnt -no options -t xfs -T /var/lib/scylla").stdout.strip().split(",")
        self.assertIn("discard", mount_options)

        # we only test this in images created by scylla-machine-image
        if self.params.get("use_preinstalled_scylla"):
            self.log.info("Ensure that we don't run fstrim")
            self.assertEqual(run("systemctl is-enabled fstrim.timer", ignore_status=True).stdout.strip(), "disabled")

    def check_service_existence(self, service_name):
        res = self.node.remoter.run(f'systemctl list-units --full | grep -Fq "{service_name}"',
                                    ignore_status=True)
        if res.exit_status:
            return False
        return True  # exit_status = 1 means the service doesn't exist

    # pylint: disable=too-many-statements,too-many-branches
    def test_scylla_service(self):
        backend = self.params["cluster_backend"]

        if backend == "aws":
            with self.subTest("check ENA support"):
                assert self.node.ena_support, "ENA support is not enabled"

        with self.subTest("verify write_back_cache perftune parameter"):
            self.verify_write_back_cache_param()

        with self.subTest("verify write cache for NVMe devices"):
            self.verify_nvme_write_cache()

        if backend != "docker" and not self.params.get("nonroot_offline_install"):
            with self.subTest("verify XFS online discard enabled"):
                self.verify_xfs_online_discard_enabled()

        if backend == "gce":
            with self.subTest("verify users"):
                self.verify_users()

        expected_housekeeping_status_code = 'cr' if backend == "docker" else 'r'

        if self.params["use_preinstalled_scylla"] and backend != "docker":
            with self.subTest("check the cluster name"):
                self.check_cluster_name()

        with self.subTest('verify snitch'):
            self.verify_snitch(backend_name=backend)

        with self.subTest('verify node health'):
            self.verify_node_health()

        with self.subTest("check Scylla server after installation"):
            self.check_scylla()

        if backend == "docker":
            with self.subTest("check locale settings in the docker image"):
                self.verify_docker_locale_settings()

        # We don't install any time sync service in docker, so the test is unnecessary:
        # https://github.com/scylladb/scylla/tree/master/dist/docker/etc/supervisord.conf.d
        if backend != "docker":
            with self.subTest("check if scylla unnecessarily installed a time synchronization service"):
                # Checks https://github.com/scylladb/scylla/issues/8339
                # If the instance already has systemd-timesyncd
                is_timesyncd_service_installed = self.check_service_existence(service_name="systemd-timesyncd")
                # Do note: On Redhat based distributions the services are named ntpd and chronyd, while on debian based
                # distributions they're named ntp and chrony.
                if self.node.is_rhel_like():
                    is_ntp_service_installed = self.check_service_existence(service_name="ntpd")
                    is_chrony_service_installed = self.check_service_existence(service_name="chronyd")
                else:
                    is_ntp_service_installed = self.check_service_existence(service_name="ntp")
                    is_chrony_service_installed = self.check_service_existence(service_name="chrony")
                try:
                    if is_timesyncd_service_installed:
                        assert not is_ntp_service_installed, \
                            "systemd-timesyncd is already installed, yet scylla installed ntp service on top of it"
                        assert not is_chrony_service_installed, \
                            "systemd-timesyncd is already installed, yet scylla installed chrony service on top of it"
                    else:
                        assert is_ntp_service_installed or is_chrony_service_installed, \
                            "systemd-timesyncd is not installed on the instance, yet Scylla did not install ntp or " \
                            "chrony services as a replacement"
                except AssertionError:
                    full_list = self.node.remoter.run('systemctl list-units --full').stdout.strip()<commit_msg>fix(artifact_test): Skip timesync test on offline installation scenarios<commit_after># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2020 ScyllaDB
import datetime
import pprint
import re
import typing
from functools import cached_property

import yaml
import requests

from sdcm.sct_events import Severity
from sdcm.sct_events.database import ScyllaHousekeepingServiceEvent
from sdcm.tester import ClusterTester
from sdcm.utils.housekeeping import HousekeepingDB
from sdcm.utils.common import get_latest_scylla_release, ScyllaProduct

STRESS_CMD: str = "/usr/bin/cassandra-stress"


BACKENDS = {
    "aws": ["Ec2Snitch", "Ec2MultiRegionSnitch"],
    "gce": ["GoogleCloudSnitch"],
    "azure": ["AzureSnitch"],
    "docker": ["GossipingPropertyFileSnitch", "SimpleSnitch"]
}


class ArtifactsTest(ClusterTester):
    REPO_TABLE = "housekeeping.repo"
    CHECK_VERSION_TABLE = "housekeeping.checkversion"

    def setUp(self) -> None:
        super().setUp()

        self.housekeeping = HousekeepingDB.from_keystore_creds()
        self.housekeeping.connect()

    def tearDown(self) -> None:
        if getattr(self, "housekeeping", None):
            self.housekeeping.close()

        super().tearDown()

    def check_scylla_version_in_housekeepingdb(self, prev_id: int, expected_status_code: str,
                                               new_row_expected: bool, backend: str) -> int:
        """
        Validate reported version
        prev_id: check if new version is created
        """
        assert self.node.uuid, "Node UUID wasn't created"

        row = self.housekeeping.get_most_recent_record(query=f"SELECT id, version, ip, statuscode "
                                                             f"FROM {self.CHECK_VERSION_TABLE} "
                                                             f"WHERE uuid = %s", args=(self.node.uuid,))
        self.log.debug("Last row in %s for uuid '%s': %s", self.CHECK_VERSION_TABLE, self.node.uuid, row)

        public_ip_address = self.node.host_public_ip_address if backend == 'docker' else self.node.public_ip_address
        self.log.debug("public_ip_address = %s", public_ip_address)

        # Validate public IP address
        assert public_ip_address == row[2], (
            f"Wrong IP address is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {self.node.public_ip_address}, got: {row[2]}")

        # Validate reported node version
        assert row[1] == self.node.scylla_version, (
            f"Wrong version is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {self.node.public_ip_address}, got: {row[2]}")

        # Validate expected status code
        assert row[3] == expected_status_code, (
            f"Wrong statuscode is saved in '{self.CHECK_VERSION_TABLE}' table: "
            f"expected {expected_status_code}, got: {row[3]}")

        if prev_id:
            # Validate row id
            if new_row_expected:
                assert row[0] > prev_id, f"New row wasn't saved in {self.CHECK_VERSION_TABLE}"
            else:
                assert row[0] == prev_id, f"New row was saved in {self.CHECK_VERSION_TABLE} unexpectedly"

        return row[0] if row else 0

    @property
    def node(self):
        if self.db_cluster is None or not self.db_cluster.nodes:
            raise ValueError('DB cluster has not been initiated')
        return self.db_cluster.nodes[0]

    @cached_property
    def write_back_cache(self) -> int | None:
        res = self.node.remoter.run("cat /etc/scylla.d/perftune.yaml", ignore_status=True)
        if res.ok:
            return yaml.safe_load(res.stdout).get("write_back_cache")
        return None

    def check_cluster_name(self):
        with self.node.remote_scylla_yaml() as scylla_yaml:
            yaml_cluster_name = scylla_yaml.cluster_name

        self.assertTrue(self.db_cluster.name == yaml_cluster_name,
                        f"Cluster name is not as expected. Cluster name in scylla.yaml: {yaml_cluster_name}. "
                        f"Cluster name: {self.db_cluster.name}")

    def run_cassandra_stress(self, args: str):
        result = self.node.remoter.run(
            f"{self.node.add_install_prefix(STRESS_CMD)} {args} -node {self.node.ip_address}")
        assert "java.io.IOException" not in result.stdout
        assert "java.io.IOException" not in result.stderr

    def check_scylla(self):
        self.node.run_nodetool("status")
        self.run_cassandra_stress("write n=10000 -mode cql3 native -pop seq=1..10000")
        self.run_cassandra_stress("mixed duration=1m -mode cql3 native -rate threads=10 -pop seq=1..10000")

    def check_housekeeping_service_status(self, backend: str):
        housekeeping_service_name = "scylla-housekeeping" if backend == "docker" else "scylla-housekeeping-restart"
        status_out = self.node.get_service_status(housekeeping_service_name, ignore_status=True)
        # When the test runs with OEL81 operation system error "TMOUT: readonly variable" is printed from /etc/bashrc.
        # Ignore it
        if status_out.stderr and "TMOUT" not in status_out.stderr:
            ScyllaHousekeepingServiceEvent(message=f"scylla-housekeeping-restart service error: {status_out.stderr}",
                                           severity=Severity.ERROR).publish()
            return

        status = status_out.stdout.strip()
        # Expected output:
        #     "scylla-housekeeping-restart.service: Succeeded" - ubuntu, centos
        #     "RUNNING" - docker
        #     "Started Scylla Housekeeping restart mode" - other
        if "scylla-housekeeping-restart.service: Succeeded" in status or \
                "Started Scylla Housekeeping restart mode" in status or \
                "RUNNING" in status:
            ScyllaHousekeepingServiceEvent(message="scylla-housekeeping-restart service running",
                                           severity=Severity.NORMAL).publish()
        else:
            ScyllaHousekeepingServiceEvent(message=f"scylla-housekeeping-restart service is not running: {status}",
                                           severity=Severity.ERROR).publish()

    def verify_users(self):
        # We can't ship the image with Scylla internal users inside. So we
        # need to verify that mistakenly we didn't create all the users that we have project wide in the image
        self.log.info("Checking that all existent users except centos were created after boot")
        uptime = self.node.remoter.run(cmd="uptime -s").stdout.strip()
        datetime_format = "%Y-%m-%d %H:%M:%S"
        instance_start_time = datetime.datetime.strptime(uptime, datetime_format)
        self.log.info("Instance started at: %s", instance_start_time)
        out = self.node.remoter.run(cmd="ls -ltr --full-time /home", verbose=True).stdout.strip()
        for line in out.splitlines():
            splitted_line = line.split()
            if len(splitted_line) <= 2:
                continue
            user = splitted_line[-1]
            if user == "centos":
                self.log.info("Skipping user %s since it is a default image user.", user)
                continue
            self.log.info("Checking user: '%s'", user)
            if datetime_str := re.search(r"(\d+-\d+-\d+ \d+:\d+:\d+).", line):
                datetime_user_created = datetime.datetime.strptime(datetime_str.group(1), datetime_format)
                self.log.info("User '%s' created at '%s'", user, datetime_user_created)
                if datetime_user_created < instance_start_time and not user == "centos":
                    AssertionError("User %s was created in the image. Only user centos should exist in the image")
            else:
                raise AssertionError(f"Unable to parse/find timestamp of the user {user} creation in {line}")
        self.log.info("All users except image user 'centos' were created after the boot.")

    def verify_node_health(self):
        self.node.check_node_health()

    def verify_snitch(self, backend_name: str):
        """
        Verify that the snitch used in the cluster is appropriate for
        the backend used.
        """
        if not self.params["use_preinstalled_scylla"]:
            self.log.info("Skipping verifying the snitch due to the 'use_preinstalled_scylla' being set to False")
            return

        describecluster_snitch = self.get_describecluster_info().snitch
        with self.node.remote_scylla_yaml() as scylla_yaml:
            scylla_yaml_snitch = scylla_yaml.endpoint_snitch
        expected_snitches = BACKENDS[backend_name]

        snitch_patterns = [re.compile(f"({snitch})") for snitch in expected_snitches]
        snitch_matches_describecluster = [pattern.search(describecluster_snitch) for pattern in snitch_patterns]
        snitch_matches_scylla_yaml = [pattern.search(scylla_yaml_snitch) for pattern in snitch_patterns]

        with self.subTest('verify snitch against describecluster output'):
            self.assertTrue(any(snitch_matches_describecluster),
                            msg=f"Expected snitch matches for describecluster to not be empty, but was. Snitch "
                                f"matches: {snitch_matches_describecluster}"
                            )

        with self.subTest('verify snitch against scylla.yaml configuration'):
            self.assertTrue(any(snitch_matches_scylla_yaml),
                            msg=f"Expected snitch matches for scylla yaml to not be empty, but was. Snitch "
                                f"matches: {snitch_matches_scylla_yaml}"
                            )

    def verify_write_back_cache_param(self) -> None:
        if self.params["cluster_backend"] in ("gce", "azure") and self.params["use_preinstalled_scylla"]:
            expected_write_back_cache_param = 0
        else:
            expected_write_back_cache_param = None
        self.assertEqual(self.write_back_cache, expected_write_back_cache_param)

    def verify_docker_locale_settings(self) -> None:
        run = self.node.remoter.run
        expected_locale_settings = {
            "LC_ALL": "en_US.UTF-8",
            "LANG": "en_US.UTF-8",
            "LANGUAGE": "en_US:en",
        }

        locale_settings_raw = run("locale").stdout.split(sep="\n")
        locale_settings = [setting.split(sep="=") for setting in locale_settings_raw if setting]
        locale_settings = {setting[0]: setting[1].strip("\"") for setting in locale_settings if len(setting) == 2}

        for setting_key, expected_value in expected_locale_settings.items():
            configured_value = locale_settings.get(setting_key)
            self.assertEqual(configured_value, expected_value)

    def verify_docker_latest_match_release(self) -> None:
        for product in typing.get_args(ScyllaProduct):
            latest_version = get_latest_scylla_release(product=product)

            url = 'https://hub.docker.com/v2/repositories/scylladb/{}/tags/{}'
            docker_latest = requests.get(url.format(product, 'latest')).json()
            docker_release = requests.get(url.format(product, latest_version)).json()
            self.log.debug('latest info: %s', pprint.pformat(docker_latest))
            self.log.debug('%s info: %s ', latest_version, pprint.pformat(docker_release))

            latest_digests = set(image['digest'] for image in docker_latest['images'])
            release_digests = set(image['digest'] for image in docker_release['images'])

            assert latest_digests == release_digests, \
                f"latest != {latest_version}, images digest differs [{latest_digests}] != [{release_digests}]"

    def verify_nvme_write_cache(self) -> None:
        if self.write_back_cache is None or self.node.parent_cluster.is_additional_data_volume_used():
            return
        expected_write_cache_value = "write back" if self.write_back_cache else "write through"

        run = self.node.remoter.sudo
        nvme_devices = re.findall(r"nvme[\d]+n[\d\w]+", run("ls -1 /dev/nvme*").stdout)
        self.assertGreater(len(nvme_devices), 0)

        for nvme_device in nvme_devices:
            self.log.info("Expected write cache for %s is %r", nvme_device, expected_write_cache_value)
            write_cache = run(f"cat /sys/block/{nvme_device}/queue/write_cache").stdout.strip()
            self.assertEqual(write_cache, expected_write_cache_value)

    def verify_xfs_online_discard_enabled(self) -> None:
        run = self.node.remoter.sudo

        self.log.info("Verify XFS mount options for /var/lib/scylla contain `discard'")
        mount_options = run("findmnt -no options -t xfs -T /var/lib/scylla").stdout.strip().split(",")
        self.assertIn("discard", mount_options)

        # we only test this in images created by scylla-machine-image
        if self.params.get("use_preinstalled_scylla"):
            self.log.info("Ensure that we don't run fstrim")
            self.assertEqual(run("systemctl is-enabled fstrim.timer", ignore_status=True).stdout.strip(), "disabled")

    def check_service_existence(self, service_name):
        res = self.node.remoter.run(f'systemctl list-units --full | grep -Fq "{service_name}"',
                                    ignore_status=True)
        if res.exit_status:
            return False
        return True  # exit_status = 1 means the service doesn't exist

    # pylint: disable=too-many-statements,too-many-branches
    def test_scylla_service(self):
        backend = self.params["cluster_backend"]

        if backend == "aws":
            with self.subTest("check ENA support"):
                assert self.node.ena_support, "ENA support is not enabled"

        with self.subTest("verify write_back_cache perftune parameter"):
            self.verify_write_back_cache_param()

        with self.subTest("verify write cache for NVMe devices"):
            self.verify_nvme_write_cache()

        if backend != "docker" and not self.params.get("nonroot_offline_install"):
            with self.subTest("verify XFS online discard enabled"):
                self.verify_xfs_online_discard_enabled()

        if backend == "gce":
            with self.subTest("verify users"):
                self.verify_users()

        expected_housekeeping_status_code = 'cr' if backend == "docker" else 'r'

        if self.params["use_preinstalled_scylla"] and backend != "docker":
            with self.subTest("check the cluster name"):
                self.check_cluster_name()

        with self.subTest('verify snitch'):
            self.verify_snitch(backend_name=backend)

        with self.subTest('verify node health'):
            self.verify_node_health()

        with self.subTest("check Scylla server after installation"):
            self.check_scylla()

        if backend == "docker":
            with self.subTest("check locale settings in the docker image"):
                self.verify_docker_locale_settings()

        # We don't install any time sync service in docker, so the test is unnecessary:
        # https://github.com/scylladb/scylla/tree/master/dist/docker/etc/supervisord.conf.d
        if backend != "docker":
            with self.subTest("check if scylla unnecessarily installed a time synchronization service"):
                # Checks https://github.com/scylladb/scylla/issues/8339
                # If the instance already has systemd-timesyncd
                is_timesyncd_service_installed = self.check_service_existence(service_name="systemd-timesyncd")
                # Do note: On Redhat based distributions the services are named ntpd and chronyd, while on debian based
                # distributions they're named ntp and chrony.
                if self.node.is_rhel_like():
                    is_ntp_service_installed = self.check_service_existence(service_name="ntpd")
                    is_chrony_service_installed = self.check_service_existence(service_name="chronyd")
                else:
                    is_ntp_service_installed = self.check_service_existence(service_name="ntp")
                    is_chrony_service_installed = self.check_service_existence(service_name="chrony")
                try:
                    if is_timesyncd_service_installed:
                        assert not is_ntp_service_installed, \
                            "systemd-timesyncd is already installed, yet scylla installed ntp service on top of it"
                        assert not is_chrony_service_installed, \
                            "systemd-timesyncd is already installed, yet scylla installed chrony service on top of it"
                    elif not self.params.get("unified_package"):
                        assert is_ntp_service_installed or is_chrony_service_installed, \
                            "systemd-timesyncd is not installed on the instance, yet Scylla did not install ntp or " \
                            "chrony services as a replacement"
                    else:
                        # https://github.com/scylladb/scylla/issues/10608#issuecomment-1135770570
                        # Scylla doesn't install any time sync service when it's an offline installation,
                        # so if there's no time sync services active after the scylla installation, it's fine.
                        # However, in such scenario a warning message should be printed during the scylla installation
                        self.log.warning("No time sync service was installed. "
                                         "Passable since it's an offline installation.")
                except AssertionError:
                    full_list = self.node.remoter.run('systemctl list-units --full').stdout.strip()
{'fraction_non_alphanumeric': 0.09390741522442662, 'fraction_numerical': 0.00374278879977487, 'mean_word_length': 2.4972935734671786, 'pattern_counts': {'":': 28, '<': 7, '<?xml version=': 0, '>': 23, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 28, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4355465', 'n_tokens_mistral': 10249, 'n_tokens_neox': 9835, 'n_words': 2482}