1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 17:24:03 +00:00

[4.x] Add command to bring the tenants up and down from maintenance and remove deprecated exception (#761)

* Add bring up from maintenance function

* Add up and down tenant maintenance commands

* Rename commands signatures

* Update TenancyServiceProvider.php

* Complying to Laravel maintenance code and parameters

* Update MaintenanceModeTest.php

* Add maintenance mode via commands test

* Update CheckTenantForMaintenanceMode.php

* Update MaintenanceModeTest.php

* Cookie bypass only for > Laravel 8

* minor formatting change, trigger CI

* clean

* Update MaintenanceModeTest.php

* Add comments for using the 'tenants' option in runForMultiple

* improve code

* php-cs-fixer

* fix php cs fixer config

* improve test logic

* remove version check since v4 will be L9+

Co-authored-by: Samuel Štancl <samuel@archte.ch>
Co-authored-by: lukinovec <lukinovec@gmail.com>
Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
This commit is contained in:
Jori Stein 2022-09-29 09:59:14 -04:00 committed by GitHub
parent e009f6700c
commit 121370ea01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 161 additions and 25 deletions

View file

@ -10,6 +10,7 @@ $rules = [
'operators' => [ 'operators' => [
'=>' => null, '=>' => null,
'|' => 'no_space', '|' => 'no_space',
'&' => 'no_space',
] ]
], ],
'blank_line_after_namespace' => true, 'blank_line_after_namespace' => true,

View file

@ -63,6 +63,7 @@
"docker-m1": "ln -s docker-compose-m1.override.yml docker-compose.override.yml", "docker-m1": "ln -s docker-compose-m1.override.yml docker-compose.override.yml",
"coverage": "open coverage/phpunit/html/index.html", "coverage": "open coverage/phpunit/html/index.html",
"phpstan": "vendor/bin/phpstan", "phpstan": "vendor/bin/phpstan",
"cs": "php-cs-fixer fix --config=.php-cs-fixer.php",
"test": "PHP_VERSION=8.1 ./test --no-coverage", "test": "PHP_VERSION=8.1 ./test --no-coverage",
"test-full": "PHP_VERSION=8.1 ./test" "test-full": "PHP_VERSION=8.1 ./test"
}, },

52
src/Commands/Down.php Normal file
View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Commands;
use Illuminate\Foundation\Console\DownCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;
class Down extends DownCommand
{
use HasATenantsOption;
protected $signature = 'tenants:down
{--redirect= : The path that users should be redirected to}
{--retry= : The number of seconds after which the request may be retried}
{--refresh= : The number of seconds after which the browser may refresh}
{--secret= : The secret phrase that may be used to bypass maintenance mode}
{--status=503 : The status code that should be used when returning the maintenance mode response}';
protected $description = 'Put tenants into maintenance mode.';
public function handle(): void
{
// The base down command is heavily used. Instead of saving the data inside a file,
// the data is stored the tenant database, which means some Laravel features
// are not available with tenants.
$payload = $this->getDownDatabasePayload();
// This runs for all tenants if no --tenants are specified
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) use ($payload) {
$this->line("Tenant: {$tenant['id']}");
$tenant->putDownForMaintenance($payload);
});
$this->comment('Tenants are now in maintenance mode.');
}
/** Get the payload to be placed in the "down" file. */
protected function getDownDatabasePayload()
{
return [
'except' => $this->excludedPaths(),
'redirect' => $this->redirectPath(),
'retry' => $this->getRetryTime(),
'refresh' => $this->option('refresh'),
'secret' => $this->option('secret'),
'status' => (int) $this->option('status', 503),
];
}
}

27
src/Commands/Up.php Normal file
View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Commands;
use Illuminate\Console\Command;
use Stancl\Tenancy\Concerns\HasATenantsOption;
class Up extends Command
{
use HasATenantsOption;
protected $signature = 'tenants:up';
protected $description = 'Put tenants out of maintenance mode.';
public function handle(): void
{
tenancy()->runForMultiple($this->getTenants(), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$tenant->bringUpFromMaintenance();
});
$this->comment('Tenants are now out of maintenance mode.');
}
}

View file

