-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathHomeserver.pm
596 lines (427 loc) · 13.6 KB
/
Homeserver.pm
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package SyTest::Homeserver;
use strict;
use warnings;
use 5.010;
use base qw( IO::Async::Notifier SyTest::Homeserver::ProcessManager );
use Future::Utils qw( repeat );
use YAML::XS ();
use JSON ();
use File::Path qw( make_path );
use File::Slurper qw( write_binary );
use POSIX qw( WIFEXITED WEXITSTATUS );
=head1 NAME
C<SyTest::Homeserver> - base class for homeserver implementations
=head1 DESCRIPTION
This class forms the basis for the various classes which implement homeservers
(or, more accurately, which provide the code to configure, start, and stop
homeserver implementations).
=head1 REQUIRED PARAMETERS
The following named parameters must be passed to C<new>:
=head2 output => SyTest::Output
An Output instance which is used to write diagnostic information.
=head2 hs_dir => STRING
A path unique to this homeserver instance, which will be created as a temporary
directory to hold things like config files and logs.
=head2 hs_index => INTEGER
The index of this homeserver (starting from 0). Used to identify it in
diagnostic messages etc.
=head1 OPTIONAL PARAMETERS
The folowing named parameters may be passed to C<new> or C<configure>:
=head2 recaptcha_config => HASH
Parameters for testing the server's recaptcha integration. Should include the
following keys:
=over
=item C<siteverify_api>
The URI of the mock recaptcha server which the homeserver should use to
validate recaptcha submissions.
=item C<public_key>
=item C<private_key>
=back
=head2 smtp_server_config => HASH
Details of an smtp server for things like 3pid validation. Should include the
following keys:
=over
=item C<host>
The hostname where the SMTP server can be reached.
=item C<port>
The port where the SMTP server can be reached.
=back
=head2 cas_config => HASH
Parameters for testing the server's CAS integration. Should include the
following keys:
=over
=item C<server_url>
The URI of the mock CAS server which the homeserver should redirect users
to for the 'cas' login method.
=item C<service_url>
The 'Service' parameter that the homeserver should send to the mock CAS server.
=back
=head2 app_service_config_files => ARRAY
An array of paths to appservice YAML files to be included in the homeserver's
configuration.
=head1 SUBCLASS METHODS
The folowing methods must be provided by any subclass which implements the
Homeserver interface.
=head2 server_name
$hs->server_name
This method should return the server_name for the server (ie, the 'domain' part
of any Matrix IDs it generates).
=head2 federation_host
This method should return the hostname where the homeserver exposes the
server-server API.
=head2 federation_port
$hs->federation_port
This method should return the port number where the homeserver exposes a
server-server API (over HTTPS). It may return undef if there is no known
federation port.
=head2 public_baseurl
$hs->public_baseurl
This method should returns the public base URL for the client-server API for
this server.
=cut
sub _init
{
my $self = shift;
my ( $args ) = @_;
$self->{$_} = delete $args->{$_} for qw(
output hs_dir hs_index bind_host
);
my $hs_dir = $self->{hs_dir};
-d $hs_dir or make_path $hs_dir;
$self->SUPER::_init( $args );
}
sub configure
{
my $self = shift;
my %params = @_;
exists $params{$_} and $self->{$_} = delete $params{$_} for qw(
recaptcha_config cas_config smtp_server_config
app_service_config_files
);
$self->SUPER::configure( %params );
}
=head1 UTILITY METHODS
=cut
sub write_file
{
my $self = shift;
my ( $relpath, $content ) = @_;
my $hs_dir = $self->{hs_dir};
write_binary( my $abspath = "$hs_dir/$relpath", $content );
return $abspath;
}
sub write_yaml_file
{
my $self = shift;
my ( $relpath, $content ) = @_;
my $hs_dir = $self->{hs_dir};
# the docs on this aren't great, but empirically this is needed to make
# YAML::XS::DumpFile understand that JSON::true values should be dumped as
# `true`.
local $YAML::XS::Boolean = "JSON::PP";
YAML::XS::DumpFile( my $abspath = "$hs_dir/$relpath", $content );
return $abspath;
}
sub write_json_file
{
my $self = shift;
my ( $relpath, $content ) = @_;
return $self->write_file( $relpath, JSON::encode_json( $content ) );
}
sub configure_logger
{
my $self = shift;
my ( $log_type ) = @_;
my $hs_dir = $self->{hs_dir};
my $log_config_file = $self->write_yaml_file("log.config.$log_type" => {
version => 1,
formatters => {
precise => {
format => "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s"
}
},
filters => {
context => {
"()" => "synapse.logging.context.LoggingContextFilter",
request => ""
}
},
handlers => {
file => {
class => "logging.FileHandler",
formatter => "precise",
filename => "$hs_dir/$log_type.log",
filters => ["context"],
encoding => "utf8"
}
},
loggers => {
synapse => {
level => "INFO"
}
},
root => {
level => "INFO",
handlers => ["file"]
}
});
return $log_config_file;
}
=head2 _get_dbconfig
%db_config = $self->_get_dbconfig( %defaults )
This method loads the database config from C<database.yaml>, or creates that
file according to the given defaults.
It then passes the loaded config to C<_check_db_config> for
sanity-checking. That method may be overridden by subclasses, and should C<die>
if there is a problem with the config.
Finally, it calls the relevant clear_db method to clear out the configured
database.
It returns the config hash.
=cut
# This is now only used for Dendrite, as synapse uses `_get_dbconfigs`. It
# probably makes more sense to have a dendrite specific handling, rather than
# using synapse config format and then parsing and converting it into dendrite
# config.
sub _get_dbconfig
{
my $self = shift;
my ( %defaults ) = @_;
my $hs_dir = $self->{hs_dir};
my $db_config_path = "database.yaml";
my $db_config_abs_path = "$hs_dir/${db_config_path}";
my ( %db_config );
if( -f $db_config_abs_path ) {
%db_config = %{ YAML::XS::LoadFile( $db_config_abs_path ) };
# backwards-compatibility hacks
my $db_name = delete $db_config{name};
if( defined $db_name ) {
if( $db_name eq 'psycopg2' ) {
$db_config{type} = 'pg';
}
elsif( $db_name eq 'sqlite3' ) {
$db_config{type} = 'sqlite';
}
else {
die "Unrecognised DB name '$db_name' in $db_config_abs_path";
}
}
}
else {
$self->write_yaml_file( $db_config_path, \%defaults );
%db_config = %defaults;
}
eval {
$self->_check_db_config( %db_config );
1;
} or die "Error loading db config $db_config_abs_path: $@";
my $db_type = $db_config{type};
my $clear_meth = "_clear_db_${db_type}";
$self->$clear_meth( %{ $db_config{args} } );
return %db_config;
}
=head2 _get_dbconfigs
%db_configs = $self->_get_dbconfigs( %defaults )
This method loads the database configs from either C<databases.yaml> or
C<database.yaml>, using the default if it doesn't exist.
It then passes the loaded configs to C<_check_db_config> for
sanity-checking. That method may be overridden by subclasses, and should C<die>
if there is a problem with the config.
Finally, it calls the relevant clear_db method on each database to clear out
the configured databases.
It returns the configs as a hash of database name to config hashref.
=cut
sub _get_dbconfigs
{
my $self = shift;
my ( %defaults ) = @_;
my $hs_dir = $self->{hs_dir};
# Try and load the configs from the various locations.
my ( %db_configs );
if ( -f "$hs_dir/databases.yaml") {
$self->{output}->diag( "Using DB config from $hs_dir/databases.yaml" );
%db_configs = %{ YAML::XS::LoadFile( "$hs_dir/databases.yaml" ) };
}
elsif( -f "$hs_dir/database.yaml" ) {
$self->{output}->diag( "Using DB config from $hs_dir/database.yaml" );
my %db_config = %{ YAML::XS::LoadFile( "$hs_dir/database.yaml" ) };
$db_configs{"main"} = \%db_config;
}
else {
$self->{output}->diag( "Using default DB config and writing to $hs_dir/database.yaml" );
$self->write_yaml_file( "database.yaml", \%defaults );
$db_configs{"main"} = \%defaults;
}
# Go through each database and check the config and clear the database.
foreach my $db ( keys %db_configs ) {
my $db_config = $db_configs{$db};
# backwards-compatibility hacks
my $db_name = delete $db_config->{name};
if( defined $db_name ) {
if( $db_name eq 'psycopg2' ) {
$db_config->{type} = 'pg';
}
elsif( $db_name eq 'sqlite3' ) {
$db_config->{type} = 'sqlite';
}
else {
die "Unrecognised DB name '$db_name'";
}
}
eval {
$self->_check_db_config( %{ $db_config } );
1;
} or die "Error loading db config: $@";
my $db_type = $db_config->{type};
my $clear_meth = "_clear_db_${db_type}";
$self->$clear_meth( %{ $db_config->{args} } );
}
return %db_configs;
}
sub _check_db_config
{
my $self = shift;
my ( %db_config ) = @_;
my $db_type = $db_config{type};
if( $db_type eq 'pg' ) {
foreach (qw( database )) {
if( !$db_config{args}->{$_} ) {
die "Missing required database argument $_";
}
}
}
elsif( $db_type eq 'sqlite' ) {
foreach (qw( database )) {
if( !$db_config{args}->{$_} ) {
die "Missing required database argument $_";
}
}
}
else {
die "Unrecognised DB type '$db_type'";
}
}
sub _clear_db_sqlite
{
my $self = shift;
my %args = @_;
my $db = $args{database};
$self->{output}->diag( "Clearing SQLite database at $db" );
unlink $db if -f $db;
}
sub _clear_db_pg
{
my $self = shift;
my %args = @_;
my $host = $args{host} // '';
$self->{output}->diag( "Clearing Pg database $args{database} on '$host'" );
require DBI;
require DBD::Pg;
# If there is a DB called sytest_template use that as the template for the
# sytest databases. Otherwise initialise the DB from scratch (which can take
# a fair few seconds)
my $dbh = DBI->connect( "dbi:Pg:dbname=sytest_template;host=$host", $args{user}, $args{password} );
if ( $dbh ) {
$dbh->do( "DROP DATABASE $args{database}" ); # we don't mind if this dies
$dbh->do( "CREATE DATABASE $args{database} WITH TEMPLATE sytest_template" ) or
die $dbh->errstr;
}
else {
$dbh = DBI->connect( "dbi:Pg:dbname=$args{database};host=$host", $args{user}, $args{password} )
or die DBI->errstr;
foreach my $row ( @{ $dbh->selectall_arrayref( "SELECT tablename FROM pg_tables WHERE schemaname = 'public'" ) } ) {
my ( $tablename ) = @$row;
$dbh->do( "DROP TABLE $tablename CASCADE" ) or
die $dbh->errstr;
}
foreach my $row ( @{ $dbh->selectall_arrayref(
"SELECT c.relname FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace WHERE relkind='S' AND n.nspname='public'"
) } ) {
my ( $seqname ) = @$row;
$dbh->do( "DROP SEQUENCE $seqname" ) or
die $dbh->errstr;
}
}
}
sub await_connectable
{
my $self = shift;
my ( $host, $port ) = @_;
my $loop = $self->loop;
my $attempts = 25;
my $delay = 0.05;
my $output = $self->{output};
$output->diag( "Connecting to server $port" );
my $fut = repeat {
$loop->connect(
host => $host,
service => $port,
socktype => "stream",
)->then_done(1)
->else( sub {
if( !$attempts ) {
return Future->fail( "Failed to connect to $port" )
}
$attempts--;
$delay *= 1.3;
main::delay( $delay )
->then_done(0);
})
} while => sub { !$_[0]->failure and !$_[0]->get };
$fut->on_done( sub {
$output->diag( "Connected to server $port" );
});
return $fut;
}
=head2 _run_command
$future = $self->_run_command( %params )
This method runs a specified command and returns a future which will complete
when the process exits.
Any output from the command is written as diagnostics.
The parameters are passed to C<IO::Async::Process::new>.
=cut
sub _run_command
{
my $self = shift;
my %params = @_;
my $cmd = $params{command}[0];
my $output = $self->{output};
my $diag = sub {
$output->diag( "\e[1;35m[$cmd]\e[m: $_[0]" );
};
my $on_output = sub {
my ( $stream, $buffref, $eof) = @_;
# write each complete line in the buffer
while ( $$buffref =~ s/^(.*)\n// ) {
&$diag($1);
}
# if this is the end of the output, and there is
# anything left in the buffer, print out the remainder.
if( $eof && $$buffref ) {
&$diag($$buffref);
}
return 0;
};
my $fut = $self->loop->new_future;
my $proc = IO::Async::Process->new(
%params,
stdout => { on_read => $on_output },
stderr => { on_read => $on_output },
on_finish => sub {
my ( undef, $exitcode ) = @_;
if( $exitcode == 0 ) {
$fut->done();
return;
}
my $failure;
if( WIFEXITED($exitcode) ) {
$failure = "$cmd exited " . WEXITSTATUS( $exitcode );
} else {
$failure = "$cmd failed $exitcode";
}
$fut->fail( $failure );
},
);
$self->loop->add($proc);
return $fut;
}
1;