-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathDatabaseServer.php
More file actions
453 lines (396 loc) · 14.7 KB
/
DatabaseServer.php
File metadata and controls
453 lines (396 loc) · 14.7 KB
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
<?php
namespace App\Models;
use App\Enums\DatabaseType;
use App\Enums\NotificationChannelSelection;
use App\Enums\NotificationTrigger;
use App\Exceptions\Backup\EncryptionException;
use Database\Factories\DatabaseServerFactory;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* @property string $id
* @property string $name
* @property string $host
* @property int $port
* @property DatabaseType $database_type
* @property string $username
* @property string $password
* @property array<string, mixed>|null $extra_config
* @property string|null $description
* @property bool $backups_enabled
* @property string|null $ssh_config_id
* @property string|null $agent_id
* @property string|null $managed_by
* @property NotificationTrigger $notification_trigger
* @property NotificationChannelSelection $notification_channel_selection
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Agent|null $agent
* @property-read Collection<int, Backup> $backups
* @property-read int|null $backups_count
* @property-read DatabaseServerSshConfig|null $sshConfig
* @property-read Collection<int, Snapshot> $snapshots
* @property-read int|null $snapshots_count
* @property-read Collection<int, NotificationChannel> $notificationChannels
* @property-read int|null $notification_channels_count
* @property-read Collection<int, UserServerAccess> $userAccesses
* @property-read int|null $user_accesses_count
*
* @method static DatabaseServerFactory factory($count = null, $state = [])
* @method static Builder<static>|DatabaseServer newModelQuery()
* @method static Builder<static>|DatabaseServer newQuery()
* @method static Builder<static>|DatabaseServer query()
* @method static Builder<static>|DatabaseServer whereCreatedAt($value)
* @method static Builder<static>|DatabaseServer whereDatabaseType($value)
* @method static Builder<static>|DatabaseServer whereDescription($value)
* @method static Builder<static>|DatabaseServer whereHost($value)
* @method static Builder<static>|DatabaseServer whereId($value)
* @method static Builder<static>|DatabaseServer whereName($value)
* @method static Builder<static>|DatabaseServer wherePassword($value)
* @method static Builder<static>|DatabaseServer wherePort($value)
* @method static Builder<static>|DatabaseServer whereUpdatedAt($value)
* @method static Builder<static>|DatabaseServer whereUsername($value)
* @method static Builder<static>|DatabaseServer whereBackupsEnabled($value)
*
* @mixin \Eloquent
*/
class DatabaseServer extends Model
{
/** @use HasFactory<DatabaseServerFactory> */
use HasFactory;
use HasUlids;
public bool $skipFileCleanup = false;
/**
* Transient state passed from factories to configure the server's default
* Backup row in an afterCreating hook. Never persisted.
*
* @var array<string, mixed>
*/
public array $pendingBackupState = [];
/**
* Transient database_names used for connection testing (SQLite file paths
* or selected database list). Not persisted — lives on the Backup model.
*
* @var array<int, string>|null
*/
public ?array $pendingDatabaseNames = null;
protected static function booted(): void
{
// Delete snapshots through Eloquent to trigger their deleting events
// (which clean up associated BackupJobs, Restores, and backup files)
static::deleting(function (DatabaseServer $server) {
foreach ($server->snapshots as $snapshot) {
$snapshot->skipFileCleanup = $server->skipFileCleanup;
$snapshot->delete();
}
// Delete restores targeting this server (cross-server restores)
// to trigger their deleting events which clean up BackupJobs
foreach (Restore::where('target_server_id', $server->id)->get() as $restore) {
$restore->delete();
}
});
}
protected $fillable = [
'name',
'host',
'port',
'database_type',
'username',
'password',
'description',
'backups_enabled',
'ssh_config_id',
'agent_id',
'extra_config',
'managed_by',
'notification_trigger',
'notification_channel_selection',
];
protected $hidden = [
'password',
];
protected function casts(): array
{
return [
'port' => 'integer',
'database_type' => DatabaseType::class,
'backups_enabled' => 'boolean',
'password' => 'encrypted',
'extra_config' => 'array',
'notification_trigger' => NotificationTrigger::class,
'notification_channel_selection' => NotificationChannelSelection::class,
];
}
/**
* @return BelongsTo<Agent, DatabaseServer>
*/
public function agent(): BelongsTo
{
return $this->belongsTo(Agent::class);
}
/**
* @return HasMany<Backup, DatabaseServer>
*/
public function backups(): HasMany
{
return $this->hasMany(Backup::class);
}
/**
* @return HasMany<Snapshot, DatabaseServer>
*/
public function snapshots(): HasMany
{
return $this->hasMany(Snapshot::class);
}
/**
* @return BelongsToMany<NotificationChannel, DatabaseServer>
*/
public function notificationChannels(): BelongsToMany
{
return $this->belongsToMany(NotificationChannel::class, 'database_server_notification_channel');
}
/**
* @return BelongsTo<DatabaseServerSshConfig, DatabaseServer>
*/
public function sshConfig(): BelongsTo
{
return $this->belongsTo(DatabaseServerSshConfig::class, 'ssh_config_id');
}
/**
* @return HasMany<UserServerAccess, DatabaseServer>
*/
public function userAccesses(): HasMany
{
return $this->hasMany(UserServerAccess::class);
}
/**
* Get the decrypted password with proper exception handling.
*
* @throws EncryptionException
*/
public function getDecryptedPassword(): string
{
try {
return $this->password ?? '';
} catch (DecryptException $e) { // @phpstan-ignore catch.neverThrown (DecryptException is thrown by Laravel's encrypted cast)
throw new EncryptionException(
'Unable to decrypt database password. The application key (APP_KEY) may have changed. Please update the password in the database server settings.',
previous: $e
);
}
}
/**
* Check if this server requires an SSH tunnel for connections.
* SQLite servers never need SSH tunnels since they use local file paths.
*/
public function requiresSshTunnel(): bool
{
return $this->database_type !== DatabaseType::SQLITE
&& $this->ssh_config_id !== null;
}
/**
* Check if this server requires SFTP file transfer for backups/restores.
* Only applies to SQLite servers accessed via SSH.
*/
public function requiresSftpTransfer(): bool
{
return $this->database_type === DatabaseType::SQLITE
&& $this->ssh_config_id !== null;
}
/**
* Create a temporary DatabaseServer instance for connection testing.
* This is not persisted to the database.
*
* @param array<string, mixed> $config
*/
public static function forConnectionTest(array $config, ?DatabaseServerSshConfig $sshConfig = null): self
{
$server = new self;
$server->host = $config['host'] ?? '';
$server->port = (int) ($config['port'] ?? 3306);
$server->database_type = $config['database_type'] ?? 'mysql';
$server->username = $config['username'] ?? '';
$server->password = $config['password'] ?? '';
$server->pendingDatabaseNames = $config['database_names'] ?? null;
$server->extra_config = $config['extra_config'] ?? null;
if ($sshConfig !== null) {
$server->ssh_config_id = 'temp';
$server->setRelation('sshConfig', $sshConfig);
}
return $server;
}
/**
* Collect the list of database names/paths this server is currently
* configured to target: the transient pending list (during connection
* testing), otherwise the flattened, de-duplicated union of every related
* Backup's `database_names`.
*
* @return array<int, string>
*/
public function resolveDatabaseNames(): array
{
if ($this->pendingDatabaseNames !== null) {
return $this->pendingDatabaseNames;
}
$backups = $this->relationLoaded('backups')
? $this->backups
: $this->backups()->get();
$names = [];
foreach ($backups as $backup) {
foreach ($backup->database_names ?? [] as $name) {
if ($name !== '') {
$names[] = $name;
}
}
}
return array_values(array_unique($names));
}
/**
* Get a short connection label for display (filename for SQLite, host:port for client-server).
*/
public function getConnectionLabel(): string
{
if ($this->database_type === DatabaseType::SQLITE) {
return implode(', ', array_map('basename', $this->resolveDatabaseNames()));
}
return "{$this->host}:{$this->port}";
}
/**
* Get full connection details for popover/tooltip (full paths for SQLite, host:port for client-server).
*/
public function getConnectionDetails(): string
{
if ($this->database_type === DatabaseType::SQLITE) {
return implode(', ', $this->resolveDatabaseNames());
}
return "{$this->host}:{$this->port}";
}
/**
* Get a type-specific config value from extra_config.
*/
public function getExtraConfig(string $key, mixed $default = null): mixed
{
return $this->extra_config[$key] ?? $default;
}
/**
* Get SSH display name if configured (tunnel or SFTP), null otherwise.
*/
public function getSshDisplayName(): ?string
{
if ($this->ssh_config_id === null || $this->sshConfig === null) {
return null;
}
return $this->sshConfig->getDisplayName();
}
/**
* Filter a list of database names using a regex pattern.
*
* @param array<string> $databases
* @return array<string>
*/
public static function filterDatabasesByPattern(array $databases, string $pattern): array
{
if (! self::isValidDatabasePattern($pattern)) {
return [];
}
$regex = '/'.$pattern.'/i';
return array_values(array_filter($databases, fn (string $db) => preg_match($regex, $db) === 1));
}
/**
* Check if this server and schema match the application's own database.
*/
public function isAppDatabase(string $schemaName): bool
{
$appDatabaseTypes = [DatabaseType::MYSQL, DatabaseType::POSTGRESQL];
if (! in_array($this->database_type, $appDatabaseTypes)) {
return false;
}
$defaultConnection = config('database.default');
$appDbDriver = config("database.connections.{$defaultConnection}.driver");
$driverToType = [
'mysql' => DatabaseType::MYSQL,
'mariadb' => DatabaseType::MYSQL,
'pgsql' => DatabaseType::POSTGRESQL,
];
$appDbType = $driverToType[$appDbDriver] ?? null;
if ($appDbType !== $this->database_type) {
return false;
}
$appDbHost = config("database.connections.{$defaultConnection}.host");
$appDbPort = (int) config("database.connections.{$defaultConnection}.port");
$appDbDatabase = config("database.connections.{$defaultConnection}.database");
return $this->host === $appDbHost
&& $this->port === $appDbPort
&& $schemaName === $appDbDatabase;
}
/**
* Move type-specific fields (auth_source, dump_flags) into extra_config.
* Clears stale keys when database type has changed.
*
* @param array<string, mixed> $data
* @param array<string, mixed>|null $existingExtraConfig
*/
public static function buildExtraConfig(array &$data, ?array $existingExtraConfig = null, ?string $previousType = null): void
{
$type = $data['database_type'] ?? '';
// Reset extra_config when type changes to avoid stale keys
$extraConfig = ($previousType !== null && $previousType !== $type) ? [] : ($existingExtraConfig ?? []);
if (array_key_exists('auth_source', $data)) {
if ($type === DatabaseType::MONGODB->value && ($data['auth_source'] !== '' && $data['auth_source'] !== null)) {
$extraConfig['auth_source'] = $data['auth_source'];
} else {
unset($extraConfig['auth_source']);
}
unset($data['auth_source']);
}
if (array_key_exists('dump_flags', $data)) {
if ($type !== DatabaseType::SQLITE->value && ($data['dump_flags'] !== '' && $data['dump_flags'] !== null)) {
$extraConfig['dump_flags'] = $data['dump_flags'];
} else {
unset($extraConfig['dump_flags']);
}
unset($data['dump_flags']);
}
$data['extra_config'] = $extraConfig ?: null;
}
/**
* Check if a regex pattern is valid.
*/
public static function isValidDatabasePattern(string $pattern): bool
{
if ($pattern === '') {
return false;
}
set_error_handler(fn () => true);
$result = preg_match('/'.$pattern.'/i', '') !== false;
restore_error_handler();
return $result;
}
/**
* Check if this server should send notifications for the given event type.
*/
public function shouldNotifyOn(string $event): bool
{
return $this->notification_trigger->shouldNotifyOn($event);
}
/**
* Resolve which notification channels to use for this server.
*
* @return Collection<int, NotificationChannel>
*/
public function resolveNotificationChannels(): Collection
{
return match ($this->notification_channel_selection) {
NotificationChannelSelection::All => NotificationChannel::all(),
NotificationChannelSelection::Selected => $this->notificationChannels,
};
}
}