@ -4,17 +4,27 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Database\Concerns; namespace Stancl\Tenancy\Database\Concerns;
use Carbon\Carbon; /**
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait MaintenanceMode trait MaintenanceMode
{ {
public function putDownForMaintenance($data = []) public function putDownForMaintenance($data = []): void
{ {
$this->update(['maintenance_mode' => [ $this->update([
'time' => $data['time'] ?? Carbon::now()->getTimestamp(), 'maintenance_mode' => [
'message' => $data['message'] ?? null, 'except' => $data['except'] ?? null,
'redirect' => $data['redirect'] ?? null,
'retry' => $data['retry'] ?? null, 'retry' => $data['retry'] ?? null,
'allowed' => $data['allowed'] ?? [], 'refresh' => $data['refresh'] ?? null,
]]); 'secret' => $data['secret'] ?? null,
'status' => $data['status'] ?? 503,
],
]);
}
public function bringUpFromMaintenance(): void
{
$this->update(['maintenance_mode' => null]);
} }
} }

View file

@ -7,7 +7,6 @@ namespace Stancl\Tenancy\Middleware;
use Closure; use Closure;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode; use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException; use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
@ -21,19 +20,38 @@ class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
if (tenant('maintenance_mode')) { if (tenant('maintenance_mode')) {
$data = tenant('maintenance_mode'); $data = tenant('maintenance_mode');
if (isset($data['allowed']) && IpUtils::checkIp($request->ip(), (array) $data['allowed'])) { if (isset($data['secret']) && $request->path() === $data['secret']) {
return $this->bypassResponse($data['secret']);
}
if ($this->hasValidBypassCookie($request, $data) ||
$this->inExceptArray($request)) {
return $next($request); return $next($request);
} }
if ($this->inExceptArray($request)) { if (isset($data['redirect'])) {
return $next($request); $path = $data['redirect'] === '/'
? $data['redirect']
: trim($data['redirect'], '/');
if ($request->path() !== $path) {
return redirect($path);
}
}
if (isset($data['template'])) {
return response(
$data['template'],
(int) ($data['status'] ?? 503),
$this->getHeaders($data)
);
} }
throw new HttpException( throw new HttpException(
503, (int) ($data['status'] ?? 503),
'Service Unavailable', 'Service Unavailable',
null, null,
isset($data['retry']) ? ['Retry-After' => $data['retry']] : [] $this->getHeaders($data)
); );
} }

View file

@ -86,6 +86,8 @@ class TenancyServiceProvider extends ServiceProvider
Commands\TenantList::class, Commands\TenantList::class,
Commands\TenantDump::class, Commands\TenantDump::class,
Commands\MigrateFresh::class, Commands\MigrateFresh::class,
Commands\Down::class,
Commands\Up::class,
]); ]);
$this->publishes([ $this->publishes([

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Tests\Etc;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase; use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase; use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains; use Stancl\Tenancy\Database\Concerns\HasDomains;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Stancl\Tenancy\Database\Models; use Stancl\Tenancy\Database\Models;
/** /**
@ -14,5 +15,5 @@ use Stancl\Tenancy\Database\Models;
*/ */
class Tenant extends Models\Tenant implements TenantWithDatabase class Tenant extends Models\Tenant implements TenantWithDatabase
{ {
use HasDatabase, HasDomains; use HasDatabase, HasDomains, MaintenanceMode;
} }

View file

@ -2,14 +2,14 @@
declare(strict_types=1); declare(strict_types=1);
use Illuminate\Support\Facades\Artisan;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode; use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode; use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain; use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Tests\Etc\Tenant; use Stancl\Tenancy\Tests\Etc\Tenant;
test('tenant can be in maintenance mode', function () { test('tenants can be in maintenance mode', function () {
Route::get('/foo', function () { Route::get('/foo', function () {
return 'bar'; return 'bar';
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]); })->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
@ -19,16 +19,40 @@ test('tenant can be in maintenance mode', function () {
'domain' => 'acme.localhost', 'domain' => 'acme.localhost',
]); ]);
pest()->get('http://acme.localhost/foo') pest()->get('http://acme.localhost/foo')->assertStatus(200);
->assertSuccessful();
tenancy()->end(); // flush stored tenant instance
$tenant->putDownForMaintenance(); $tenant->putDownForMaintenance();
pest()->expectException(HttpException::class); tenancy()->end(); // End tenancy before making a request
pest()->withoutExceptionHandling() pest()->get('http://acme.localhost/foo')->assertStatus(503);
->get('http://acme.localhost/foo');
$tenant->bringUpFromMaintenance();
tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(200);
});
test('tenants can be put into maintenance mode using artisan commands', function() {
Route::get('/foo', function () {
return 'bar';
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
$tenant = MaintenanceTenant::create();
$tenant->domains()->create([
'domain' => 'acme.localhost',
]);
pest()->get('http://acme.localhost/foo')->assertStatus(200);
Artisan::call('tenants:down');
tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(503);
Artisan::call('tenants:up');
tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(200);
}); });
class MaintenanceTenant extends Tenant class MaintenanceTenant extends Tenant