-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.php
1471 lines (1298 loc) · 44.2 KB
/
module.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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* +------------------------------------------------------------+
* | apnscp |
* +------------------------------------------------------------+
* | Copyright (c) Apis Networks |
* +------------------------------------------------------------+
* | Licensed under Artistic License 2.0 |
* +------------------------------------------------------------+
* | Author: Matt Saladna (msaladna@apisnetworks.com) |
* +------------------------------------------------------------+
*/
use Module\Support\Webapps\App\Type\Discourse\Launcher;
use Module\Support\Webapps\Passenger;
use Module\Support\Webapps\PathManager;
use Module\Support\Webapps\Traits\PublicRelocatable;
use Module\Support\Webapps\VersionFetcher\Github;
use Opcenter\Net\Port;
/**
* Discourse management
*
* Forum software
*
* @package core
*/
class Discourse_Module extends \Module\Support\Webapps
{
use PublicRelocatable {
getAppRoot as getAppRootReal;
}
// via config/application.rb
const MINIMUM_INTERPRETERS = [
'0' => '2.4.2',
'2.2.0.beta5' => '2.5.2',
'2.5.0' => '2.6.5',
'2.6.0' => '2.7.2',
'3.0.0' => '3.1.3',
'3.1.0' => '3.2.0'
];
// via https://github.com/discourse/discourse_docker/blob/master/image/base/Dockerfile#L29
// "debsource" install
const NODE_VERSIONS = [
'0' => '8',
'2.4' => '10',
'2.5' => '14',
'2.6' => '15',
'2.8' => '16',
'3.2' => '18'
];
const APP_NAME = 'Discourse';
const DEFAULT_VERSION_LOCK = 'minor';
const DISCOURSE_REPO = 'https://github.com/discourse/discourse.git';
public function __construct()
{
parent::__construct();
$this->exportedFunctions['restart'] = PRIVILEGE_SITE | PRIVILEGE_USER;
}
public function plugin_status(string $hostname, string $path = '', string $plugin = null)
{
return error('not supported');
}
public function uninstall_plugin(string $hostname, string $path, string $plugin, bool $force = false): bool
{
return error('not supported');
}
public function disable_all_plugins(string $hostname, string $path = ''): bool
{
return error('not supported');
}
/**
* Get next Discourse version
*
* @param string $version
* @param string $maximalbranch
* @return null|string
*/
public function next_version(string $version, string $maximalbranch = '99999999.99999999.99999999'): ?string
{
return parent::next_version($version, $maximalbranch);
}
/**
* @inheritDoc
*/
public function reconfigure(string $hostname, string $path, $param, $value = null): bool
{
return parent::reconfigure($hostname, $path, $param, $value); // TODO: Change the autogenerated stub
}
/**
* @inheritDoc
*/
public function reconfigurables(string $hostname, string $path = ''): array
{
return parent::reconfigurables($hostname, $path);
}
/**
* @param string $hostname
* @param string $path
* @param string|array $fields
* @return mixed
*/
public function get_configuration(string $hostname, string $path, $fields): array
{
if (!IS_CLI) {
return $this->query('discourse_get_configuration', $hostname, $path, $fields);
}
$config = $this->getAppRoot($hostname, $path) . '/config/discourse.conf';
$stat = $this->file_stat($config);
if (!$stat['can_read']) {
error("Path %(path)s unreadable", ['path' => $config]);
return [];
}
$map = \Opcenter\Map::read($this->domain_fs_path($config), 'inifile')->section(null);
$values = [];
foreach ((array)$fields as $k) {
$values[$k] = $map->fetch($k);
}
if (\count($values) === 1) {
return array_pop($values);
}
return $values;
}
/**
* Get app root for Discourse
*
* @param string $hostname
* @param string $path
* @return null|string
*/
protected function getAppRoot(string $hostname, string $path = ''): ?string
{
return $this->getAppRootReal($hostname, $path);
}
/**
* Install Discourse into a pre-existing location
*
* @TODO disable cgroup OOM killer on 1 GB sites?
*
* @param string $hostname domain or subdomain to install Laravel
* @param string $path optional path under hostname
* @param array $opts additional install options
* @return bool
*/
public function install(string $hostname, string $path = '', array $opts = array()): bool
{
if (posix_geteuid() && !IS_CLI) {
return $this->query('discourse_install', $hostname, $path, $opts);
}
if (!$this->pgsql_enabled()) {
return error('%(what)s must be enabled to install %(app)s', ['what' => 'PostgreSQL', 'app' => static::APP_NAME]);
}
if (!SSH_USER_DAEMONS) {
return error('[ssh] => user_daemons must be set to true in config.ini');
}
$available = null;
if (!$this->hasMemoryAllowance(1536, $available)) {
return error("Discourse requires at least 1.5 GB memory, `%s' MB provided for account", $available);
}
if (!$this->hasStorageAllowance(2048, $available)) {
return error('Discourse requires ~2 GB storage. Only %.2f MB free.', $available);
}
if ($this->getServiceValue('cgroup', 'enabled') && ($limit = $this->getServiceValue('cgroup',
'proclimit') ?: 100) < 100) {
return error("Resource limits enforced. proclimit `%d' is below minimum value 100. Change via cgroup,proclimit",
$limit);
}
if (!$this->crontab_permitted()) {
return error('%(app)s requires %(service)s service to be enabled', [
'app' => self::APP_NAME, 'service' => 'crontab'
]);
}
if (!$this->crontab_enabled() && !$this->crontab_start()) {
return error('Failed to enable task scheduling');
}
if (!empty($opts['maxmind']) && !ctype_alnum($opts['maxmind'])) {
return error('A MaxMind GeoLite2 key is required.');
}
if (!isset($opts['mode'])) {
$opts['mode'] = 'apache';
}
if ($opts['mode'] !== 'standalone' && $opts['mode'] !== 'nginx' && $opts['mode'] !== 'apache') {
return error("Unknown Discourse mode `%s'", $opts['mode']);
}
// assume all Discourse installs will be located in a parent directory
// once installed, relink the domain/subdomain to $docroot + /public
// also block installing under a path, because this would require either relocating
// Discourse outside any document root, e.g. /var/www/<hostname>-<path>-discourse and making
// a symlink, which fails once the parent document root moves (must use relative symlinks)
// and clutters up wherever they get located... no sound solution
if ($path) {
return error('Discourse may only be installed directly on a subdomain or domain without a child path, e.g. https://discourse.domain.com but not https://domain.com/discourse');
}
if (!($docroot = $this->getDocumentRoot($hostname, $path))) {
return error("failed to normalize path for `%s'", $hostname);
}
if (!$this->parseInstallOptions($opts, $hostname, $path)) {
return false;
}
$rubyVersion = \Opcenter\Versioning::satisfy($opts['version'], self::MINIMUM_INTERPRETERS);
if (!($rubyVersion = $this->validateRuby($rubyVersion, $opts['user'] ?? null))) {
return false;
}
$args['version'] = $opts['version'];
$db = \Module\Support\Webapps\DatabaseGenerator::pgsql($this->getAuthContext(), $hostname);
$db->connectionLimit = max($db->connectionLimit, 15);
if (!$db->create()) {
return false;
}
$context = null;
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($docroot, $context);
$oldex = \Error_Reporter::exception_upgrade();
try {
$wrapper->git_clone(static::DISCOURSE_REPO, $docroot,
[
'recursive' => null,
'depth' => 1,
'branch' => 'v' . $opts['version']
]);
$this->ruby_make_default($rubyVersion, $docroot);
$bundler = 'bundler:"< 2"';
if (version_compare($args['version'], '2.3.8', '>=')) {
$bundler = 'bundler:"~> 2.2"';
if (version_compare($args['version'], '3.1.0', '<')) {
$bundler = 'bundler:"<= 2.4.22"';
}
}
$wrapper->ruby_do($rubyVersion, $docroot, 'gem install -E --no-document passenger ' . $bundler);
$bundleFlags = '--deployment --without test development';
if (version_compare($args['version'], '2.5.0', '>=')) {
$wrapper->ruby_do($rubyVersion, $docroot, 'bundle config set deployment true');
$wrapper->ruby_do($rubyVersion, $docroot, 'bundle config set without "test development"');
$bundleFlags = '';
}
if (version_compare($args['version'], '2.8.10', '>=') && version_compare($rubyVersion, '3.1.3', '<')) {
$wrapper->ruby_do($rubyVersion, $docroot, 'gem update --system 3.2.28 --no-doc');
}
$wrapper->ruby_do('', $docroot, 'bundle install ' . $bundleFlags . ' -j' . max(4, (int)NPROC + 1));
# renice requires CAP_SYS_NICE, which Discourse doesn't catch
$wrapper->file_put_file_contents($wrapper->user_get_home() . '/.rbenv-usergems/' . $rubyVersion . '/bin/renice',
"#!/bin/sh\nexec /bin/true");
$wrapper->file_chmod($wrapper->user_get_home() . '/.rbenv-usergems/' . $rubyVersion . '/bin/renice', 755);
$this->applyPatches($wrapper, $docroot, $args['version']);
$extensions = ['pg_trgm', 'hstore'];
if (version_compare($args['version'], '3.0', '>=')) {
$extensions[] = 'unaccent';
}
foreach ($extensions as $extension) {
$this->pgsql_add_extension($db->database, $extension);
}
if (!$wrapper->crontab_user_permitted($opts['user'] ?? $this->username)) {
if (!$this->crontab_permit_user($opts['user'] ?? $this->username)) {
return error("failed to enable task scheduling for `%s'", $opts['user'] ?? $this->username);
}
warn("Task scheduling enabled for user `%s'", $opts['user'] ?? $this->username);
}
} catch (\apnscpException $e) {
if (array_get($opts, 'hold')) {
return false;
}
info('removing temporary files');
$this->file_delete($docroot, true);
$db->rollback();
return error('failed to install Discourse %s: %s', $args['version'], $e->getMessage());
} finally {
\Error_Reporter::exception_upgrade($oldex);
}
$opts['url'] = rtrim($hostname . '/' . $path, '/');
if (null === ($docroot = $this->remapPublic($hostname, $path))) {
// it's more reasonable to fail at this stage, but let's try to complete
return error("Failed to remap Discourse to public/, manually remap from `%s' - Discourse setup is incomplete!",
$docroot);
}
$docroot = $this->getDocumentRoot($hostname, $path);
$approot = $this->getAppRoot($hostname, $path);
$config = $approot . '/config/discourse.conf';
$wrapper->file_copy($approot . '/config/discourse_defaults.conf', $config);
$configurables = [
'db_name' => $db->database,
'db_username' => $db->username,
'db_password' => $db->password,
'hostname' => $hostname,
'db_host' => $db->hostname,
'developer_emails' => $opts['email'],
'load_mini_profiler' => false
];
if (!empty($opts['maxmind'])) {
$configurables['maxmind_license_key'] = $opts['maxmind'];
}
$this->set_configuration($hostname, $path, $configurables);
if (version_compare($args['version'], '3.0.0', '>=')) {
$this->createMailUser($hostname, $path);
}
$redispass = \Opcenter\Auth\Password::generate(32);
if ($wrapper->redis_exists($this->domain)) {
warn("Existing Redis profile named `%s' found - removing", $this->domain);
$wrapper->redis_delete($this->domain);
}
$wrapper->redis_create($this->domain, ['requirepass' => $redispass]);
$redisconfig = $wrapper->redis_config($this->domain);
$vars = [
'redis_port' => $redisconfig['port'],
'redis_host' => '127.0.0.1',
'redis_password' => $redisconfig['requirepass'],
'db_pool' => 7
];
$this->set_configuration($hostname, $path, $vars);
/**
* Sidekiq + DB migration + asset generation
*/
$exold = \Error_Reporter::exception_upgrade();
try {
$nodeVersion = $this->validateNode((string)$opts['version'], $wrapper);
$this->node_make_default($nodeVersion, $approot);
$this->assetsCompile($hostname, $path, 'production');
$this->migrate($approot);
if (version_compare($opts['version'], '2.4.0', '<')) {
$this->launchSidekiq($approot, 'production');
$passenger = Passenger::instantiateContexted($context, [$approot, 'ruby']);
$passenger->createLayout();
$passenger->setEngine('standalone');
// avoid excessive mutex locking in Passenger
$passenger->setProcessConcurrency(0);
$passenger->setMaxPoolSize(3);
$passenger->setMinInstances(3);
$passenger->setEnvironment([
'RUBY_GLOBAL_METHOD_CACHE_SIZE' => 131072,
'LD_PRELOAD' => '/usr/lib64/libjemalloc.so.1',
'RUBY_GC_HEAP_GROWTH_MAX_SLOTS' => 40000,
'RUBY_GC_HEAP_INIT_SLOTS' => 400000,
'RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR' => 1.5
]);
$this->file_put_file_contents($approot . '/Passengerfile.json',
$passenger->getExecutableConfiguration());
$passenger->start();
} else {
$handler = Launcher::instantiateContexted($context,
[$approot]);
$handler->create(Port::firstFree($this->getAuthContext()));
}
} catch (\apnscpException $e) {
dlog($e->getTraceAsString());
return error('Error encountered during housekeeping. Discourse may be incomplete: %s',
$e->getMessage());
} finally {
\Error_Reporter::exception_upgrade($exold);
}
if (version_compare($opts['version'], '2.4.0', '>=')) {
$launcher = Launcher::instantiateContexted($context, [$approot]);
$launcher->start();
$command = $launcher->getCommand();
$rules = 'RewriteEngine On' . "\n" .
'RewriteCond %{REQUEST_FILENAME} !-f' . "\n" .
'RewriteRule ^(.*)$ http://localhost:' . $launcher->getPort() . '/$1 [P,L,QSA]' . "\n";
} else {
$command = $passenger->getExecutable();
$this->pman_run($command);
$rules = $passenger->getDirectives();
}
if (!isset($passenger) || $passenger->getEngine() !== 'apache') {
$args = [
'@reboot',
null,
null,
null,
null,
$command
];
if (!($wrapper->crontab_exists(...$args) || $wrapper->crontab_add_job(...$args))) {
warn('Failed to create job to start Discourse on boot. Command: %s', $command);
}
}
if (!empty($opts['ssl'])) {
$rules = 'RequestHeader set X-Forwarded-Proto expr=%{REQUEST_SCHEME}' . "\n" .
$rules;
}
if (!$this->file_put_file_contents($approot . '/public/.htaccess',
'# Enable caching' . "\n" .
'UnsetEnv no-cache' . "\n" .
// prevents page not found on vanilla installs
// defaults to index.html otherwise
'DirectoryIndex disabled' . "\n" .
$rules
)) {
return error('failed to create .htaccess control - Discourse is not properly setup');
}
$this->notifyInstalled($hostname, $path, $opts);
return info('%(app)s installed - confirmation email with login info sent to %(email)s',
['app' => static::APP_NAME, 'email' => $opts['email']]);
}
/**
* Create unprivileged mail relay user
*
* Required for v3.0.0, SMTP provider changed to net-smtp
*
* @param string $hostname
* @param string $path
* @return void
*/
private function createMailUser(string $hostname, string $path = ''): void
{
if (version_compare($this->get_version($hostname, $path), '3.0.0', '<')) {
return;
}
if (!$this->email_enabled()) {
warn("Mail disabled on account. Manual SMTP configuration required to config/discourse.conf");
return;
}
$cfg = $this->get_configuration($hostname, $path, ['smtp_user_name', 'smtp_address']);
if (array_get($cfg, 'smtp_address') && $cfg['smtp_user_name']) {
return;
}
$user = 'discourse-' . \Opcenter\Auth\Password::generate(8, 'a-z');
$password = \Opcenter\Auth\Password::generate(16);
if (!$this->user_add($user, $password, 'Discourse email user - ' . $hostname, 0, [
'smtp' => true,
'cp' => false,
'ssh' => false,
'ftp' => false,
'imap' => false
]))
{
warn("Failed to create SMTP user for Discourse. Manual configuration of SMTP required");
return;
}
$this->set_configuration($hostname, $path, [
'smtp_user_name' => "$user@$hostname",
'smtp_password' => $password,
'smtp_address' => 'localhost',
'smtp_port' => 587,
'smtp_enable_start_tls' => 'false',
]);
}
private function deleteMailUser(string $hostname, string $path = ''): void
{
$cfg = $this->get_configuration($hostname, $path, ['smtp_user_name', 'smtp_address']);
if (array_get($cfg, 'smtp_address') !== 'localhost' || !str_contains($cfg['smtp_user_name'], "@$hostname")) {
return;
}
$user = strtok($cfg['smtp_user_name'], '@');
if (!($pwd = $this->user_getpwnam($user)) || !str_starts_with($pwd['gecos'], "Discourse email user")) {
return;
}
$this->user_delete($user, true);
}
/**
* Additional version checks
*
* @param array $options
* @return bool
*/
protected function checkVersion(array &$options): bool
{
if (!parent::checkVersion($options)) {
return false;
}
$version = array_get($options, 'version');
// Requires Redis 4.0 by Sidekiq 6 compat
$redisVersion = $this->redis_version();
foreach(['2.4.0' => '4.0.0', '3.0.0' => '6.2.0'] as $discourseVersion => $redisReq) {
if (version_compare($version, $discourseVersion, '<')) {
return true;
}
if (version_compare($redisVersion, $redisReq, '<')) {
return error('%(app)s %(version)s+ requires %(pkgname)s %(pkgver)s+. ' .
'%(pkgname)s %(pkginstver)s installed in FST', [
'app' => self::APP_NAME,
'version' => $version,
'pkgname' => 'Redis',
'pkgver' => $redisReq,
'pkginstver' => $redisVersion
]);
}
}
return true;
}
/**
* Verify Node LTS is installed
*
* @param string|null $version optional version to compare against
* @param string|null $user
* @return string|null
*/
protected function validateRuby(string $version = 'lts', string $user = null): ?string
{
debug("Validating Ruby %s installed", $version);
if ($user) {
$afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
}
$wrapper = $afi ?? $this;
// @TODO accept newer Rubies if present
if (!$exists = $wrapper->ruby_installed($version, '>=')) {
if (!$version = $wrapper->ruby_install(\Opcenter\Versioning::asMinor($version))) {
error('failed to install Ruby %s', $version);
return null;
}
} else {
debug("Ruby %(found)s satisfies request %(wanted)s", ['found' => $exists, 'wanted' => $version]);
// update version with satisficier
$version = $exists;
}
$ret = $wrapper->ruby_do($version, null, 'gem install --no-document -E passenger');
if (!$ret['success']) {
error('failed to install Passenger gem: %s', $ret['stderr'] ?? 'UNKNOWN ERROR');
return null;
}
$home = $this->user_get_home($user);
$stat = $this->file_stat($home);
if (!$stat || !$this->file_chmod($home, decoct($stat['permissions']) | 0001)) {
error("failed to query user home directory `%s' for user `%s'", $home, $user);
return null;
}
return $version;
}
/**
* Get installed version
*
* @param string $hostname
* @param string $path
* @return string version number
*/
public function get_version(string $hostname, string $path = ''): ?string
{
if (!$this->valid($hostname, $path)) {
return null;
}
$approot = $this->getAppRoot($hostname, $path);
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($approot);
$ret = $wrapper->ruby_do(null, $approot,
'ruby -e \'require "./%(path)s" ; puts Discourse::VERSION::STRING;\'',
['path' => 'lib/version.rb']
);
return $ret['success'] ? trim($ret['output']) : null;
}
/**
* Location is a valid Discourse install
*
* @param string $hostname or $docroot
* @param string $path
* @return bool
*/
public function valid(string $hostname, string $path = ''): bool
{
if (0 === strncmp($hostname, '/', 1)) {
if (!($path = realpath($this->domain_fs_path($hostname)))) {
return false;
}
$approot = \dirname($path);
} else {
$approot = $this->getAppRoot($hostname, $path);
if (!$approot) {
return false;
}
$approot = $this->domain_fs_path($approot);
}
return file_exists($approot . '/lib/discourse.rb');
}
public function set_configuration(string $hostname, string $path, array $params = [])
{
if (!IS_CLI) {
return $this->query('discourse_set_configuration', $hostname, $path, $params);
}
$config = $this->getAppRoot($hostname, $path) . '/config/discourse.conf';
$stat = $this->file_stat($config);
if ($stat && !$stat['can_write']) {
return error("Path %(path)s unreadable", ['path' => $config]);
}
$ini = \Opcenter\Map::load($this->domain_fs_path($config), 'wd', 'inifile')->section(null);
clearstatcache(true, $this->domain_fs_path($config));
if (!str_starts_with(realpath($this->domain_fs_path($config)), $this->domain_fs_path('/'))) {
$ini->close();
fatal("Unsafe path");
}
foreach ($params as $k => $v) {
$ini[$k] = $v;
}
return $ini->save();
}
/**
* Apply Discourse patches
*
* @param apnscpFunctionInterceptor $wrapper
* @param string $approot
* @param string $version
* @throws ReflectionException
*/
private function applyPatches(\apnscpFunctionInterceptor $wrapper, string $approot, string $version): void
{
if (version_compare('2.5.0', $version, '>')) {
return;
}
$patch = '/0001-Rack-Lint-InputWrapper-lacks-size-method.patch';
if (version_compare('3.0.0', $version, '<=')) {
$patch = '/0001-Rack-Lint-InputWrapper-lacks-size-method-3.0.patch';
} else if (version_compare('2.8.0', $version, '<=')) {
$patch = '/0001-Rack-Lint-InputWrapper-lacks-size-method-2.8.patch';
}
$path = PathManager::storehouse('discourse') . $patch;
$wrapper->file_put_file_contents($approot . '/0001.patch', file_get_contents($path));
$ret = $wrapper->pman_run('cd %s && (git apply 0001.patch ; rm -f 0001.patch)', [$approot]);
if (!$ret['success']) {
warn("Failed to apply Rack input patch: %s", $ret['stderr']);
}
}
/**
* Migrate Discourse database
*
* @param string $approot
* @param string $appenv optional app environment to source DB config
* @return bool
*/
private function migrate(string $approot, string $appenv = 'production'): bool
{
return $this->rake($approot, 'db:migrate', ['RAILS_ENV' => $appenv]);
}
private function rake(string $approot, string $task, array $env): bool
{
// https://github.com/nodejs/node/issues/25933
// as is soft, which allows raising to unlimited
// note: can fail if .bashrc lacks /etc/bashrc source
$ret = $this->_exec(
$approot,
"ulimit -v unlimited ; nvm exec /bin/bash -ic 'rbenv exec bundle exec rake -j" . min(4, (int)NPROC + 1) . " $task'",
[
[],
$env
],
);
return $ret['success'] ?: error("failed Rake task `%s': %s", $task,
coalesce($ret['stderr'], $ret['stdout']));
}
private function _exec(?string $path, $cmd, array $args = array())
{
// client may override tz, propagate to bin
if (!is_array($args)) {
$args = func_get_args();
array_shift($args);
}
// PHP has no recursive union. array_merge() with numeric keys appends
$baseArgs = [
0 => [],
1 => ['RAILS_ENV' => 'production'],
2 => []
];
$args = array_key_map(static function ($k, $v) use ($args) {
return ($args[$k] ?? []) + $v;
}, $baseArgs);
$user = $this->username;
if ($path) {
$cmd = 'cd %(path)s && /bin/bash -ic -- ' . escapeshellarg($cmd);
$args[0]['path'] = $path;
$user = $this->file_stat($path)['owner'] ?? $this->username;
}
$args[2]['user'] = $user;
$ret = $this->pman_run($cmd, ...$args);
if (!strncmp(coalesce($ret['stderr'], $ret['stdout']), 'Error:', strlen('Error:'))) {
// move stdout to stderr on error for consistency
$ret['success'] = false;
if (!$ret['stderr']) {
$ret['stderr'] = $ret['stdout'];
}
}
return $ret;
}
/**
* Launch Sidekiq process
*
* @param string $approot
* @param string $mode
* @return bool
*/
protected function launchSidekiq(string $approot, string $mode = 'production'): bool
{
if ($this->sidekiqRunning($approot)) {
return true;
}
$job = [
'@reboot',
null,
null,
null,
null,
'/bin/bash -ic ' .
escapeshellarg($this->getSidekiqJob($approot, 'production'))
];
if (!$this->crontab_exists(...$job)) {
$this->crontab_add_job(...$job);
}
$ret = $this->_exec(
$approot,
$this->getSidekiqCommand($approot),
[
[
'approot' => $approot
],
[
'RAILS_ENV' => $mode
]
]
);
return $ret['success'] ?: error('Failed to launch Sidekiq, check log/sidekiq.log');
}
protected function sidekiqRunning(string $approot): ?int
{
$pidfile = $approot . '/tmp/sidekiq.pid';
if (!$this->file_exists($pidfile)) {
return null;
}
$pid = (int)$this->file_get_file_contents($pidfile);
return \Opcenter\Process::pidMatches($pid, 'ruby') ? $pid : null;
}
/**
* Get Sidekiq cronjob
*
* @param string $approot
* @param string $env
* @return string
*/
private function getSidekiqJob(string $approot, $env = 'production')
{
return 'cd ' . $approot . ' && env RAILS_ENV=production ' . $this->getSidekiqCommand($approot);
}
/**
* Get Sidekiq command
*
* @param string $approot
* @return string
*/
private function getSidekiqCommand(string $approot)
{
return 'bundle exec sidekiq -L log/sidekiq.log -P tmp/sidekiq.pid -q critical -q low -q default -d -c5';
}
/**
* Compile assets
*
* @param string $hostname
* @param string $path
* @param string $appenv
*
* @return bool
*/
private function assetsCompile(string $hostname, string $path = '', string $appenv = 'production'): bool
{
$approot = $this->getAppRoot($hostname, $path);
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($approot);
$discourseVersion = $this->get_version($hostname, $path);
if (null === $discourseVersion) {
return error("Failed to discover Discourse version in `%s'/`%s'", $hostname, $path);
}
$nodeVersion = $this->validateNode($discourseVersion, $wrapper);
$wrapper->node_make_default($nodeVersion, $approot);
// update deps
$packages = ['yarn'];
if (version_compare($discourseVersion, '2.6', '>=')) {
$packages = array_merge($packages, ['terser', 'uglify-js']);
} else {
$packages = array_merge($packages, ['uglify-js@2']);
}
$ret = $wrapper->node_do($nodeVersion, null, 'npm install --no-save -g ' . implode(' ', $packages));
if (!$ret['success']) {
return error('Failed to install preliminary packages: %s', $ret['error']);
}
$ret = $this->_exec($approot, 'nvm exec ' . $nodeVersion . ' yarn install');
if (!$ret['success']) {
return error('Failed to install packages: %s', $ret['error']);
}
$this->fixupMaxMind($wrapper, $approot);
$env = [
'RAILS_ENV' => $appenv,
'NODE_VERSION' => $nodeVersion
];
return $this->rake($approot, 'assets:clean', $env) && $this->rake($approot, 'assets:precompile', $env);
}
/**
* Verify specific Node major installed
*
* @param string $version Discourse version
* @param apnscpFunctionInterceptor $wrapper
* @return string required Node version
*/
private function validateNode(string $version, \apnscpFunctionInterceptor $wrapper): string
{
$nodeVersion = \Opcenter\Versioning::satisfy($version, self::NODE_VERSIONS);
debug("Validating Node %s installed", $nodeVersion);
if (!$wrapper->node_installed($nodeVersion)) {
$wrapper->node_install($nodeVersion);
}
return $nodeVersion;
}
/**
* Replace MaxMind configuration
*
* CCPA places MaxMind behind a portal. Only available in master
*
* @param apnscpFunctionInterceptor $wrapper
* @param string $approot
* @return bool
*/
private function fixupMaxMind(apnscpFunctionInterceptor $wrapper, string $approot): bool
{
$path = "${approot}/lib/discourse_ip_info.rb";
$template = file_get_contents(resource_path('storehouse/discourse/discourse_ip_info.rb'));
return $wrapper->file_put_file_contents($path, $template);
}
public function build()
{
if (!is_debug()) {
return true;
}
$approot = $this->getAppRoot($this->domain, '');
$docroot = $this->getDocumentRoot($this->domain, '');
$context = null;
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($docroot, $context);
$passenger = Passenger::instantiateContexted($context, [$approot, 'ruby']);
$passenger->createLayout();
$passenger->setEngine('standalone');
$command = $passenger->getExecutableConfiguration();
//
echo $command, "\n";
dd($passenger->getExecutable(), $passenger->getDirectives());
}
public function restart(string $hostname, string $path = ''): bool
{
if (!$approot = $this->getAppRoot($hostname, $path)) {
return false;
}
$user = $this->getDocrootUser($approot);
return Passenger::instantiateContexted(\Auth::context($user, $this->site),
[$approot, 'ruby'])->restart();
}
/**
* Install and activate plugin
*
* @param string $hostname domain or subdomain of wp install
* @param string $path optional path component of wp install
* @param string $plugin plugin name
* @param string $version optional plugin version
* @return bool
*/
public function install_plugin(
string $hostname,
string $path,
string $plugin,
string $version = 'stable'
): bool {
return error('not supported');
}
/**
* Get configuration from a webapp
*
* @param $hostname
* @param string $path
* @param string $delete remove all files under docroot
* @return bool
*/
public function uninstall(string $hostname, string $path = '', string $delete = 'all'): bool
{
$approot = $this->getAppRoot($hostname, $path);
// @xxx f'ugly
$version = (string)$this->get_version($hostname, $path);
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($approot);
if ($wrapper !== $this->getApnscpFunctionInterceptor()) {
$wrapper->discourse_uninstall($hostname, $path, 'proc');
} else if ($delete !== 'proc') {
$this->getApnscpFunctionInterceptor()->discourse_uninstall($hostname, $path, 'proc');
}
if ($delete === 'proc') {
$this->kill($hostname, $path);
// will fail if run as Apache, ignore
if (version_compare($version, '2.4.0', '<')) {
$this->pman_run('cd %(approot)s && /bin/bash -ic %(cmd)s',
['approot' => $approot, 'cmd' => 'rbenv exec passenger stop']);
}
if ($this->redis_exists($hostname)) {
$this->redis_delete($hostname);
}
$this->killSidekiq($approot);
foreach ($this->crontab_filter_by_command($approot) as $job) {
$this->crontab_delete_job(
$job['minute'],
$job['hour'],
$job['day_of_month'],
$job['month'],
$job['day_of_week'],
$job['cmd']
);
}
return true;