<commit_before># Copyright (c) 2013 Mirantis Inc.
# Copyright (c) 2015-2017 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
import time

import cotyledon
from cotyledon import oslo_config_glue
import daiquiri
from oslo_config import cfg
import six
import tenacity
import tooz

from gnocchi import exceptions
from gnocchi import incoming
from gnocchi import indexer
from gnocchi import service
from gnocchi import storage
from gnocchi import utils


LOG = daiquiri.getLogger(__name__)


# Retry with exponential backoff for up to 1 minute
_wait_exponential = tenacity.wait_exponential(multiplier=0.5, max=60)


retry_on_exception = tenacity.Retrying(wait=_wait_exponential)


class MetricProcessBase(cotyledon.Service):
    def __init__(self, worker_id, conf, interval_delay=0):
        super(MetricProcessBase, self).__init__(worker_id)
        self.conf = conf
        self.startup_delay = worker_id
        self.interval_delay = interval_delay
        self._wake_up = threading.Event()
        self._shutdown = threading.Event()
        self._shutdown_done = threading.Event()

    def wakeup(self):
        self._wake_up.set()

    def _configure(self):
        self.store = retry_on_exception(storage.get_driver, self.conf)
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)
        self.index = retry_on_exception(indexer.get_driver, self.conf)

    def run(self):
        self._configure()
        # Delay startup so workers are jittered.
        time.sleep(self.startup_delay)

        while not self._shutdown.is_set():
            with utils.StopWatch() as timer:
                self._run_job()
            self._wake_up.wait(max(0, self.interval_delay - timer.elapsed()))
            self._wake_up.clear()
        self._shutdown_done.set()

    def terminate(self):
        self._shutdown.set()
        self.wakeup()
        LOG.info("Waiting ongoing metric processing to finish")
        self._shutdown_done.wait()
        self.close_services()

    @staticmethod
    def close_services():
        pass

    @staticmethod
    def _run_job():
        raise NotImplementedError


class MetricReporting(MetricProcessBase):
    name = "reporting"

    def __init__(self, worker_id, conf):
        super(MetricReporting, self).__init__(
            worker_id, conf, conf.metricd.metric_reporting_delay)

    def _configure(self):
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)

    def _run_job(self):
        try:
            report = self.incoming.measures_report(details=False)
            LOG.info("%d measurements bundles across %d "
                     "metrics wait to be processed.",
                     report['summary']['measures'],
                     report['summary']['metrics'])
        except incoming.ReportGenerationError:
            LOG.warning("Unable to compute backlog. Retrying at next "
                        "interval.")
        except Exception:
            LOG.error("Unexpected error during pending measures reporting",
                      exc_info=True)


