<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# this file is part of 'RAX-AutoScaler'
#
# Copyright 2014 Rackspace US, Inc.
#
# 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 argparse
import logging.config
import socket

from raxas import common, enums
from raxas.colouredconsolehandler import ColouredConsoleHandler
from raxas.auth import Auth
from raxas.version import return_version
from raxas.core_plugins.raxmon import Raxmon


# CHECK logging.conf
logging_config = common.check_file('logging.conf')

if logging_config is None:
    logging.handlers.ColouredConsoleHandler = ColouredConsoleHandler
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

else:

    logging_conf_file = logging_config
    logging.handlers.ColouredConsoleHandler = ColouredConsoleHandler
    logging.config.fileConfig(logging_conf_file)
    logger = logging.getLogger(__name__)


def is_node_master(scalingGroup):
    """This function checks scaling group state and determines if node is a master.

    :param scalingGroup: data about servers in scaling group retrieve from cloudmonitor
    :returns: enums.NodeStatus

    """
    masters = []
    node_id = common.get_machine_uuid(scalingGroup)

    if node_id is None:
        logger.error('Failed to get server uuid')
        return enums.NodeStatus.Unknown

    sg_state = scalingGroup.get_state()
    if len(sg_state['active']) == 1:
        masters.append(sg_state['active'][0])
    elif len(sg_state['active']) > 1:
        masters.append(sg_state['active'][0])
        masters.append(sg_state['active'][1])
    else:
        logger.error('Unknown cluster state')
        return enums.NodeStatus.Unknown

    if node_id in masters:
        logger.info('Node is a master, continuing')
        return enums.NodeStatus.Master
    else:
        logger.info('Node is not a master, nothing to do. Exiting')
        return enums.NodeStatus.Slave


def autoscale(group, config_data, args):
    """This function executes scale up or scale down policy

    :param group: group name
    :param config_data: json configuration data
    :param args: user provided arguments
    :returns: enums.ScaleEvent
    """

    scalingGroup = common.get_scaling_group(group, config_data)
    if scalingGroup is None:
        logger.error('Unable to get scaling group: %s', group)
        return enums.ScaleEvent.Error

    logger.info('Cluster Mode Enabled: %s', args.get('cluster', False))

    if args['cluster']:
        is_master = is_node_master(scalingGroup)
        if is_master in [enums.NodeStatus.Slave, enums.NodeStatus.Unknown]:
            return enums.ScaleEvent.NotMaster

    monitor = Raxmon(scalingGroup,
                     common.get_plugin_config(config_data, group, "raxmon"), args)

    scaling_decision = monitor.make_decision()
    if scaling_decision <= -1:
        scaling_decision = -1
    elif scaling_decision >= 1:
        scaling_decision = 1

    scale = {-1: 'down', 1: 'up'}.get(scaling_decision, None)
    if scale is None:
        logger.info('Cluster within target parameters')
        return enums.ScaleEvent.NoAction

    try:
        logger.info('Threshold reached - Scaling %s', scale.title())
        scale_policy_id = common.get_group_value(config_data, group, 'scale_%s_policy' % scale)
        scale_policy = scalingGroup.get_policy(scale_policy_id)
        if not args['dry_run']:
            common.webhook_call(config_data, group, 'scale_%s' % scale, 'pre')
            scale_policy.execute()
            logger.info('Scale %s policy executed (%s)', scale, scale_policy_id)
            common.webhook_call(config_data, group, 'scale_%s' % scale, 'post')
        else:
            logger.info('Scale %s prevented by --dry-run', scale)<commit_msg>don't scale down when no monitoring data returned<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# this file is part of 'RAX-AutoScaler'
#
# Copyright 2014 Rackspace US, Inc.
#
# 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 argparse
import logging.config
import socket

from raxas import common, enums
from raxas.colouredconsolehandler import ColouredConsoleHandler
from raxas.auth import Auth
from raxas.version import return_version
from raxas.core_plugins.raxmon import Raxmon


# CHECK logging.conf
logging_config = common.check_file('logging.conf')

if logging_config is None:
    logging.handlers.ColouredConsoleHandler = ColouredConsoleHandler
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

else:

    logging_conf_file = logging_config
    logging.handlers.ColouredConsoleHandler = ColouredConsoleHandler
    logging.config.fileConfig(logging_conf_file)
    logger = logging.getLogger(__name__)


def is_node_master(scalingGroup):
    """This function checks scaling group state and determines if node is a master.

    :param scalingGroup: data about servers in scaling group retrieve from cloudmonitor
    :returns: enums.NodeStatus

    """
    masters = []
    node_id = common.get_machine_uuid(scalingGroup)

    if node_id is None:
        logger.error('Failed to get server uuid')
        return enums.NodeStatus.Unknown

    sg_state = scalingGroup.get_state()
    if len(sg_state['active']) == 1:
        masters.append(sg_state['active'][0])
    elif len(sg_state['active']) > 1:
        masters.append(sg_state['active'][0])
        masters.append(sg_state['active'][1])
    else:
        logger.error('Unknown cluster state')
        return enums.NodeStatus.Unknown

    if node_id in masters:
        logger.info('Node is a master, continuing')
        return enums.NodeStatus.Master
    else:
        logger.info('Node is not a master, nothing to do. Exiting')
        return enums.NodeStatus.Slave


def autoscale(group, config_data, args):
    """This function executes scale up or scale down policy

    :param group: group name
    :param config_data: json configuration data
    :param args: user provided arguments
    :returns: enums.ScaleEvent
    """

    scalingGroup = common.get_scaling_group(group, config_data)
    if scalingGroup is None:
        logger.error('Unable to get scaling group: %s', group)
        return enums.ScaleEvent.Error

    logger.info('Cluster Mode Enabled: %s', args.get('cluster', False))

    if args['cluster']:
        is_master = is_node_master(scalingGroup)
        if is_master in [enums.NodeStatus.Slave, enums.NodeStatus.Unknown]:
            return enums.ScaleEvent.NotMaster

    monitor = Raxmon(scalingGroup,
                     common.get_plugin_config(config_data, group, "raxmon"), args)

    scaling_decision = monitor.make_decision()
    if scaling_decision is None:
        return enums.ScaleEvent.Error
    elif scaling_decision <= -1:
        scaling_decision = -1
    elif scaling_decision >= 1:
        scaling_decision = 1

    scale = {-1: 'down', 1: 'up'}.get(scaling_decision, None)
    if scale is None:
        logger.info('Cluster within target parameters')
        return enums.ScaleEvent.NoAction

    try:
        logger.info('Threshold reached - Scaling %s', scale.title())
        scale_policy_id = common.get_group_value(config_data, group, 'scale_%s_policy' % scale)
        scale_policy = scalingGroup.get_policy(scale_policy_id)
        if not args['dry_run']:
            common.webhook_call(config_data, group, 'scale_%s' % scale, 'pre')
            scale_policy.execute()
            logger.info('Scale %s policy executed (%s)', scale, scale_policy_id)
            common.webhook_call(config_data, group, 'scale_%s' % scale, 'post')
        else:
            logger.info('Scale %s prevented by --dry-run', scale)
{'fraction_non_alphanumeric': 0.09473563482050694, 'fraction_numerical': 0.005275834384677142, 'mean_word_length': 3.4444444444444446, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, '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': '5067070', 'n_tokens_mistral': 2564, 'n_tokens_neox': 2478, 'n_words': 740}