<commit_before>#    Copyright 2015 Mirantis, 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.

"""Solar CLI api

On create "golden" resource should be moved to special place
"""

import click
from fabric import api as fabric_api
import json
import networkx as nx
import os
import pprint
import sys
import tabulate
import yaml

from solar import utils
from solar.core import actions
from solar.core import resource as sresource
from solar.core import signals
from solar.core.tags_set_parser import Expression
from solar.core.resource import virtual_resource as vr
from solar.interfaces.db import get_db
from solar import errors
from solar.core.log import log

from solar.cli import base
from solar.cli import executors
from solar.cli.orch import orchestration
from solar.cli.system_log import changes
from solar.cli.events import events


db = get_db()


# HELPERS
def format_resource_input(resource_name, resource_input_name):
    return '{}::{}'.format(
        #click.style(resource_name, fg='white', bold=True),
        resource_name,
        click.style(resource_input_name, fg='yellow')
    )

def show_emitter_connections(emitter_name, destinations):
    inputs = sorted(destinations)

    for emitter_input in inputs:
        click.echo(
            '{} -> {}'.format(
                format_resource_input(emitter_name, emitter_input),
                '[{}]'.format(
                    ', '.join(
                        format_resource_input(*r)
                        for r in destinations[emitter_input]
                    )
                )
            )
        )


@click.group(cls=base.AliasedGroup)
def main():
    pass


def init_actions():
    @main.command()
    @click.option('-t', '--tags')
    @click.option('-a', '--action')
    @click.option('-d', '--dry-run', default=False, is_flag=True)
    @click.option('-m', '--dry-run-mapping', default='{}')
    def run(dry_run_mapping, dry_run, action, tags):
        from solar.core import actions
        from solar.core import resource

        if dry_run:
            dry_run_executor = executors.DryRunExecutor(mapping=json.loads(dry_run_mapping))

        resources = filter(
            lambda r: Expression(tags, r.get('tags', [])).evaluate(),
            db.get_list('resource'))

        for resource in resources:
            resource_obj = sresource.load(resource['id'])
            actions.resource_action(resource_obj, action)

        if dry_run:
            click.echo('EXECUTED:')
            for key in dry_run_executor.executed:
                click.echo('{}: {}'.format(
                    click.style(dry_run_executor.compute_hash(key), fg='green'),
                    str(key)
                ))


def init_cli_connect():
    @main.command()
    @click.argument('emitter')
    @click.argument('receiver')
    @click.argument('mapping', default='')
    def connect(mapping, receiver, emitter):
        mapping_parsed = {}

        click.echo('Connect {} to {}'.format(emitter, receiver))
        emitter = sresource.load(emitter)
        receiver = sresource.load(receiver)
        try:
            mapping_parsed.update(json.loads(mapping))
        except ValueError:
            for m in mapping.split():
                k, v = m.split('->')
                mapping_parsed.update({k: v})
        signals.connect(emitter, receiver, mapping=mapping_parsed)

        clients = signals.Connections.read_clients()
        show_emitter_connections(emitter.name, clients[emitter.name])

    @main.command()
    @click.argument('emitter')
    @click.argument('receiver')
    def disconnect(receiver, emitter):
        click.echo('Disconnect {} from {}'.format(emitter, receiver))
        emitter = sresource.load(emitter)
        receiver = sresource.load(receiver)
        click.echo(emitter)
        click.echo(receiver)
        signals.disconnect(emitter, receiver)

        clients = signals.Connections.read_clients()
        show_emitter_connections(emitter.name, clients[emitter.name])


def init_cli_connections():
    @main.group()
    def connections():
        pass

    @connections.command()
    def clear_all():
        click.echo('Clearing all connections')
        signals.Connections.clear()

    @connections.command()
    def show():
        clients = signals.Connections.read_clients()
        keys = sorted(clients)
        for emitter_name in keys:
            show_emitter_connections(emitter_name, clients[emitter_name])

    # TODO: this requires graphing libraries
    @connections.command()
    @click.option('--start-with', default=None)
    @click.option('--end-with', default=None)
    def graph(start_with, end_with):
        g = signals.detailed_connection_graph(start_with=start_with,
                                              end_with=end_with)

        nx.write_dot(g, 'graph.dot')<commit_msg>CLI: fix show_emitter_connections function, remove connections clear_all<commit_after>#    Copyright 2015 Mirantis, 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.