class MetricProcessor(MetricProcessBase):
    name = "processing"
    GROUP_ID = "gnocchi-processing"

    def __init__(self, worker_id, conf):
        super(MetricProcessor, self).__init__(
            worker_id, conf, conf.metricd.metric_processing_delay)
        self._tasks = []
        self.group_state = None
        self.sacks_with_measures_to_process = set()
        # This stores the last time the processor did a scan on all the sack it
        # is responsible for
        self._last_full_sack_scan = utils.StopWatch().start()

    @tenacity.retry(
        wait=_wait_exponential,
        # Never retry except when explicitly asked by raising TryAgain
        retry=tenacity.retry_never)
    def _configure(self):
        self.coord = retry_on_exception(utils.get_coordinator_and_start,
                                        self.conf.storage.coordination_url)
        self.store = retry_on_exception(storage.get_driver,
                                        self.conf, self.coord)
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)
        self.index = retry_on_exception(indexer.get_driver, self.conf)

        # create fallback in case paritioning fails or assigned no tasks
        self.fallback_tasks = list(
            six.moves.range(self.incoming.NUM_SACKS))
        try:
            self.partitioner = self.coord.join_partitioned_group(
                self.GROUP_ID, partitions=200)
            LOG.info('Joined coordination group: %s', self.GROUP_ID)
        except tooz.NotImplemented:
            LOG.warning('Coordinator does not support partitioning. Worker '
                        'will battle against other workers for jobs.')
        except tooz.ToozError as e:
            LOG.error('Unexpected error configuring coordinator for '
                      'partitioning. Retrying: %s', e)
            raise tenacity.TryAgain(e)

        filler = threading.Thread(target=self._fill_sacks_to_process)
        filler.daemon = True
        filler.start()

    @retry_on_exception.wraps
    def _fill_sacks_to_process(self):
        try:
            for sack in self.incoming.iter_on_sacks_to_process():
                if sack in self._get_sacks_to_process():
                    LOG.debug(
                        "Got notification for sack %s, waking up processing",
                        sack)
                    self.sacks_with_measures_to_process.add(sack)
                    self.wakeup()
        except exceptions.NotImplementedError:
            LOG.info("Incoming driver does not support notification")
        except Exception as e:
            LOG.error(
                "Error while listening for new measures notification, "
                "retrying",
                exc_info=True)
            raise tenacity.TryAgain(e)

    def _get_sacks_to_process(self):
        try:
            self.coord.run_watchers()
            if (not self._tasks or
                    self.group_state != self.partitioner.ring.nodes):
                self.group_state = self.partitioner.ring.nodes.copy()
                self._tasks = [
                    i for i in six.moves.range(self.incoming.NUM_SACKS)
                    if self.partitioner.belongs_to_self(
                        i, replicas=self.conf.metricd.processing_replicas)]
        except Exception as e:
            LOG.error('Unexpected error updating the task partitioner: %s', e)
        finally:
            return self._tasks or self.fallback_tasks

    def _run_job(self):
        m_count = 0
        s_count = 0
        # We are going to process the sacks we got notified for, and if we got
        # no notification, then we'll just try to process them all, just to be
        # sure we don't miss anything. In case we did not do a full scan for
        # more than `metric_processing_delay`, we do that instead.
        if self._last_full_sack_scan.elapsed() >= self.interval_delay:
            sacks = self._get_sacks_to_process()
        else:
            sacks = (self.sacks_with_measures_to_process.copy()
                     or self._get_sacks_to_process())
        for s in sacks:
            # TODO(gordc): support delay release lock so we don't
            # process a sack right after another process
            lock = self.incoming.get_sack_lock(self.coord, s)
            if not lock.acquire(blocking=False):<commit_msg>metricd: fix coordinator not implemented error<commit_after># Copyright (c) 2013 Mirantis Inc.
# Copyright (c) 2015-2017 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
import time

import cotyledon
from cotyledon import oslo_config_glue
import daiquiri
from oslo_config import cfg
import six
import tenacity
import tooz

from gnocchi import exceptions
from gnocchi import incoming
from gnocchi import indexer
from gnocchi import service
from gnocchi import storage
from gnocchi import utils


LOG = daiquiri.getLogger(__name__)


# Retry with exponential backoff for up to 1 minute
_wait_exponential = tenacity.wait_exponential(multiplier=0.5, max=60)


retry_on_exception = tenacity.Retrying(wait=_wait_exponential)


class MetricProcessBase(cotyledon.Service):
    def __init__(self, worker_id, conf, interval_delay=0):
        super(MetricProcessBase, self).__init__(worker_id)
        self.conf = conf
        self.startup_delay = worker_id
        self.interval_delay = interval_delay
        self._wake_up = threading.Event()
        self._shutdown = threading.Event()
        self._shutdown_done = threading.Event()

    def wakeup(self):
        self._wake_up.set()

    def _configure(self):
        self.store = retry_on_exception(storage.get_driver, self.conf)
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)
        self.index = retry_on_exception(indexer.get_driver, self.conf)

    def run(self):
        self._configure()
        # Delay startup so workers are jittered.
        time.sleep(self.startup_delay)

        while not self._shutdown.is_set():
            with utils.StopWatch() as timer:
                self._run_job()
            self._wake_up.wait(max(0, self.interval_delay - timer.elapsed()))
            self._wake_up.clear()
        self._shutdown_done.set()

    def terminate(self):
        self._shutdown.set()
        self.wakeup()
        LOG.info("Waiting ongoing metric processing to finish")
        self._shutdown_done.wait()
        self.close_services()

    @staticmethod
    def close_services():
        pass

    @staticmethod
    def _run_job():
        raise NotImplementedError


class MetricReporting(MetricProcessBase):
    name = "reporting"

    def __init__(self, worker_id, conf):
        super(MetricReporting, self).__init__(
            worker_id, conf, conf.metricd.metric_reporting_delay)

    def _configure(self):
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)

    def _run_job(self):
        try:
            report = self.incoming.measures_report(details=False)
            LOG.info("%d measurements bundles across %d "
                     "metrics wait to be processed.",
                     report['summary']['measures'],
                     report['summary']['metrics'])
        except incoming.ReportGenerationError:
            LOG.warning("Unable to compute backlog. Retrying at next "
                        "interval.")
        except Exception:
            LOG.error("Unexpected error during pending measures reporting",
                      exc_info=True)


