# Copyright 2015 Huawei Technologies Co., Ltd.
#
#    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 oslo_config import cfg
from oslo_log import log as logging
from pecan import rest
import six
import tooz.coordination
import wsmeext.pecan as wsme_pecan

from mistral.api import access_control as acl
from mistral.api.controllers.v2 import resources
# TODO(rakhmerov): invalid dependency, a REST controller must not depend on
# a launch script.
from mistral.cmd import launch
from mistral import context
from mistral import exceptions as exc
from mistral.service import coordination
from mistral.utils import rest_utils


LOG = logging.getLogger(__name__)


class ServicesController(rest.RestController):
    @rest_utils.wrap_wsme_controller_exception
    @wsme_pecan.wsexpose(resources.Services)
    def get_all(self):
        """Return all services."""
        acl.enforce('services:list', context.ctx())

        LOG.info("Fetch services.")

        if not cfg.CONF.coordination.backend_url:
            raise exc.CoordinationException("Service API is not supported.")

        service_coordinator = coordination.get_service_coordinator()

        if not service_coordinator.is_active():
            raise exc.CoordinationException(
                "Failed to connect to coordination backend."
            )

        services_list = []
        service_group = ['%s_group' % i for i in launch.LAUNCH_OPTIONS]

        try:
            for group in service_group:
                members = service_coordinator.get_members(group)
                services_list.extend(
                    [resources.Service.from_dict(
                        {'type': group, 'name': member}) for member in members]
                )
        except tooz.coordination.ToozError as e:
            # In the scenario of network interruption or manually shutdown
            # connection shutdown, ToozError will be raised.
            raise exc.CoordinationException(
                "Failed to get service members from coordination backend. %s"
                % six.text_type(e)
            )

        return resources.Services(services=services_list)

[((33, 6, 33, 33), 'oslo_log.log.getLogger', 'logging.getLogger', ({(33, 24, 33, 32): '__name__'}, {}), '(__name__)', True, 'from oslo_log import log as logging\n'), ((38, 5, 38, 44), 'wsmeext.pecan.wsexpose', 'wsme_pecan.wsexpose', ({(38, 25, 38, 43): 'resources.Services'}, {}), '(resources.Services)', True, 'import wsmeext.pecan as wsme_pecan\n'), ((48, 30, 48, 68), 'mistral.service.coordination.get_service_coordinator', 'coordination.get_service_coordinator', ({}, {}), '()', False, 'from mistral.service import coordination\n'), ((73, 15, 73, 57), 'mistral.api.controllers.v2.resources.Services', 'resources.Services', (), '', False, 'from mistral.api.controllers.v2 import resources\n'), ((41, 37, 41, 50), 'mistral.context.ctx', 'context.ctx', ({}, {}), '()', False, 'from mistral import context\n'), ((46, 18, 46, 76), 'mistral.exceptions.CoordinationException', 'exc.CoordinationException', ({(46, 44, 46, 75): '"""Service API is not supported."""'}, {}), "('Service API is not supported.')", True, 'from mistral import exceptions as exc\n'), ((51, 18, 53, 13), 'mistral.exceptions.CoordinationException', 'exc.CoordinationException', ({(52, 16, 52, 60): '"""Failed to connect to coordination backend."""'}, {}), "('Failed to connect to coordination backend.')", True, 'from mistral import exceptions as exc\n'), ((62, 21, 63, 56), 'mistral.api.controllers.v2.resources.Service.from_dict', 'resources.Service.from_dict', ({(63, 24, 63, 55): "{'type': group, 'name': member}"}, {}), "({'type': group, 'name': member})", False, 'from mistral.api.controllers.v2 import resources\n'), ((70, 18, 70, 34), 'six.text_type', 'six.text_type', ({(70, 32, 70, 33): 'e'}, {}), '(e)', False, 'import six\n')]