forked from mugifly/vm-signage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrol-server.pl
executable file
·365 lines (302 loc) · 8.36 KB
/
control-server.pl
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env perl
# VM Signare - Control server
use Mojolicious::Lite;
use Mojo::JSON;
# ----
# Initialize hash / array for WebSocket
our %deviceClients = (); # Key: Tx string, Value: Hash-ref
our %adminClients = (); # Key: Tx string, Value: Tx
our %adminWsKeys = (); # Key: Websocket auth key, Value: Generated date epoch-sec
# Initialize array of Id for processed queue
our @processed_queues_id = ();
# Initialize repository revision
our %repo_revs = ();
# Set configuration for hypnotoad daemon
app->config(
hypnotoad => {
listen => [ 'http://*:' . ( $ENV{PORT} || 80 ) ],
workers => 1,
},
);
# To serve static files
push @{app->static->paths}, app->home->rel_dir('assets/control-server');
# Helper - redis
app->helper(redis => sub {
if (!defined $ENV{REDISCLOUD_URL}) {
warn 'REDISCLOUD_URL is not defined; Please run: $ heroku addons:add rediscloud';
return undef;
}
return Redis->new(server => $ENV{REDISCLOUD_URL});
});
app->helper(push_queue_to_redis => sub {
my ($s, $type, $content) = @_;
if (defined $s->redis()) {
$s->redis()->rpush('queues', Mojo::JSON::encode_json({
id => time(),
created_at => time(),
type => $type,
content => Mojo::JSON::encode_json($content),
}));
} else {
foreach my $id (keys %deviceClients) {
$deviceClients{$id}->{tx}->send(Mojo::JSON::encode_json($content));
}
}
});
# Helper - Log
app->helper(write_device_log => sub {
my ($s, $device_name, $message) = @_;
# Output to log
$s->app->log->debug("Device log - ${message}");
# Send to admin clients
foreach my $id (keys %adminClients) {
$adminClients{$id}->send(Mojo::JSON::encode_json({
cmd => 'log',
log_from => $device_name,
log_text => $message,
}));
}
});
# WebSocket endpoint for push notification to signage device
websocket '/notif' => sub {
my $s = shift;
# Set timeout sec
$s->inactivity_timeout(600);
# Insert connection into clients hash
my $client_id = sprintf("%s", $s->tx);
my $device_name = $client_id;
if ($device_name =~ /HASH\((.+)\)/) {
$device_name = $1;
}
$deviceClients{$client_id} = {
name => $device_name,
tx => $s->tx,
connected_at => time(),
config => undef,
};
# Set event handlers
$s->on(json => sub { # Incomming message
my ($tx, $hash) = @_;
if (defined $hash->{cmd}) {
if ($hash->{cmd} eq 'post-log') { # Posting of log
$s->write_device_log($client_id, $hash->{log_text});
} elsif ($hash->{cmd} eq 'set-device-info') { # Set of device information
foreach my $k (keys %{$hash->{device_info}}) {
$deviceClients{$client_id}->{$k} = $hash->{device_info}->{$k};
}
} elsif ($hash->{cmd} eq 'get-latest-repo-rev') { # Getting of latest revision of repository
$s->app->log->debug("Received cmd - " . $hash->{cmd});
$tx->send({ json => {
cmd => $hash->{cmd},
repo_rev => $repo_revs{master} || undef, # for old version
repo_revs => \%repo_revs, # for compatibility with old version
}});
} else {
$s->app->log->warn("Received unknown command - " . $hash->{cmd});
}
}
});
$s->on(finish => sub { # Closed
my ($s, $code, $reason) = @_;
delete $deviceClients{$client_id};
$s->write_device_log($client_id, "Device diconnected - Code = " . $code);
});
$s->write_device_log($client_id, "Device connected");
return;
};
# Webhook receiver for pushed on GitHub
any '/github-webhook-receiver' => sub {
my $s = shift;
# Read payload parameter
my $data = $s->req->body;
my $payload;
eval {
$payload = Mojo::JSON::decode_json($data);
}; if ($@) {
$s->render(text => 'Invalid payload format', status => 400);
return;
}
# Save revision
if (!defined $payload->{ref} || $payload->{ref} !~ /^refs\/heads\/(.+)/) {
$s->render(text => 'Invalid target refs', status => 400);
return;
}
my $branch = $1;
my $rev = $payload->{after};
$repo_revs{$branch} = $rev;
# Insert a notification-task to queue
$s->push_queue_to_redis('notify-to-clients', {
cmd => 'repository-updated',
branch => $branch,
});
$s->render(text => 'OK:' . $branch);
};
# Webhook receiver for general
any '/webhook-receiver' => sub {
my $s = shift;
if (!defined $ENV{VM_SIGNAGE_WEBHOOK_KEY}) {
my $msg = <<EOF;
For using webhook receiver, You must defined VM_SIGNAGE_WEBHOOK_KEY on Environment variables.
EOF
$s->render(text => $msg, status => 400);
return;
} elsif (!defined $s->param('webhook_key')) {
$s->render(text => "webhook_key parameter was not presented.", status => 400);
return;
}
# Check for key
if ($s->param('webhook_key') ne $ENV{VM_SIGNAGE_WEBHOOK_KEY}) {
$s->render(text => "webhook_key parameter was not matched with value of VM_SIGNAGE_WEBHOOK_KEY.", status => 401);
return;
}
# Check for command
my $is_success = 0;
my $cmd = $s->param('cmd') || undef;
if ($cmd eq 'restart') {
# Insert a notification-task to queue
$s->push_queue_to_redis('notify-to-clients', {
cmd => 'restart',
});
$is_success = 1;
}
if ($is_success == 0) {
$s->render(text => 'cmd parameter was invalid or failed');
return;
}
$s->render(text => "OK:${cmd}");
};
# Web console for administrators
any '/admin' => sub {
my $s = shift;
if (!defined $ENV{VM_SIGNAGE_AUTH_USERNAME} || !defined $ENV{VM_SIGNAGE_AUTH_PASSWORD}) {
my $msg = <<EOF;
For using web console,
You must defined VM_SIGNAGE_AUTH_USERNAME and VM_SIGNAGE_AUTH_PASSWORD on Environment variables.
EOF
$s->render(text => $msg, status => 400);
return;
}
# Require basic authentication
$s->res->headers->www_authenticate('Basic');
# Check for user name and password
my $basic_str = $ENV{VM_SIGNAGE_AUTH_USERNAME} . ':' . $ENV{VM_SIGNAGE_AUTH_PASSWORD};
if ($s->req->url->to_abs->userinfo ne $basic_str) {
my $msg = <<EOF;
Please authentication
EOF
$s->render(text => $msg, status => 401);
return;
}
# Generate key for websocket authentication
my $ws_key = Mojo::Util::sha1_sum(time() . '-' . int(rand(9999999)));
$adminWsKeys{$ws_key} = time();
$s->stash(ws_key => $ws_key);
# Output
$s->render(template => 'admin');
};
# WebSocket endpoint for web console
websocket '/admin/ws/:wsKey' => sub {
my $s = shift;
my $ws_key = $s->param('wsKey');
if (!defined $ws_key || !defined $adminWsKeys{$ws_key}) {
$s->app->log->warn('Admin websocket connection was blocked: ' . $ws_key);
$s->tx->finish();
return;
}
# Set timeout sec
$s->inactivity_timeout(600);
# Insert connection into clients hash
my $client_id = sprintf("%s", $s->tx);
$adminClients{$client_id} = $s->tx;
# Set event handlers
$s->on(json => sub { # Incomming message
my ($tx, $hash) = @_;
if ($hash->{cmd} eq 'restart') {
# Insert a notification-task to queue
$s->push_queue_to_redis('notify-to-clients', {
cmd => 'restart',
});
}
});
$s->on(finish => sub { # Closed
my ($s, $code, $reason) = @_;
delete $adminClients{$client_id};
delete $adminWsKeys{$ws_key};
});
return;
};
# ----
# Loop for ping and queue checking
my $id = Mojo::IOLoop->recurring(5 => sub {
# Make the signage device list
my @devices = ();
foreach my $id (keys %deviceClients) {
my %device = %{$deviceClients{$id}};
delete $device{tx}; # Delete property from copied hash
push(@devices, \%device);
}
# Ping to signage devices
foreach my $id (keys %deviceClients) {
eval {
$deviceClients{$id}->{tx}->send(Mojo::JSON::encode_json({
cmd => 'device-ping',
created_at => time(),
}));
};
}
# Ping to admin console
foreach my $id (keys %adminClients) {
# Send to admin console
eval {
$adminClients{$id}->send(Mojo::JSON::encode_json({
cmd => 'device-list',
devices => \@devices
}));
};
}
# Queue checking
my $redis = undef;
if (!defined app->redis()) {
return;
}
my $len = $redis->llen('queues');
if ($len <= 0) {
return;
}
for (my $i = 0; $i < $len; $i++) {
my $task = Mojo::JSON::decode_json($redis->lindex('queues', $i));
}
});
# Start the server
app->start;
__DATA__
@@ admin.html.ep
<!DOCTYPE html>
<html>
<head>
<title>VM-Signage Web Console</title>
%= javascript '/mojo/jquery/jquery.js'
<script>
var WS_KEY = '<%= stash 'ws_key' %>';
</script>
%= javascript '/js/admin.js'
<style>
#deviceList .device-caption a {
margin-left: 10px;
}
#deviceList .device-info {
font-size: 80%;
}
}
</style>
</head>
<body>
<h1>vm-signage</h1>
<h2>Connected devices</h2>
<ul id="deviceList"></ul>
<h2>Commands</h2>
<button id="btnRestart" href="javascript:void(0);">Restart devices</button>
<h2>Log</h2>
<ul id="logger"></ul>
</body>
</html>