class MetricProcessor(MetricProcessBase):
    name = "processing"
    GROUP_ID = "gnocchi-processing"

    def __init__(self, worker_id, conf):
        super(MetricProcessor, self).__init__(
            worker_id, conf, conf.metricd.metric_processing_delay)
        self._tasks = []
        self.group_state = None
        self.sacks_with_measures_to_process = set()
        # This stores the last time the processor did a scan on all the sack it
        # is responsible for
        self._last_full_sack_scan = utils.StopWatch().start()

    @tenacity.retry(
        wait=_wait_exponential,
        # Never retry except when explicitly asked by raising TryAgain
        retry=tenacity.retry_never)
    def _configure(self):
        self.coord = retry_on_exception(utils.get_coordinator_and_start,
                                        self.conf.storage.coordination_url)
        self.store = retry_on_exception(storage.get_driver,
                                        self.conf, self.coord)
        self.incoming = retry_on_exception(incoming.get_driver, self.conf)
        self.index = retry_on_exception(indexer.get_driver, self.conf)

        # create fallback in case paritioning fails or assigned no tasks
        self.fallback_tasks = list(
            six.moves.range(self.incoming.NUM_SACKS))
        try:
            self.partitioner = self.coord.join_partitioned_group(
                self.GROUP_ID, partitions=200)
            LOG.info('Joined coordination group: %s', self.GROUP_ID)
        except tooz.NotImplemented:
            LOG.warning('Coordinator does not support partitioning. Worker '
                        'will battle against other workers for jobs.')
        except tooz.ToozError as e:
            LOG.error('Unexpected error configuring coordinator for '
                      'partitioning. Retrying: %s', e)
            raise tenacity.TryAgain(e)

        filler = threading.Thread(target=self._fill_sacks_to_process)
        filler.daemon = True
        filler.start()

    @retry_on_exception.wraps
    def _fill_sacks_to_process(self):
        try:
            for sack in self.incoming.iter_on_sacks_to_process():
                if sack in self._get_sacks_to_process():
                    LOG.debug(
                        "Got notification for sack %s, waking up processing",
                        sack)
                    self.sacks_with_measures_to_process.add(sack)
                    self.wakeup()
        except exceptions.NotImplementedError:
            LOG.info("Incoming driver does not support notification")
        except Exception as e:
            LOG.error(
                "Error while listening for new measures notification, "
                "retrying",
                exc_info=True)
            raise tenacity.TryAgain(e)

    def _get_sacks_to_process(self):
        try:
            self.coord.run_watchers()
            if (not self._tasks or
                    self.group_state != self.partitioner.ring.nodes):
                self.group_state = self.partitioner.ring.nodes.copy()
                self._tasks = [
                    i for i in six.moves.range(self.incoming.NUM_SACKS)
                    if self.partitioner.belongs_to_self(
                        i, replicas=self.conf.metricd.processing_replicas)]
        except tooz.NotImplemented:
            # Do not log anything. If `run_watchers` is not implemented, it's
            # likely that partitioning is not implemented either, so it already
            # has been logged at startup with a warning.
            pass
        except Exception as e:
            LOG.error('Unexpected error updating the task partitioner: %s', e)
        finally:
            return self._tasks or self.fallback_tasks

    def _run_job(self):
        m_count = 0
        s_count = 0
        # We are going to process the sacks we got notified for, and if we got
        # no notification, then we'll just try to process them all, just to be
        # sure we don't miss anything. In case we did not do a full scan for
        # more than `metric_processing_delay`, we do that instead.
        if self._last_full_sack_scan.elapsed() >= self.interval_delay:
            sacks = self._get_sacks_to_process()
        else:
            sacks = (self.sacks_with_measures_to_process.copy()
                     or self._get_sacks_to_process())
        for s in sacks:
            # TODO(gordc): support delay release lock so we don't
            # process a sack right after another process
            lock = self.incoming.get_sack_lock(self.coord, s)
            if not lock.acquire(blocking=False):
{'fraction_non_alphanumeric': 0.07781692317201311, 'fraction_numerical': 0.0034612769639656344, 'mean_word_length': 2.2986748216106014, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1964956', 'n_tokens_mistral': 4559, 'n_tokens_neox': 4399, 'n_words': 1209}