<commit_before># (c) Copyright 2018 SUSE LLC
#
# 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.

from . import policy

from flask import abort
from flask import Blueprint
from flask import jsonify
from flask import request
import json
from keystoneauth1 import loading
from keystoneauth1 import session
from novaclient import client as novaClient
import os
from oslo_config import cfg
from oslo_log import log as logging

LOG = logging.getLogger(__name__)
bp = Blueprint('compute', __name__)
CONF = cfg.CONF


def get_compute_client(req):

    try:
        loader = loading.get_plugin_loader('v3token')
        auth = loader.load_from_options(
            auth_url=CONF.keystone_authtoken.auth_url,
            token=req.headers.get('X-Auth-Token'),
            project_name=CONF.keystone_authtoken.project_name,
            project_domain_name=CONF.keystone_authtoken.project_domain_name
        )
        sess = session.Session(auth=auth,
                               verify=not CONF.keystone_authtoken.insecure)
        compute_client = novaClient.Client(
            # api version for live_migrate with block_migration='auto'
            '2.25',
            endpoint_type="internalURL",
            session=sess
        )
        return compute_client

    except Exception as e:
        LOG.error(e)
        abort(500, 'Failed to get compute novaclient')


def complete_with_errors_response(msg, contents):
    response = jsonify({'error_msg': msg, 'contents': contents})
    response.status_code = 500
    return response


@bp.route("/api/v2/compute/services/<hostname>", methods=['GET'])
@policy.enforce('lifecycle:get_compute')
def compute_services_status(hostname):
    """Get the compute services status for a compute host

        .. :quickref: Compute; Get the compute services status

        **Example Request**:

        .. sourcecode:: http

           GET /api/v2/compute/services/<hostname> HTTP/1.1
           Content-Type: application/json

        **Example Response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK

            {
                "nova-compute": "enabled"
            }

    """
    # mock for getting nova service status for a compute host
    if cfg.CONF.testing.use_mock:
        mock_json = "tools/compute-mock-data.json"
        json_file = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), mock_json)
        with open(json_file) as f:
            return jsonify(json.load(f)['compute_services_status'])

    compute_client = get_compute_client(request)

    compute_services = compute_client.services.list(host=hostname)

    if len(compute_services) == 0:
        msg = 'No compute service for %s' % hostname
        LOG.error(msg)
        abort(410, msg)

    services = dict()

    for service in compute_services:
        binary = getattr(service, 'binary', None)
        if binary:
            services[binary] = getattr(service, 'status', None)

    return jsonify(services)


@bp.route("/api/v2/compute/services/<hostname>/disable", methods=['PUT'])
@policy.enforce('lifecycle:update_compute')
def compute_disable_services(hostname):
    """Disable the compute services for a compute host

        .. :quickref: Compute; Disable the compute services

        **Example Request**:

        .. sourcecode:: http

           PUT /api/v2/compute/services/<hostname>/disable HTTP/1.1
           Content-Type: application/json

        **Example Response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK

            [{
                "binary": "nova-compute",
                "id": 1
            }]

    """
    # mock for running nova disable service for a compute host<commit_msg>SCRD-3479 Fix issue detecting nova service state<commit_after># (c) Copyright 2018 SUSE LLC
#
# 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.

from . import policy

from flask import abort
from flask import Blueprint
from flask import jsonify
from flask import request
import json
from keystoneauth1 import loading
from keystoneauth1 import session
from novaclient import client as novaClient
import os
from oslo_config import cfg
from oslo_log import log as logging

LOG = logging.getLogger(__name__)
bp = Blueprint('compute', __name__)
CONF = cfg.CONF


def get_compute_client(req):

    try:
        loader = loading.get_plugin_loader('v3token')
        auth = loader.load_from_options(
            auth_url=CONF.keystone_authtoken.auth_url,
            token=req.headers.get('X-Auth-Token'),
            project_name=CONF.keystone_authtoken.project_name,
            project_domain_name=CONF.keystone_authtoken.project_domain_name
        )
        sess = session.Session(auth=auth,
                               verify=not CONF.keystone_authtoken.insecure)
        compute_client = novaClient.Client(
            # api version for live_migrate with block_migration='auto'
            '2.25',
            endpoint_type="internalURL",
            session=sess
        )
        return compute_client

    except Exception as e:
        LOG.error(e)
        abort(500, 'Failed to get compute novaclient')


def complete_with_errors_response(msg, contents):
    response = jsonify({'error_msg': msg, 'contents': contents})
    response.status_code = 500
    return response


@bp.route("/api/v2/compute/services/<hostname>", methods=['GET'])
@policy.enforce('lifecycle:get_compute')
def compute_services_status(hostname):
    """Get the compute services status for a compute host

        .. :quickref: Compute; Get the compute services status

        **Example Request**:

        .. sourcecode:: http

           GET /api/v2/compute/services/<hostname> HTTP/1.1
           Content-Type: application/json

        **Example Response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK

            {
                "nova-compute": "enabled"
            }

    """
    # mock for getting nova service status for a compute host
    if cfg.CONF.testing.use_mock:
        mock_json = "tools/compute-mock-data.json"
        json_file = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), mock_json)
        with open(json_file) as f:
            return jsonify(json.load(f)['compute_services_status'])

    compute_client = get_compute_client(request)

    compute_services = compute_client.services.list(host=hostname)

    if len(compute_services) == 0:
        msg = 'No compute service for %s' % hostname
        LOG.error(msg)
        abort(410, msg)

    services = dict()

    for service in compute_services:
        binary = getattr(service, 'binary', None)
        if binary:
            services[binary] = \
                getattr(service, 'status', None) == 'enabled' and \
                getattr(service, 'state', None) != 'down'

    return jsonify(services)


@bp.route("/api/v2/compute/services/<hostname>/disable", methods=['PUT'])
@policy.enforce('lifecycle:update_compute')
def compute_disable_services(hostname):
    """Disable the compute services for a compute host

        .. :quickref: Compute; Disable the compute services

        **Example Request**:

        .. sourcecode:: http

           PUT /api/v2/compute/services/<hostname>/disable HTTP/1.1
           Content-Type: application/json

        **Example Response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK

            [{
                "binary": "nova-compute",
                "id": 1
            }]

    """
    # mock for running nova disable service for a compute host
{'fraction_non_alphanumeric': 0.09591788579518641, 'fraction_numerical': 0.010618216139688533, 'mean_word_length': 2.6288527397260273, 'pattern_counts': {'":': 6, '<': 11, '<?xml version=': 0, '>': 11, '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': '1428516', 'n_tokens_mistral': 2438, 'n_tokens_neox': 2317, 'n_words': 683}