@@ -7,6 +7,7 @@ use App\Services\SyncDirectoryUsers;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class SyncActiveDirectory extends Command
|
||||
@@ -18,34 +19,48 @@ class SyncActiveDirectory extends Command
|
||||
|
||||
public function handle(SyncDirectoryUsers $sync): int
|
||||
{
|
||||
$started = hrtime(true);
|
||||
$context = [
|
||||
'run_id' => (string) Str::uuid(),
|
||||
'dry_run' => (bool) $this->option('dry-run'),
|
||||
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
|
||||
];
|
||||
|
||||
$duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000);
|
||||
Log::info('Active Directory sync started.', $context);
|
||||
|
||||
try {
|
||||
$lock = Cache::lock('ad:sync', 3600);
|
||||
if (! $lock->get()) {
|
||||
throw new DirectorySyncRejected('A directory sync is already running.');
|
||||
}
|
||||
try {
|
||||
$counts = $sync->run($context['dry_run'], $context['deactivate_missing']);
|
||||
$result = $sync->run($context['dry_run'], $context['deactivate_missing']);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
} catch (DirectorySyncRejected $exception) {
|
||||
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage()]);
|
||||
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]);
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Active Directory sync failed.', $context + ['exception_type' => $exception::class]);
|
||||
Log::error('Active Directory sync failed.', $context + [
|
||||
'exception_type' => $exception::class,
|
||||
'exception_code' => $exception->getCode(),
|
||||
'duration_ms' => $duration(),
|
||||
]);
|
||||
$this->error('Sync stopped due to a directory or database error.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
Log::info('Active Directory sync completed.', $context + $counts);
|
||||
foreach ($result['changes'] as $change) {
|
||||
Log::info('Active Directory sync user change.', $context + $change);
|
||||
}
|
||||
|
||||
$counts = $result['counts'];
|
||||
Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]);
|
||||
$summary = [];
|
||||
foreach ($counts as $key => $value) {
|
||||
$summary[] = "$key=$value";
|
||||
|
||||
Reference in New Issue
Block a user