Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/sugar_network/local/bus.py
blob: 5d5784071f957f6969532e84967455c94e3816ce (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# Copyright (C) 2012 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import json
import errno
import socket
import logging
from os.path import exists

import active_document as ad
from sugar_network import local
from sugar_network.toolkit import ipc, sugar
from active_toolkit import coroutine, sockets, util


_logger = logging.getLogger('local.bus')


class IPCServer(object):

    def __init__(self, mounts):
        self._subscriptions = []
        self._mounts = mounts
        self._publish_lock = coroutine.Lock()
        self._servers = coroutine.Pool()

        self._mounts.connect(self._republish)

        self._servers.spawn(
                _start_server('accept', self._serve_client))
        self._servers.spawn(
                _start_server('subscribe', self._serve_subscription))

    def serve_forever(self):
        # Clients write to rendezvous named pipe, in block mode,
        # to make sure that server is started
        rendezvous = ipc.rendezvous(server=True)
        try:
            self._servers.join()
        except KeyboardInterrupt:
            pass
        finally:
            os.close(rendezvous)

    def stop(self):
        while self._subscriptions:
            self._subscriptions.pop().close()
        self._servers.kill()

    def _serve_client(self, conn_file):
        while True:
            message = conn_file.read_message()
            if message is None:
                break
            try:
                request = ad.Request(message)
                request.principal = sugar.uid()
                request.access_level = ad.ACCESS_LOCAL

                content_type = request.pop('content_type')
                if content_type == 'application/json':
                    request.content = json.loads(conn_file.read())
                elif content_type:
                    request.content_stream = conn_file
                else:
                    request.content = conn_file.read() or None

                response = ad.Response()
                result = self._mounts.call(request, response)
                conn_file.write_message(result)

            except Exception, error:
                conn_file.write_message({'error': str(error)})

    def _serve_subscription(self, conn_file):
        _logger.debug('Added new %r subscription', conn_file)
        self._subscriptions.append(conn_file)
        return True

    def _republish(self, event):
        _logger.debug('Send notification: %r', event)

        with self._publish_lock:
            for sock in self._subscriptions[:]:
                try:
                    sock.write_message(event)
                except socket.error, error:
                    if error.errno == errno.EPIPE:
                        _logger.debug('Lost %r subscription', sock)
                        self._subscriptions.remove(sock)
                    else:
                        util.exception(_logger,
                                'Failed to deliver event via %r', sock)


def _start_server(name, serve_cb):
    accept_path = local.ensure_path('run', name)
    if exists(accept_path):
        os.unlink(accept_path)

    # pylint: disable-msg=E1101
    accept = coroutine.socket(socket.AF_UNIX)
    accept.bind(accept_path)
    accept.listen(5)

    def connection_cb(conn, address):
        conn_file = sockets.SocketFile(conn)
        _logger.debug('New %r connection: %r', name, conn_file)
        do_not_close = False
        try:
            do_not_close = serve_cb(conn_file)
        finally:
            _logger.debug('Quit %r connection: %r', name, conn_file)
            if not do_not_close:
                conn_file.close()

    return coroutine.Server(accept, connection_cb).serve_forever