websockets.py 3.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2017, Daniele Venzano
#
# 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.

"""Ajax API for the Zoe web interface."""

import json
19
import logging
20
from concurrent.futures import ThreadPoolExecutor
21 22

import tornado.iostream
23
import tornado.gen
24 25 26

import zoe_api.exceptions
from zoe_api.api_endpoint import APIEndpoint  # pylint: disable=unused-import
27
from zoe_api.custom_request_handler import ZoeWSRequestHandler
28 29

log = logging.getLogger(__name__)
30

31 32
THREAD_POOL = ThreadPoolExecutor(20)

33

34
class WebSocketEndpointWeb(ZoeWSRequestHandler):
35 36 37
    """Handler class"""
    def initialize(self, **kwargs):
        """Initializes the request handler."""
38
        super().initialize(**kwargs)
39
        self.api_endpoint = kwargs['api_endpoint']  # type: APIEndpoint
40
        self.connection_closed = None
41

42 43 44
    def open(self, *args, **kwargs):
        """Invoked when a new WebSocket is opened."""
        log.debug('WebSocket opened')
45
        if self.current_user is None:
46
            self.close(401, "Unauthorized")
47

48 49 50 51
    def check_origin(self, origin):
        """Check connection origin."""
        return True

52
    @tornado.gen.coroutine
53 54
    def on_message(self, message):
        """WebSocket message handler."""
55

56 57 58 59 60
        if message is None:
            return

        request = json.loads(message)

61
        if request['command'] == 'query_status':
62
            try:
63
                execution = self.api_endpoint.execution_by_id(self.current_user, request['exec_id'])
64 65 66 67 68 69 70 71 72 73 74
            except zoe_api.exceptions.ZoeNotFoundException:
                response = {
                    'status': 'ok',
                    'exec_status': 'none'
                }
            else:
                response = {
                    'status': 'ok',
                    'exec_status': execution.status
                }
                if execution.status == execution.RUNNING_STATUS:
75
                    services_info_, endpoints = self.api_endpoint.execution_endpoints(self.current_user, execution)
76
                    response['endpoints'] = endpoints
77
            self.write_message(response)
78
        elif request['command'] == 'service_logs':
79 80 81 82 83 84 85 86 87 88 89 90 91
            try:
                log_obj = self.api_endpoint.service_logs(self.current_user, request['service_id'])
            except zoe_api.exceptions.ZoeException as e:
                self.write_message(str(e))
            else:
                while not self.connection_closed:
                    try:
                        log_line = yield THREAD_POOL.submit(next, log_obj)
                    except StopIteration:
                        yield tornado.gen.sleep(0.2)
                        continue

                    self.write_message(log_line)
92
        elif request['command'] == 'system_status':
93
            stats = self.api_endpoint.statistics_scheduler()
94
            self.write_message(json.dumps(stats))
95 96 97 98 99
        else:
            response = {
                'status': 'error',
                'message': 'unknown request type'
            }
100 101 102 103 104
            self.write_message(response)

    def _stream_log_line(self, log_line):
        self.write_message(log_line)
        self.stream.read_until(b'\n', callback=self._stream_log_line)
105

106 107 108
    def on_close(self):
        """Invoked when the WebSocket is closed."""
        log.debug("WebSocket closed")
109
        self.connection_closed = True
110 111 112

    def data_received(self, chunk):
        """Not implemented as we do not use stream uploads"""