blob: f4b3e05a928d912c38720558e697b6cd3536d6f7 [file] [log] [blame]
Holger Hans Peter Freytherb7749a72018-02-25 21:08:01 +00001# osmo_ms_driver: Event loop because asyncio is not up to the job
2#
3# Copyright (C) 2018 by Holger Hans Peter Freyther
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as
7# published by the Free Software Foundation, either version 3 of the
8# License, or (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18from osmo_gsm_tester import log
19from functools import partial
20
21import os
22import selectors
23import socket
24
25
26class SimpleLoop(log.Origin):
27 def __init__(self):
28 super().__init__(log.C_RUN, "SimpleLoop")
29 self._loop = selectors.DefaultSelector()
30 self._timeout = None
31
32 def register_fd(self, fd, event, callback):
33 self._loop.register(fd, event, callback)
34
35 def schedule_timeout(self, timeout):
36 assert self._timeout == None
37 self._timeout = timeout
38
39 def create_unix_server(self, cb, path):
40 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
41
42 if len(path.encode()) > 107:
43 raise log.Error('Path for unix socket is longer than max allowed len for unix socket path (107):', path)
44
45 # If not a special Linux namespace...
46 if path[0] != '\0':
47 try:
48 os.unlink(path)
49 except FileNotFoundError:
50 pass
51
52 # Now bind+listen+NONBLOCK
53 sock.bind(path)
54 sock.setblocking(False)
55
56 self.register_fd(sock.fileno(), selectors.EVENT_READ, cb)
57 return sock
58
59 def select(self):
60 events = self._loop.select(timeout=self._timeout)
61 self._timeout = None
62 for key, mask in events:
63 key.data(key.fileobj, mask)