aboutsummaryrefslogtreecommitdiffstats
path: root/vicn/resource/gui.py
blob: 26129b3e1cac15f660b896e43fe993870f86cba6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Cisco and/or its affiliates.
#
# 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 http.server
import io
import os
import socket
import socketserver
import sys
import threading

from vicn.core.resource_mgr             import ResourceManager
from vicn.helpers.resource_definition   import *

DEFAULT_GUI_ADDRESS = ''
DEFAULT_GUI_PORT    = 8000

class GUIHandler(http.server.SimpleHTTPRequestHandler):
    def send_head(self):
        if self.path == '/js/settings.js':
            return self.get_settings()
        return super().send_head()

    def get_settings(self):
        host = self.request.getsockname()[0]
        port = ResourceManager().get('websocket_port');
        r = []
        r.append("var URL='ws://{}:{}';\n".format(host, port))
        enc = sys.getfilesystemencoding()
        encoded = '\n'.join(r).encode(enc, 'surrogateescape')
        f = io.BytesIO()
        f.write(encoded)
        f.seek(0)
        self.send_response(http.server.HTTPStatus.OK)
        self.send_header("Content-type", "text/javascript;")
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        return f


class GUI(Resource):
    """
    Resource: GUI

    This resource is empty on purpose. It is a temporary resource used as a
    placeholder for controlling the GUI and should be deprecated in future
    releases.
    """
    address = Attribute(String, description = 'Address on which the Webserver listens',
        default = DEFAULT_GUI_ADDRESS)
    port = Attribute(Integer, description = 'Port on which the Webserver listens',
        default = DEFAULT_GUI_PORT)
    path = Attribute(String, default='www')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        thread = threading.Thread(target = self.run)
        thread.daemon = True
        # XXX vICN should expose internal resources for interaction
        try:
            thread.start()
        except KeyboardInterrupt:
            server.shutdown()
            sys.exit(0)

    def run(self):
        if not self.path.startswith(os.path.sep):
            # XXX we might also search in the experiment folder
            base_dir = os.path.join(os.path.dirname(__file__), os.path.pardir,
                    os.path.pardir)
            web_dir = os.path.join(base_dir, self.path)
        else:
            web_dir = self.path
        os.chdir(web_dir)
        socketserver.TCPServer.allow_reuse_address = True
        httpd = socketserver.TCPServer((self.address, self.port), GUIHandler)
        httpd.serve_forever()

    def __del__(self):
        pass