<commit_before>#
# 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 collections
import itertools
import uuid

import daiquiri
import proton.handlers
import proton.reactor
import six
import ujson

from gnocchi import incoming
from gnocchi import indexer
from gnocchi import service
from gnocchi import utils

LOG = daiquiri.getLogger(__name__)


class BatchProcessor(object):
    def __init__(self, conf):
        self.conf = conf
        self.incoming = incoming.get_driver(self.conf)
        self.indexer = indexer.get_driver(self.conf)
        self._ensure_resource_type_exists()

        self._hosts = {}
        self._measures = collections.defaultdict(
            lambda: collections.defaultdict(list))

    def reset(self):
        self._hosts.clear()
        self._measures.clear()

    def add_measures(self, host, name, measures):
        host_id = "%s:%s" % (self.conf.amqp1d.resource_type,
                             host.replace("/", "_"))
        self._hosts[host_id] = host
        self._measures[host_id][name].extend(measures)

    def flush(self):
        try:
            self._flush()
        except Exception:
            LOG.error("Unepected error during flush()", exc_info=True)
        self.reset()

    def _flush(self):
        archive_policies = {}
        resources = self._get_resources(self._measures.keys())
        for host_id, measures_by_names in six.iteritems(self._measures):
            resource = resources[host_id]

            mbn_keys = measures_by_names.keys()
            names = (set(mbn_keys) if len(mbn_keys)
                     else set())

            for name in names:
                if name not in archive_policies:
                    archive_policies[name] = (
                        self.indexer.get_archive_policy_for_metric(name))
            known_metrics = self.indexer.list_metrics(attribute_filter={
                "and": [{"=": {"resource_id": resource.id}},
                        {"in": {"name": list(names)}}]
            })
            known_names = set((m.name for m in known_metrics))
            already_exists_names = []
            for name in (names - known_names):
                try:
                    m = self.indexer.create_metric(
                        uuid.uuid4(),
                        creator=self.conf.amqp1d.creator,
                        resource_id=resource.id,
                        name=name,
                        archive_policy_name=archive_policies[name].name)
                except indexer.NamedMetricAlreadyExists as e:
                    already_exists_names.append(e.metric)
                except indexer.IndexerException:<commit_msg>Only convert set to list in amqp1d _flush()<commit_after>#
# 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 collections
import itertools
import uuid

import daiquiri
import proton.handlers
import proton.reactor
import six
import ujson

from gnocchi import incoming
from gnocchi import indexer
from gnocchi import service
from gnocchi import utils

LOG = daiquiri.getLogger(__name__)


class BatchProcessor(object):
    def __init__(self, conf):
        self.conf = conf
        self.incoming = incoming.get_driver(self.conf)
        self.indexer = indexer.get_driver(self.conf)
        self._ensure_resource_type_exists()

        self._hosts = {}
        self._measures = collections.defaultdict(
            lambda: collections.defaultdict(list))

    def reset(self):
        self._hosts.clear()
        self._measures.clear()

    def add_measures(self, host, name, measures):
        host_id = "%s:%s" % (self.conf.amqp1d.resource_type,
                             host.replace("/", "_"))
        self._hosts[host_id] = host
        self._measures[host_id][name].extend(measures)

    def flush(self):
        try:
            self._flush()
        except Exception:
            LOG.error("Unepected error during flush()", exc_info=True)
        self.reset()

    def _flush(self):
        archive_policies = {}
        resources = self._get_resources(self._measures.keys())
        for host_id, measures_by_names in six.iteritems(self._measures):
            resource = resources[host_id]

            names = set(measures_by_names.keys())
            for name in names:
                if name not in archive_policies:
                    archive_policies[name] = (
                        self.indexer.get_archive_policy_for_metric(name))
            known_metrics = self.indexer.list_metrics(attribute_filter={
                "and": [{"=": {"resource_id": resource.id}},
                        {"in": {"name": list(names)}}]
            })
            known_names = set((m.name for m in known_metrics))
            already_exists_names = []
            for name in (names - known_names):
                try:
                    m = self.indexer.create_metric(
                        uuid.uuid4(),
                        creator=self.conf.amqp1d.creator,
                        resource_id=resource.id,
                        name=name,
                        archive_policy_name=archive_policies[name].name)
                except indexer.NamedMetricAlreadyExists as e:
                    already_exists_names.append(e.metric)
                except indexer.IndexerException:
{'fraction_non_alphanumeric': 0.09008, 'fraction_numerical': 0.0024, 'mean_word_length': 2.1682716675114038, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3258676', 'n_tokens_mistral': 1710, 'n_tokens_neox': 1656, 'n_words': 448}