"""Solar CLI api

On create "golden" resource should be moved to special place
"""

import click
from fabric import api as fabric_api
import json
import networkx as nx
import os
import pprint
import sys
import tabulate
import yaml

from solar.core import actions
from solar.core import resource as sresource
from solar.core import signals
from solar.core.tags_set_parser import Expression
from solar.core.resource import virtual_resource as vr
from solar.core.log import log
from solar import errors
from solar.interfaces.db import get_db
from solar.interfaces import orm
from solar import utils

from solar.cli import base
from solar.cli import executors
from solar.cli.orch import orchestration
from solar.cli.system_log import changes
from solar.cli.events import events


db = get_db()


# HELPERS
def format_resource_input(resource_input):
    return '{}::{}'.format(
        #click.style(resource_name, fg='white', bold=True),
        resource_input.resource.name,
        click.style(resource_input.name, fg='yellow')
    )


def show_emitter_connections(emitter):
    for emitter_input in emitter.resource_inputs().values():
        click.echo(
            '{} -> {}'.format(
                format_resource_input(emitter_input),
                '[{}]'.format(
                    ', '.join(
                        format_resource_input(r)
                        for r in emitter_input.receivers.value
                    )
                )
            )
        )


@click.group(cls=base.AliasedGroup)
def main():
    pass


def init_actions():
    @main.command()
    @click.option('-t', '--tags')
    @click.option('-a', '--action')
    @click.option('-d', '--dry-run', default=False, is_flag=True)
    @click.option('-m', '--dry-run-mapping', default='{}')
    def run(dry_run_mapping, dry_run, action, tags):
        from solar.core import actions
        from solar.core import resource

        if dry_run:
            dry_run_executor = executors.DryRunExecutor(mapping=json.loads(dry_run_mapping))

        resources = filter(
            lambda r: Expression(tags, r.get('tags', [])).evaluate(),
            db.get_list('resource'))

        for resource in resources:
            resource_obj = sresource.load(resource['id'])
            actions.resource_action(resource_obj, action)

        if dry_run:
            click.echo('EXECUTED:')
            for key in dry_run_executor.executed:
                click.echo('{}: {}'.format(
                    click.style(dry_run_executor.compute_hash(key), fg='green'),
                    str(key)
                ))


def init_cli_connect():
    @main.command()
    @click.argument('emitter')
    @click.argument('receiver')
    @click.argument('mapping', default='')
    def connect(mapping, receiver, emitter):
        mapping_parsed = {}

        click.echo('Connect {} to {}'.format(emitter, receiver))
        emitter = sresource.load(emitter)
        receiver = sresource.load(receiver)
        try:
            mapping_parsed.update(json.loads(mapping))
        except ValueError:
            for m in mapping.split():
                k, v = m.split('->')
                mapping_parsed.update({k: v})
        signals.connect(emitter, receiver, mapping=mapping_parsed)

        show_emitter_connections(emitter)

    @main.command()
    @click.argument('emitter')
    @click.argument('receiver')
    def disconnect(receiver, emitter):
        click.echo('Disconnect {} from {}'.format(emitter, receiver))
        emitter = sresource.load(emitter)
        receiver = sresource.load(receiver)
        click.echo(emitter)
        click.echo(receiver)
        signals.disconnect(emitter, receiver)

        show_emitter_connections(emitter)


def init_cli_connections():
    @main.group()
    def connections():
        pass

    @connections.command()
    def show():
        resources = sresource.load_all()
        for r in resources:
            show_emitter_connections(r)

    # TODO: this requires graphing libraries
    @connections.command()
    @click.option('--start-with', default=None)
    @click.option('--end-with', default=None)
    def graph(start_with, end_with):
        g = signals.detailed_connection_graph(start_with=start_with,
                                              end_with=end_with)

        nx.write_dot(g, 'graph.dot')
{'fraction_non_alphanumeric': 0.10779020439645198, 'fraction_numerical': 0.0015426147319706903, 'mean_word_length': 2.634548002803083, 'pattern_counts': {'":': 0, '<': 3, '<?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': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5251325', 'n_tokens_mistral': 2997, 'n_tokens_neox': 2858, 'n_words': 754}