-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathindex.php
239 lines (198 loc) · 7.63 KB
/
index.php
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env php
<?php
/*
* Copyright (C) 2024 Xibo Signage Ltd
*
* Xibo - Digital Signage - https://xibosignage.com
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Loop;
use React\Http\Message\Response;
use Xibo\Controller\Api;
use Xibo\Controller\Relay;
use Xibo\Controller\Server;
use Xibo\Entity\Queue;
require 'vendor/autoload.php';
// TODO: ratchet does not support PHP8
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set('display_errors', 0);
set_error_handler(function($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting
return;
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
// Decide where to look for the config file
$dirname = (Phar::running(false) == '') ? __DIR__ : dirname(Phar::running(false));
$config = $dirname . '/config.json';
if (!file_exists($config)) {
throw new InvalidArgumentException('Missing ' . $config . ' file, please create one in ' . $dirname);
}
$configString = file_get_contents($config);
$config = json_decode($configString);
if ($config === null) {
throw new InvalidArgumentException('Cannot decode config file ' . json_last_error_msg() . ' config string is [' . $configString . ']');
}
$logLevel = $config->debug ? Logger::DEBUG : Logger::WARNING;
// Set up logging to file
$log = new Logger('xmr');
$log->pushHandler(new StreamHandler(STDOUT, $logLevel));
// Queue settings
$queuePoll = $config->queuePoll ?? 5;
$queueSize = $config->queueSize ?? 10;
// Create a client to relay messages
$relay = new Relay(
$log,
$config->relayMessages ?? '',
$config->relayOldMessages ?? '',
);
// Create an in memory message queue.
$messageQueue = new Queue();
try {
$loop = Loop::get();
// Private API
// -----------
// Create a private API to receive messages from the CMS
$api = new Api($messageQueue, $log, $relay);
// Create a HTTP server to handle requests to the API
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) use ($log, $api) {
try {
if ($request->getMethod() !== 'POST') {
throw new Exception('Method not allowed');
}
$json = json_decode($request->getBody()->getContents(), true);
if ($json === false || !is_array($json)) {
throw new InvalidArgumentException('Not valid JSON');
}
return $api->handleMessage($json);
} catch (Exception $e) {
$log->error('API: e = ' . $e->getMessage());
return new Response(
422,
['Content-Type' => 'plain/text'],
$e->getMessage()
);
}
});
$socket = new React\Socket\SocketServer($config->sockets->api);
$http->listen($socket);
$http->on('error', function (Exception $exception) use ($log) {
$log->error('http: ' . $exception->getMessage());
});
$log->info('HTTP listening');
// WS
// ----
// Web Socket server
$messagingServer = new Server($messageQueue, $log);
$wsSocket = new React\Socket\SocketServer($config->sockets->ws);
$wsServer = new WsServer($messagingServer);
$ioServer = new IoServer(
new HttpServer($wsServer),
$wsSocket,
$loop
);
// Enable keep alive
$wsServer->enableKeepAlive($ioServer->loop);
$log->info('WS listening on ' . $config->sockets->ws);
// PUB/SUB
// -------
// LEGACY: Pub socket for messages to Players (subs)
if ($relay->isRelayOld()) {
$log->info('Legacy: relaying old messages');
$publisher = null;
$relay->configureZmq();
} else {
$log->info('Legacy: handling old messages');
$publisher = (new React\ZMQ\Context($loop))->getSocket(ZMQ::SOCKET_PUB);
// Set PUB socket options
if (isset($config->ipv6PubSupport) && $config->ipv6PubSupport === true) {
$log->debug('Pub MQ Setting socket option for IPv6 to TRUE');
$publisher->setSockOpt(\ZMQ::SOCKOPT_IPV6, true);
}
foreach ($config->sockets->zmq as $pubOn) {
$log->info(sprintf('Bind to %s for Publish.', $pubOn));
$publisher->bind($pubOn);
}
}
// Queue Processor
// ---------------
$log->debug('Adding a queue processor for every ' . $queuePoll . ' seconds');
$loop->addPeriodicTimer($queuePoll, function() use ($log, $messagingServer, $relay, $publisher, $messageQueue, $queueSize) {
// Is there work to be done
if ($messageQueue->hasItems()) {
$log->debug('Queue Poll - work to be done.');
$messageQueue->sortQueue();
$log->debug('Queue Poll - message queue sorted');
// Send up to X messages.
for ($i = 0; $i < $queueSize; $i++) {
if ($i > $messageQueue->queueSize()) {
$log->debug('Queue Poll - queue size reached');
break;
}
// Pop an element
$msg = $messageQueue->getItem();
// Send
$log->debug('Sending ' . $i);
// Where are we sending this item?
if ($msg->isWebSocket) {
$display = $messagingServer->getDisplayById($msg->channel);
if ($display === null) {
if ($relay->isRelay()) {
$relay->relay($msg);
} else {
$log->info('Display ' . $msg->channel . ' not connected');
}
} else {
$display->connection->send($msg->message);
}
} else if ($relay->isRelayOld()) {
$relay->relay($msg);
} else if ($publisher !== null) {
$publisher->sendmulti([$msg->channel, $msg->key, $msg->message], \ZMQ::MODE_DONTWAIT);
} else {
$log->error('No route to send');
}
$log->debug('Popped ' . $i . ' from the queue, new queue size ' . $messageQueue->queueSize());
}
}
});
// Periodic updater
$loop->addPeriodicTimer(30, function() use ($log, $messagingServer, $publisher) {
$log->debug('Heartbeat...');
// Send to all connected WS clients
$messagingServer->heartbeat();
// Send to PUB queue
$publisher?->sendmulti(["H", "", ""], \ZMQ::MODE_DONTWAIT);
});
// Key management
$loop->addPeriodicTimer(3600, function() use ($log, $messageQueue) {
$log->debug('Key management...');
$messageQueue->expireKeys();
});
// Run the React event loop
$loop->run();
} catch (Exception $e) {
$log->error($e->getMessage());
$log->error($e->getTraceAsString());
}
// This ends - causing Docker to restart if we're in a container.