A free open source IT asset/license management system
Adds cache locking to long-running processes (LDAP sync, etc)
snipe03a142131c2d
diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.phpindex 027a941314..24a4a66ee2 100644--- a/app/Console/Commands/LdapSync.php+++ b/app/Console/Commands/LdapSync.php@@ -9,11 +9,23 @@ use App\Models\Ldap;use App\Models\Location;use App\Models\Setting;use App\Models\User;+use App\Traits\LocksLongRunningOperation;use Illuminate\Console\Command;use Illuminate\Support\Facades\Log;class LdapSync extends Command{+ use LocksLongRunningOperation;++ /**+ * Shared mutex key for LDAP sync. Both the scheduled CLI run and the+ * UI "Sync Now" (which Artisan::call's this command) acquire the+ * same key, so cron + an admin click can't collide on the same+ * directory read. Public so the UI controller can read the lock+ * state via isOperationLocked() without duplicating the string.+ */+ public const LDAP_SYNC_LOCK = 'ldap-sync:running';+/*** The name and signature of the console command.*@@ -52,11 +64,32 @@ class LdapSync extends Commandexit();}- // Tag every action_log written during this run (direct writes- // and the observer-driven writes User saves trigger) as `ldap`- // so the activity report distinguishes LDAP-created entries- // from gui / api / sync-adapter origins.- return Actionlog::withActionSource('ldap', fn () => $this->runSync());+ // Shared backup+restore pattern: refuse to start a second sync+ // when one is already in flight. Covers both the UI sync-now+ // path (via LDAPImportController's Artisan::call) and a+ // scheduled cron that fires while a UI run is still open.+ // Output shape matches the existing JSON-summary branches+ // below so the UI's result parser doesn't need a special case.+ if (! $this->acquireOperationLock(self::LDAP_SYNC_LOCK)) {+ $message = $this->operationAlreadyRunningMessage('general.ldap_sync');+ if ($this->option('json_summary')) {+ $this->info(json_encode(['error' => true, 'error_message' => $message, 'summary' => []]));+ } else {+ $this->error($message);+ }++ return 1;+ }++ try {+ // Tag every action_log written during this run (direct writes+ // and the observer-driven writes User saves trigger) as `ldap`+ // so the activity report distinguishes LDAP-created entries+ // from gui / api / sync-adapter origins.+ return Actionlog::withActionSource('ldap', fn () => $this->runSync());+ } finally {+ $this->releaseOperationLock(self::LDAP_SYNC_LOCK);+ }}private function runSync()@@ -221,7 +254,7 @@ class LdapSync extends Command}}}-+$results = array_merge($location_users, $results);$results['count'] = count(array_filter(array_keys($results), 'is_int'));}diff --git a/app/Console/Commands/PullInventory.php b/app/Console/Commands/PullInventory.phpindex 7fd8c284bc..1f3f617d98 100644--- a/app/Console/Commands/PullInventory.php+++ b/app/Console/Commands/PullInventory.php@@ -6,12 +6,15 @@ use App\Models\Actionlog;use App\Models\SyncAdapterInstance;use App\SyncAdapters\SyncAdapter;use App\SyncAdapters\SyncErrorFormatter;+use App\Traits\LocksLongRunningOperation;use Illuminate\Console\Command;use Illuminate\Support\Facades\Log;use Throwable;class PullInventory extends Command{+ use LocksLongRunningOperation;+protected $signature = 'snipeit:pull-inventory{adapter? : The adapter instance slug. Omit to pull every enabled instance.}{--dry-run : Fetch and log each normalized record but do not create, update, or link any Snipe-IT assets. Overrides the per-instance pull_dry_run config for this one run.}@@ -110,122 +113,142 @@ class PullInventory extends Commandreturn self::FAILURE;}- // CLI PHP usually has no time cap, but being explicit is- // harmless and matches the interactive controller.- set_time_limit(0);-- $seen = 0;- $skipped = 0;- $errors = 0;-- Log::channel('sync-adapters')->info("{$slug} sync starting (CLI)");-- // --dry-run flag on the CLI overrides the per-instance config- // for this one run so admins can preview a sync without first- // flipping and saving the setting in the web UI. Push the- // override onto the adapter so any inner isPullDryRun() check- // honors it too.- if ($this->option('dry-run') === true) {- $adapter->withPullDryRunOverride(true);- }- $dryRun = $adapter->isPullDryRun();- if ($dryRun) {- Log::channel('sync-adapters')->info("{$slug} sync [dry-run]: no assets will be created or updated");- $this->warn("Pull dry-run is on for {$slug}: records will be logged, no assets will be written.");- }+ // Per-instance mutex. Pull and Push on the same adapter share+ // one key, so a scheduled pull and a UI push on the same+ // instance can't collide. Fleet pulling doesn't block Jamf+ // pulling because the key is scoped to the instance slug.+ // Return SUCCESS on contention so a cron tick that fires+ // during a long UI run isn't a scheduler failure, just a+ // no-op.+ if (! $this->acquireOperationLock($instance->lockKey())) {+ $message = "{$slug} sync skipped: another pull or push is already running for this instance.";+ Log::channel('sync-adapters')->info($message);+ $this->warn($message);+ $rows[] = [$slug, 'Already running', '-', '-', '-', self::formatElapsed($startedAt)];- // --limit caps how many records this adapter processes before- // we break out. Null = no limit. Non-positive values are- // treated as no-limit so operators don't foot-gun themselves- // with --limit=0 and get a silent zero-record run.- $limitInput = $this->option('limit');- $limit = ($limitInput !== null && (int) $limitInput > 0) ? (int) $limitInput : null;- if ($limit !== null) {- Log::channel('sync-adapters')->info("{$slug} sync: --limit set to {$limit}, will stop after that many records");- $this->warn("Pull limit is {$limit} for {$slug}: run stops after that many records.");+ return self::SUCCESS;}try {- Actionlog::withActionSource('sync:'.$slug, function () use ($adapter, $slug, $dryRun, $limit, &$seen, &$skipped, &$errors) {- foreach ($adapter->pull() as $record) {- if ($limit !== null && ($seen + $skipped + $errors) >= $limit) {- Log::channel('sync-adapters')->info("{$slug} sync: --limit {$limit} reached, stopping early");- break;- }- try {- if ($dryRun) {- // Mirror of the push dry-run shape: log the- // normalized record, tally it as "seen" so the- // run summary reports useful counts, skip the- // asset-side write entirely.- Log::channel('sync-adapters')->info(sprintf(- '%s sync [dry-run]: would upsert record source=%s id=%s hostname=%s serial=%s',- $slug,- $record->sourceKey,- $record->sourceId,- $record->hostname ?? '(none)',- $record->hardwareSerial ?? '(none)',- ));- $seen++;-- continue;- }+ // CLI PHP usually has no time cap, but being explicit is+ // harmless and matches the interactive controller.+ set_time_limit(0);++ $seen = 0;+ $skipped = 0;+ $errors = 0;++ Log::channel('sync-adapters')->info("{$slug} sync starting (CLI)");++ // --dry-run flag on the CLI overrides the per-instance config+ // for this one run so admins can preview a sync without first+ // flipping and saving the setting in the web UI. Push the+ // override onto the adapter so any inner isPullDryRun() check+ // honors it too.+ if ($this->option('dry-run') === true) {+ $adapter->withPullDryRunOverride(true);+ }+ $dryRun = $adapter->isPullDryRun();+ if ($dryRun) {+ Log::channel('sync-adapters')->info("{$slug} sync [dry-run]: no assets will be created or updated");+ $this->warn("Pull dry-run is on for {$slug}: records will be logged, no assets will be written.");+ }++ // --limit caps how many records this adapter processes before+ // we break out. Null = no limit. Non-positive values are+ // treated as no-limit so operators don't foot-gun themselves+ // with --limit=0 and get a silent zero-record run.+ $limitInput = $this->option('limit');+ $limit = ($limitInput !== null && (int) $limitInput > 0) ? (int) $limitInput : null;+ if ($limit !== null) {+ Log::channel('sync-adapters')->info("{$slug} sync: --limit set to {$limit}, will stop after that many records");+ $this->warn("Pull limit is {$limit} for {$slug}: run stops after that many records.");+ }- $result = SyncAdapter::syncFromRecord($record);- if ($result === null) {- $skipped++;- } else {- $seen++;+ try {+ Actionlog::withActionSource('sync:'.$slug, function () use ($adapter, $slug, $dryRun, $limit, &$seen, &$skipped, &$errors) {+ foreach ($adapter->pull() as $record) {+ if ($limit !== null && ($seen + $skipped + $errors) >= $limit) {+ Log::channel('sync-adapters')->info("{$slug} sync: --limit {$limit} reached, stopping early");+ break;+ }+ try {+ if ($dryRun) {+ // Mirror of the push dry-run shape: log the+ // normalized record, tally it as "seen" so the+ // run summary reports useful counts, skip the+ // asset-side write entirely.+ Log::channel('sync-adapters')->info(sprintf(+ '%s sync [dry-run]: would upsert record source=%s id=%s hostname=%s serial=%s',+ $slug,+ $record->sourceKey,+ $record->sourceId,+ $record->hostname ?? '(none)',+ $record->hardwareSerial ?? '(none)',+ ));+ $seen++;++ continue;+ }++ $result = SyncAdapter::syncFromRecord($record);+ if ($result === null) {+ $skipped++;+ } else {+ $seen++;+ }+ } catch (Throwable $e) {+ $errors++;+ $sourceId = $record->sourceId;+ $message = $e->getMessage();+ // A single bad record shouldn't take down the run.+ // Log the offending host and keep going.+ $this->warn("Failed to sync host {$sourceId}: {$message}");+ Log::channel('sync-adapters')->warning("{$slug} sync: failed to upsert host {$sourceId}: {$message}");}- } catch (Throwable $e) {- $errors++;- $sourceId = $record->sourceId;- $message = $e->getMessage();- // A single bad record shouldn't take down the run.- // Log the offending host and keep going.- $this->warn("Failed to sync host {$sourceId}: {$message}");- Log::channel('sync-adapters')->warning("{$slug} sync: failed to upsert host {$sourceId}: {$message}");}- }- });- } catch (Throwable $e) {- // Brief summary for the UI "Last Synced" field and the- // console error output.- $summary = SyncErrorFormatter::summary($e);- $abortSummary = "Sync aborted: {$summary}";+ });+ } catch (Throwable $e) {+ // Brief summary for the UI "Last Synced" field and the+ // console error output.+ $summary = SyncErrorFormatter::summary($e);+ $abortSummary = "Sync aborted: {$summary}";+ $instance->last_synced_at = now();+ $instance->last_sync_result = $abortSummary;+ $instance->save();++ $elapsed = self::formatElapsed($startedAt);+ $this->error("{$slug} {$abortSummary} ({$elapsed})");+ Log::channel('sync-adapters')->warning(+ "{$slug} sync aborted after {$seen} record(s), {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}: {$summary}",+ SyncErrorFormatter::logContext($e),+ );+ $rows[] = [$slug, 'Aborted', $seen, $skipped, $errors, $elapsed];++ return self::FAILURE;+ }++ // Same lang key as the UI so both paths render the same phrasing+ // on the settings page.+ $result = trans('admin/settings/sync_adapters.sync_complete', [+ 'count' => $seen,+ 'skipped' => $skipped,+ 'errors' => $errors,+ ]);$instance->last_synced_at = now();- $instance->last_sync_result = $abortSummary;+ $instance->last_sync_result = $result;$instance->save();$elapsed = self::formatElapsed($startedAt);- $this->error("{$slug} {$abortSummary} ({$elapsed})");- Log::channel('sync-adapters')->warning(- "{$slug} sync aborted after {$seen} record(s), {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}: {$summary}",- SyncErrorFormatter::logContext($e),- );- $rows[] = [$slug, 'Aborted', $seen, $skipped, $errors, $elapsed];+ Log::channel('sync-adapters')->info("{$slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}");- return self::FAILURE;- }-- // Same lang key as the UI so both paths render the same phrasing- // on the settings page.- $result = trans('admin/settings/sync_adapters.sync_complete', [- 'count' => $seen,- 'skipped' => $skipped,- 'errors' => $errors,- ]);- $instance->last_synced_at = now();- $instance->last_sync_result = $result;- $instance->save();+ $status = $errors > 0 ? 'Errors' : 'OK';+ $rows[] = [$slug, $status, $seen, $skipped, $errors, $elapsed];- $elapsed = self::formatElapsed($startedAt);- Log::channel('sync-adapters')->info("{$slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}");-- $status = $errors > 0 ? 'Errors' : 'OK';- $rows[] = [$slug, $status, $seen, $skipped, $errors, $elapsed];-- return $errors > 0 ? self::FAILURE : self::SUCCESS;+ return $errors > 0 ? self::FAILURE : self::SUCCESS;+ } finally {+ $this->releaseOperationLock($instance->lockKey());+ }}/**diff --git a/app/Console/Commands/PushInventory.php b/app/Console/Commands/PushInventory.phpindex ed53d05ffa..128038b843 100644--- a/app/Console/Commands/PushInventory.php+++ b/app/Console/Commands/PushInventory.php@@ -5,12 +5,15 @@ namespace App\Console\Commands;use App\Models\AssetExternalSource;use App\Models\SyncAdapterInstance;use App\SyncAdapters\PushableAdapter;+use App\Traits\LocksLongRunningOperation;use Illuminate\Console\Command;use Illuminate\Support\Facades\Log;use Throwable;class PushInventory extends Command{+ use LocksLongRunningOperation;+protected $signature = 'snipeit:push-inventory{adapter? : The adapter instance slug. Omit to push every enabled instance that supports push.}{--dry-run : Build each payload and log it to the sync-adapters log without calling the vendor API. Overrides the per-instance push_dry_run config for this one run.}@@ -110,73 +113,93 @@ class PushInventory extends Commandreturn self::FAILURE;}- // --dry-run on the CLI overrides the persisted push_dry_run- // config so admins can preview a push without saving the- // setting through the web UI first.- if ($this->option('dry-run') === true) {- $adapter->withPushDryRunOverride(true);- $this->warn("Push dry-run is on for {$slug}: payloads will be logged, no vendor API calls will be made.");- }+ // Per-instance mutex. Pull and Push on the same adapter share+ // one key so a scheduled push and a UI pull on the same+ // instance can't collide. Fleet pushing doesn't block Jamf+ // pushing because the key is scoped to the instance slug.+ // SUCCESS on contention so a cron tick during a UI run isn't+ // a scheduler failure.+ if (! $this->acquireOperationLock($instance->lockKey())) {+ $message = "{$slug} push skipped: another pull or push is already running for this instance.";+ Log::channel('sync-adapters')->info($message);+ $this->warn($message);+ $rows[] = [$slug, 'Already running', '-', '-', self::formatElapsed($startedAt)];- // --limit caps how many assets this adapter pushes before we- // break out. Null = no limit. Non-positive values treated as- // no-limit so operators don't foot-gun themselves with- // --limit=0 and get a silent zero-asset run.- $limitInput = $this->option('limit');- $limit = ($limitInput !== null && (int) $limitInput > 0) ? (int) $limitInput : null;- if ($limit !== null) {- $this->warn("Push limit is {$limit} for {$slug}: run stops after that many assets.");+ return self::SUCCESS;}- set_time_limit(0);-- $pushed = 0;- $errors = 0;-try {- AssetExternalSource::query()- ->where('source', $slug)- ->with('asset')- ->chunkById(200, function ($queryRows) use ($adapter, $slug, $limit, &$pushed, &$errors) {- foreach ($queryRows as $row) {- if ($limit !== null && ($pushed + $errors) >= $limit) {- // Returning false from a chunkById callback- // tells Eloquent to stop paging after this- // chunk, which is what we want for an early- // break on --limit.- Log::channel('sync-adapters')->info("{$slug} push: --limit {$limit} reached, stopping early");-- return false;- }- $asset = $row->asset;- if ($asset === null) {- continue;- }+ // --dry-run on the CLI overrides the persisted push_dry_run+ // config so admins can preview a push without saving the+ // setting through the web UI first.+ if ($this->option('dry-run') === true) {+ $adapter->withPushDryRunOverride(true);+ $this->warn("Push dry-run is on for {$slug}: payloads will be logged, no vendor API calls will be made.");+ }- try {- $adapter->push($asset);- $pushed++;- } catch (Throwable $e) {- $errors++;- $message = $e->getMessage();- $this->warn("push: asset {$asset->id} failed: {$message}");+ // --limit caps how many assets this adapter pushes before we+ // break out. Null = no limit. Non-positive values treated as+ // no-limit so operators don't foot-gun themselves with+ // --limit=0 and get a silent zero-asset run.+ $limitInput = $this->option('limit');+ $limit = ($limitInput !== null && (int) $limitInput > 0) ? (int) $limitInput : null;+ if ($limit !== null) {+ $this->warn("Push limit is {$limit} for {$slug}: run stops after that many assets.");+ }++ set_time_limit(0);++ $pushed = 0;+ $errors = 0;++ try {+ AssetExternalSource::query()+ ->where('source', $slug)+ ->with('asset')+ ->chunkById(200, function ($queryRows) use ($adapter, $slug, $limit, &$pushed, &$errors) {+ foreach ($queryRows as $row) {+ if ($limit !== null && ($pushed + $errors) >= $limit) {+ // Returning false from a chunkById callback+ // tells Eloquent to stop paging after this+ // chunk, which is what we want for an early+ // break on --limit.+ Log::channel('sync-adapters')->info("{$slug} push: --limit {$limit} reached, stopping early");++ return false;+ }++ $asset = $row->asset;+ if ($asset === null) {+ continue;+ }++ try {+ $adapter->push($asset);+ $pushed++;+ } catch (Throwable $e) {+ $errors++;+ $message = $e->getMessage();+ $this->warn("push: asset {$asset->id} failed: {$message}");+ }}- }- });- } catch (Throwable $e) {- $elapsed = self::formatElapsed($startedAt);- $message = $e->getMessage();- $this->error("{$slug} push aborted: {$message} ({$elapsed})");- $rows[] = [$slug, 'Aborted', $pushed, $errors, $elapsed];+ });+ } catch (Throwable $e) {+ $elapsed = self::formatElapsed($startedAt);+ $message = $e->getMessage();+ $this->error("{$slug} push aborted: {$message} ({$elapsed})");+ $rows[] = [$slug, 'Aborted', $pushed, $errors, $elapsed];- return self::FAILURE;- }+ return self::FAILURE;+ }- $status = $errors > 0 ? 'Errors' : 'OK';- $rows[] = [$slug, $status, $pushed, $errors, self::formatElapsed($startedAt)];+ $status = $errors > 0 ? 'Errors' : 'OK';+ $rows[] = [$slug, $status, $pushed, $errors, self::formatElapsed($startedAt)];- return $errors > 0 ? self::FAILURE : self::SUCCESS;+ return $errors > 0 ? self::FAILURE : self::SUCCESS;+ } finally {+ $this->releaseOperationLock($instance->lockKey());+ }}/**diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.phpindex fc7608ccfa..30d836aac0 100644--- a/app/Http/Controllers/SettingsController.php+++ b/app/Http/Controllers/SettingsController.php@@ -21,6 +21,7 @@ use App\Models\Setting;use App\Models\User;use App\Notifications\MailTest;use App\Rules\CssColor;+use App\Traits\LocksLongRunningOperation;use Illuminate\Contracts\View\View;use Illuminate\Http\JsonResponse;use Illuminate\Http\RedirectResponse;@@ -47,6 +48,18 @@ use ZipArchive;*/class SettingsController extends Controller{+ use LocksLongRunningOperation;++ /**+ * Shared mutex key for backup + restore. Both operations acquire+ * the same key so they're mutually exclusive. Restore is+ * backup-plus-more (it optionally takes a pre-restore backup, wipes, replays),+ * so a concurrent plain backup firing while a restore holds this+ * lock would race the pre-restore backup write against the+ * concurrent backup's write to the same backup disk.+ */+ private const BACKUP_RESTORE_LOCK = 'backup-restore:running';+/*** Return a view that shows some of the key settings.*@@ -925,7 +938,13 @@ class SettingsController extends Controller// Reverse the array so it lists oldest first$files = array_reverse($files_raw);- return view('settings/backups', compact('files'));+ // Belt-and-suspenders UI feedback for the shared backup+restore+ // mutex. The write-side rejects a concurrent trigger regardless,+ // this just stops the admin from clicking a button that will+ // immediately bounce.+ $backupRestoreRunning = $this->isOperationLocked(self::BACKUP_RESTORE_LOCK);++ return view('settings/backups', compact('files', 'backupRestoreRunning'));}/**@@ -937,7 +956,16 @@ class SettingsController extends Controller*/public function postBackups(): RedirectResponse{- if (! config('app.lock_passwords')) {+ if (config('app.lock_passwords')) {+ return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));+ }++ if (!$this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {+ return redirect()->route('settings.backups.index')+ ->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));+ }++ try {Artisan::call('snipeit:backup', ['--filename' => 'manual-backup-'.date('Y-m-d-H-i-s')]);$output = Artisan::output();@@ -955,9 +983,9 @@ class SettingsController extends Controller}return redirect()->route('settings.backups.index')->with('error', $formatted_output);+ } finally {+ $this->releaseOperationLock(self::BACKUP_RESTORE_LOCK);}-- return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));}/**@@ -1099,6 +1127,11 @@ class SettingsController extends Controllerreturn redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));}+ if (!$this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {+ return redirect()->route('settings.backups.index')+ ->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));+ }+// Path inside the backup disk mirrors getBackups / downloadFile /// deleteFile. spatie writes to <disk root>/<backup.backup.name>/// and the name defaults to 'backups'.@@ -1281,6 +1314,7 @@ class SettingsController extends Controllerif ($localTempPath !== null && file_exists($localTempPath)) {@unlink($localTempPath);}+ $this->releaseOperationLock(self::BACKUP_RESTORE_LOCK);}}diff --git a/app/Http/Controllers/SyncAdapterController.php b/app/Http/Controllers/SyncAdapterController.phpindex 535b8354d7..4deb78e44f 100644--- a/app/Http/Controllers/SyncAdapterController.php+++ b/app/Http/Controllers/SyncAdapterController.php@@ -4,6 +4,7 @@ namespace App\Http\Controllers;use App\Models\Actionlog;use App\SyncAdapters\SyncErrorFormatter;+use App\Traits\LocksLongRunningOperation;use Illuminate\Contracts\View\View;use Illuminate\Http\JsonResponse;use Illuminate\Http\RedirectResponse;@@ -16,6 +17,8 @@ use Symfony\Component\HttpFoundation\Response;class SyncAdapterController extends Controller{+ use LocksLongRunningOperation;+public function getAdapters(Request $request): View|RedirectResponse{$adapterTypes = \App\SyncAdapters\SyncAdapter::typeLabels();@@ -248,130 +251,143 @@ class SyncAdapterController extends Controller->with('error', $message);}- // Drop PHP's execution-time cap. Web-server proxy timeouts still apply tho- set_time_limit(0);+ // Per-instance mutex: a pull or push already in progress for THIS+ // adapter blocks a second trigger. Different adapters stay+ // independent (Fleet pulling doesn't block a Jamf pull, etc).+ if (!$this->acquireOperationLock($instance->lockKey())) {+ return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with('error', $this->operationAlreadyRunningMessage('admin/settings/sync_adapters.sync_adapter_run'));+ }- $seen = 0;- $skipped = 0;- $errors = 0;- $startedAt = microtime(true);+ try {- Log::channel('sync-adapters')->info("{$instance->slug} sync starting (UI)");+ // Drop PHP's execution-time cap. Web-server proxy timeouts still apply tho+ set_time_limit(0);- $dryRun = $adapter->isPullDryRun();- if ($dryRun) {- Log::channel('sync-adapters')->info($instance->slug.' sync [dry-run]: no assets will be created or updated');- }+ $seen = 0;+ $skipped = 0;+ $errors = 0;+ $startedAt = microtime(true);- // captureSyncRunLog's token return goes unused on the caller- // side - the panel reads sync_run_log_last_token directly from- // session rather than from a flashed value, so we don't need- // the token here. The capture itself is still what we're after:- // it isolates this run's log lines, caches them under the- // persistent session key, and purges any prior run's cache.- // --limit from the panel caps how many records this run- // processes before stopping. Null = no limit. Non-positive- // (<=0) treated as no-limit to prevent silent zero-record runs.- $limitInput = $request->input('limit');- $limit = ($limitInput !== null && $limitInput !== '' && (int) $limitInput > 0) ? (int) $limitInput : null;- if ($limit !== null) {- Log::channel('sync-adapters')->info($instance->slug.' sync: limit set to '.$limit.', will stop after that many records');- }+ Log::channel('sync-adapters')->info("{$instance->slug} sync starting (UI)");- $abortedRedirect = null;- $this->captureSyncRunLog($instance->slug, 'pull', function () use ($adapter, $instance, $dryRun, $limit, &$seen, &$skipped, &$errors, &$abortedRedirect) {- try {- Actionlog::withActionSource('sync:'.$instance->slug, function () use ($adapter, $instance, $dryRun, $limit, &$seen, &$skipped, &$errors) {- foreach ($adapter->pull() as $record) {- if ($limit !== null && ($seen + $skipped + $errors) >= $limit) {- Log::channel('sync-adapters')->info($instance->slug.' sync: limit '.$limit.' reached, stopping early');- break;- }- try {- if ($dryRun) {- // Mirror of the push dry-run shape: log the- // normalized record and tally it as "seen"- // without handing it to syncFromRecord.- Log::channel('sync-adapters')->info(sprintf(- '%s sync [dry-run]: would upsert record source=%s id=%s hostname=%s serial=%s',- $instance->slug,- $record->sourceKey,- $record->sourceId,- $record->hostname ?? '(none)',- $record->hardwareSerial ?? '(none)',- ));- $seen++;-- continue;+ $dryRun = $adapter->isPullDryRun();+ if ($dryRun) {+ Log::channel('sync-adapters')->info($instance->slug . ' sync [dry-run]: no assets will be created or updated');+ }++ // captureSyncRunLog's token return goes unused on the caller+ // side - the panel reads sync_run_log_last_token directly from+ // session rather than from a flashed value, so we don't need+ // the token here. The capture itself is still what we're after:+ // it isolates this run's log lines, caches them under the+ // persistent session key, and purges any prior run's cache.+ // --limit from the panel caps how many records this run+ // processes before stopping. Null = no limit. Non-positive+ // (<=0) treated as no-limit to prevent silent zero-record runs.+ $limitInput = $request->input('limit');+ $limit = ($limitInput !== null && $limitInput !== '' && (int) $limitInput > 0) ? (int) $limitInput : null;+ if ($limit !== null) {+ Log::channel('sync-adapters')->info($instance->slug . ' sync: limit set to ' . $limit . ', will stop after that many records');+ }++ $abortedRedirect = null;+ $this->captureSyncRunLog($instance->slug, 'pull', function () use ($adapter, $instance, $dryRun, $limit, &$seen, &$skipped, &$errors, &$abortedRedirect) {+ try {+ Actionlog::withActionSource('sync:' . $instance->slug, function () use ($adapter, $instance, $dryRun, $limit, &$seen, &$skipped, &$errors) {+ foreach ($adapter->pull() as $record) {+ if ($limit !== null && ($seen + $skipped + $errors) >= $limit) {+ Log::channel('sync-adapters')->info($instance->slug . ' sync: limit ' . $limit . ' reached, stopping early');+ break;}+ try {+ if ($dryRun) {+ // Mirror of the push dry-run shape: log the+ // normalized record and tally it as "seen"+ // without handing it to syncFromRecord.+ Log::channel('sync-adapters')->info(sprintf(+ '%s sync [dry-run]: would upsert record source=%s id=%s hostname=%s serial=%s',+ $instance->slug,+ $record->sourceKey,+ $record->sourceId,+ $record->hostname ?? '(none)',+ $record->hardwareSerial ?? '(none)',+ ));+ $seen++;++ continue;+ }- $result = \App\SyncAdapters\SyncAdapter::syncFromRecord($record);- if ($result === null) {- $skipped++;- } else {- $seen++;+ $result = \App\SyncAdapters\SyncAdapter::syncFromRecord($record);+ if ($result === null) {+ $skipped++;+ } else {+ $seen++;+ }+ } catch (\Throwable $e) {+ $errors++;+ Log::channel('sync-adapters')->warning($instance->slug . ' sync: failed to upsert host ' . $record->sourceId . ': ' . $e->getMessage());}- } catch (\Throwable $e) {- $errors++;- Log::channel('sync-adapters')->warning($instance->slug.' sync: failed to upsert host '.$record->sourceId.': '.$e->getMessage());}- }- });- } catch (\Throwable $e) {- Log::channel('sync-adapters')->warning(- $instance->slug.' sync aborted: '.SyncErrorFormatter::summary($e),- SyncErrorFormatter::logContext($e),- );-- $failMessage = trans('admin/settings/sync_adapters.sync_failed', [- 'summary' => SyncErrorFormatter::summary($e),- ]);- $instance->last_synced_at = now();- $instance->last_sync_result = $failMessage;- $instance->save();+ });+ } catch (\Throwable $e) {+ Log::channel('sync-adapters')->warning(+ $instance->slug . ' sync aborted: ' . SyncErrorFormatter::summary($e),+ SyncErrorFormatter::logContext($e),+ );- $abortedRedirect = redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])- ->with('error', $failMessage);- }- });+ $failMessage = trans('admin/settings/sync_adapters.sync_failed', [+ 'summary' => SyncErrorFormatter::summary($e),+ ]);+ $instance->last_synced_at = now();+ $instance->last_sync_result = $failMessage;+ $instance->save();- if ($abortedRedirect !== null) {- return $abortedRedirect;- }+ $abortedRedirect = redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with('error', $failMessage);+ }+ });- $result = trans('admin/settings/sync_adapters.sync_complete', [- 'count' => $seen,- 'skipped' => $skipped,- 'errors' => $errors,- ]);- $instance->last_synced_at = now();- $instance->last_sync_result = $result;- $instance->save();+ if ($abortedRedirect !== null) {+ return $abortedRedirect;+ }- $elapsed = number_format(microtime(true) - $startedAt, 1);- Log::channel('sync-adapters')->info("{$instance->slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}s");-- // at least one seen, no errors -> success (green)- // at least one seen, some errors -> warning (orange, admin should check log)- // nothing seen at all, at least one error -> error (red)- // nothing seen AND no errors -> warning: vendor returned no rows,- // which may be legitimate (empty inventory) but is also the- // canary for a misconfigured pull that silently returned empty.- // Warning flags it for the admin to notice without being a- // hard error, so a genuinely empty vendor doesn't scream red.- $flashType = match (true) {- $seen > 0 && $errors === 0 => 'success',- $seen > 0 && $errors > 0 => 'warning',- $seen === 0 && $errors > 0 => 'error',- default => 'warning',- };-- // The download-run-log link reads sync_run_log_last_token from- // the persistent session instead of a flash key, so a reload- // inside the 10-min TTL keeps the link visible. captureSyncRunLog- // put() the token in session already.- return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])- ->with($flashType, $result);+ $result = trans('admin/settings/sync_adapters.sync_complete', [+ 'count' => $seen,+ 'skipped' => $skipped,+ 'errors' => $errors,+ ]);+ $instance->last_synced_at = now();+ $instance->last_sync_result = $result;+ $instance->save();++ $elapsed = number_format(microtime(true) - $startedAt, 1);+ Log::channel('sync-adapters')->info("{$instance->slug} sync complete: {$seen} record(s) processed, {$skipped} skipped, {$errors} error(s), elapsed {$elapsed}s");++ // at least one seen, no errors -> success (green)+ // at least one seen, some errors -> warning (orange, admin should check log)+ // nothing seen at all, at least one error -> error (red)+ // nothing seen AND no errors -> warning: vendor returned no rows,+ // which may be legitimate (empty inventory) but is also the+ // canary for a misconfigured pull that silently returned empty.+ // Warning flags it for the admin to notice without being a+ // hard error, so a genuinely empty vendor doesn't scream red.+ $flashType = match (true) {+ $seen > 0 && $errors === 0 => 'success',+ $seen > 0 && $errors > 0 => 'warning',+ $seen === 0 && $errors > 0 => 'error',+ default => 'warning',+ };++ // The download-run-log link reads sync_run_log_last_token from+ // the persistent session instead of a flash key, so a reload+ // inside the 10-min TTL keeps the link visible. captureSyncRunLog+ // put() the token in session already.+ return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with($flashType, $result);+ } finally {+ $this->releaseOperationLock($instance->lockKey());+ }}/**@@ -439,110 +455,123 @@ class SyncAdapterController extends Controller->with('error', $message);}- set_time_limit(0);+ // Shared with the pull side via $instance->lockKey() so Pull Now+ // and Push Now on the same adapter are mutually exclusive.+ // Different adapters stay independent.+ if (!$this->acquireOperationLock($instance->lockKey())) {+ return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with('error', $this->operationAlreadyRunningMessage('admin/settings/sync_adapters.sync_adapter_run'));+ }- $pushed = 0;- $skipped = 0;- $errors = 0;+ try {- // --limit cap, same semantics as the pull side.- $limitInput = $request->input('limit');- $limit = ($limitInput !== null && $limitInput !== '' && (int) $limitInput > 0) ? (int) $limitInput : null;- if ($limit !== null) {- Log::channel('sync-adapters')->info($instance->slug.' push: limit set to '.$limit.', will stop after that many assets');- }+ set_time_limit(0);- $abortedRedirect = null;- $this->captureSyncRunLog($instance->slug, 'push', function () use ($adapter, $instance, $limit, &$pushed, &$skipped, &$errors, &$abortedRedirect) {- try {- \App\Models\AssetExternalSource::query()- ->where('source', $instance->slug)- ->with('asset')- ->chunkById(200, function ($rows) use ($adapter, $instance, $limit, &$pushed, &$skipped, &$errors) {- foreach ($rows as $row) {- if ($limit !== null && ($pushed + $skipped + $errors) >= $limit) {- // Returning false from chunkById's- // callback stops Eloquent paging after- // this chunk.- Log::channel('sync-adapters')->info($instance->slug.' push: limit '.$limit.' reached, stopping early');-- return false;- }+ $pushed = 0;+ $skipped = 0;+ $errors = 0;- $asset = $row->asset;- if ($asset === null) {- continue;- }+ // --limit cap, same semantics as the pull side.+ $limitInput = $request->input('limit');+ $limit = ($limitInput !== null && $limitInput !== '' && (int) $limitInput > 0) ? (int) $limitInput : null;+ if ($limit !== null) {+ Log::channel('sync-adapters')->info($instance->slug . ' push: limit set to ' . $limit . ', will stop after that many assets');+ }- try {- if ($adapter->push($asset)) {- $pushed++;- } else {- $skipped++;+ $abortedRedirect = null;+ $this->captureSyncRunLog($instance->slug, 'push', function () use ($adapter, $instance, $limit, &$pushed, &$skipped, &$errors, &$abortedRedirect) {+ try {+ \App\Models\AssetExternalSource::query()+ ->where('source', $instance->slug)+ ->with('asset')+ ->chunkById(200, function ($rows) use ($adapter, $instance, $limit, &$pushed, &$skipped, &$errors) {+ foreach ($rows as $row) {+ if ($limit !== null && ($pushed + $skipped + $errors) >= $limit) {+ // Returning false from chunkById's+ // callback stops Eloquent paging after+ // this chunk.+ Log::channel('sync-adapters')->info($instance->slug . ' push: limit ' . $limit . ' reached, stopping early');++ return false;+ }++ $asset = $row->asset;+ if ($asset === null) {+ continue;+ }++ try {+ if ($adapter->push($asset)) {+ $pushed++;+ } else {+ $skipped++;+ }+ } catch (\Throwable $e) {+ $errors++;+ // Log the sanitized summary (short) plus,+ // for HTTP client exceptions, the raw+ // response body truncated to 2KB so vendor+ // errors like "missing required field+ // 'query'" or "gitops mode requires spec"+ // surface in the log even when the vendor's+ // JSON shape isn't one the summary+ // extractor recognizes.+ Log::channel('sync-adapters')->warning(sprintf(+ '%s push: asset %d failed: %s',+ $row->source,+ $asset->id,+ SyncErrorFormatter::summary($e),+ ), SyncErrorFormatter::logContext($e));}- } catch (\Throwable $e) {- $errors++;- // Log the sanitized summary (short) plus,- // for HTTP client exceptions, the raw- // response body truncated to 2KB so vendor- // errors like "missing required field- // 'query'" or "gitops mode requires spec"- // surface in the log even when the vendor's- // JSON shape isn't one the summary- // extractor recognizes.- Log::channel('sync-adapters')->warning(sprintf(- '%s push: asset %d failed: %s',- $row->source,- $asset->id,- SyncErrorFormatter::summary($e),- ), SyncErrorFormatter::logContext($e));}- }- });- } catch (\Throwable $e) {- Log::channel('sync-adapters')->warning(- sprintf('%s push aborted: %s', $instance->slug, SyncErrorFormatter::summary($e)),- SyncErrorFormatter::logContext($e),- );-- $abortedRedirect = redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])- ->with('error', trans('admin/settings/sync_adapters.push_failed', [- 'summary' => SyncErrorFormatter::summary($e),- ]));+ });+ } catch (\Throwable $e) {+ Log::channel('sync-adapters')->warning(+ sprintf('%s push aborted: %s', $instance->slug, SyncErrorFormatter::summary($e)),+ SyncErrorFormatter::logContext($e),+ );++ $abortedRedirect = redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with('error', trans('admin/settings/sync_adapters.push_failed', [+ 'summary' => SyncErrorFormatter::summary($e),+ ]));+ }+ });++ if ($abortedRedirect !== null) {+ return $abortedRedirect;}- });- if ($abortedRedirect !== null) {- return $abortedRedirect;+ // at least one push, no failures -> success (green)+ // at least one push, some failures -> warning (orange, admin should check log)+ // no pushes, at least one failure -> error (red)+ // no pushes AND no failures (every row skipped) -> error too, since the+ // button did nothing meaningful and the admin should know+ // nothing to iterate at all (no matching external_sources) -> warning+ // Message includes skipped count so admins see the full breakdown.+ $flashType = match (true) {+ $pushed > 0 && $errors === 0 => 'success',+ $pushed > 0 && $errors > 0 => 'warning',+ $errors > 0 => 'error',+ $skipped > 0 => 'error',+ default => 'warning',+ };++ // Same session-persistent download link affordance as the pull+ // path - captureSyncRunLog() has already put() the token under+ // sync_run_log_last_token, so the panel renders the link until+ // either (a) the next sync/push run purges this cache entry,+ // or (b) the download endpoint consumes it, or (c) the 10-min+ // TTL fires.+ return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])+ ->with($flashType, trans('admin/settings/sync_adapters.push_complete', [+ 'count' => $pushed,+ 'skipped' => $skipped,+ 'errors' => $errors,+ ]));+ } finally {+ $this->releaseOperationLock($instance->lockKey());}-- // at least one push, no failures -> success (green)- // at least one push, some failures -> warning (orange, admin should check log)- // no pushes, at least one failure -> error (red)- // no pushes AND no failures (every row skipped) -> error too, since the- // button did nothing meaningful and the admin should know- // nothing to iterate at all (no matching external_sources) -> warning- // Message includes skipped count so admins see the full breakdown.- $flashType = match (true) {- $pushed > 0 && $errors === 0 => 'success',- $pushed > 0 && $errors > 0 => 'warning',- $errors > 0 => 'error',- $skipped > 0 => 'error',- default => 'warning',- };-- // Same session-persistent download link affordance as the pull- // path - captureSyncRunLog() has already put() the token under- // sync_run_log_last_token, so the panel renders the link until- // either (a) the next sync/push run purges this cache entry,- // or (b) the download endpoint consumes it, or (c) the 10-min- // TTL fires.- return redirect()->route('settings.adapters.index', ['adapter' => $instance->slug])- ->with($flashType, trans('admin/settings/sync_adapters.push_complete', [- 'count' => $pushed,- 'skipped' => $skipped,- 'errors' => $errors,- ]));}/**diff --git a/app/Http/Controllers/Users/LDAPImportController.php b/app/Http/Controllers/Users/LDAPImportController.phpindex 74345f9fb7..23d93e0e5f 100644--- a/app/Http/Controllers/Users/LDAPImportController.php+++ b/app/Http/Controllers/Users/LDAPImportController.php@@ -2,7 +2,9 @@namespace App\Http\Controllers\Users;+use App\Console\Commands\LdapSync;use App\Http\Controllers\Controller;+use App\Traits\LocksLongRunningOperation;use Illuminate\Auth\Access\AuthorizationException;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;@@ -13,6 +15,8 @@ use Illuminate\Support\Facades\Artisan;class LDAPImportController extends Controller{+ use LocksLongRunningOperation;+/*** Return view for LDAP import.*@@ -35,7 +39,13 @@ class LDAPImportController extends Controllerabort(403);}- return view('users/ldap');+ // Belt-and-suspenders UI for the shared LDAP sync lock.+ // The command itself refuses a concurrent trigger, this just+ // stops the admin from clicking a button that will immediately+ // fail.+ $ldapSyncRunning = $this->isOperationLocked(LdapSync::LDAP_SYNC_LOCK);++ return view('users/ldap', compact('ldapSyncRunning'));}/**diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.phpindex 3d5a0c3cb7..e95f68b40e 100644--- a/app/Livewire/Importer.php+++ b/app/Livewire/Importer.php@@ -19,6 +19,7 @@ use App\Models\Manufacturer;use App\Models\Setting;use App\Models\Supplier;use App\Models\User;+use App\Traits\LocksLongRunningOperation;use Illuminate\Support\Facades\Storage;use League\Csv\Reader;use Livewire\Attributes\Computed;@@ -28,6 +29,7 @@ use Livewire\WithPagination;class Importer extends Component{+ use LocksLongRunningOperation;use WithPagination;// How many import files to show per page. Not currently user-configurable;@@ -969,6 +971,27 @@ class Importer extends Componentreturn;}+ // Per-file mutex. Two admins (or two tabs) trying to process+ // the SAME file concurrently would double-insert rows and race+ // the slice index. Different files stay independent because+ // the key is scoped by file id. The lock persists across all+ // per-slice API POSTs until stopProcessing() releases it, or+ // the 30-min TTL expires if the admin abandons the page+ // mid-run.+ $file = Import::find($this->activeFileId);+ if ($file === null) {+ $this->message = trans('general.file_not_found');+ $this->message_type = 'danger';++ return;+ }+ if (! $this->acquireOperationLock($file->lockKey())) {+ $this->message = $this->operationAlreadyRunningMessage('general.import');+ $this->message_type = 'danger';++ return;+ }+$this->processing = true;$this->progress = 0;$this->progress_bar_class = 'progress-bar-warning';@@ -1001,6 +1024,15 @@ class Importer extends Componentpublic function stopProcessing(): void{$this->processing = false;++ // Release the per-file mutex acquired in startProcessing().+ // Called by the slice-driver JS on either successful completion+ // or any slice failure, so the lock clears whether the run+ // finished or bailed early.+ $file = Import::find($this->activeFileId);+ if ($file !== null) {+ $this->releaseOperationLock($file->lockKey());+ }}/**diff --git a/app/Models/Import.php b/app/Models/Import.phpindex 5a1b1bd387..136785b897 100644--- a/app/Models/Import.php+++ b/app/Models/Import.php@@ -32,4 +32,15 @@ class Import extends Model{return $this->belongsTo(User::class, 'created_by')->withTrashed();}++ /**+ * Shared mutex key for an in-flight import of this specific file. Scoped by+ * file id so different files can be processed in parallel: admin A+ * importing accessories.csv does not block admin B importing+ * assets-batch-2.csv. Same file can't be processed concurrently.+ */+ public function lockKey(): string+ {+ return 'import:'.$this->id.':running';+ }}diff --git a/app/Models/SyncAdapterInstance.php b/app/Models/SyncAdapterInstance.phpindex cc394ec047..cb0c5097c2 100644--- a/app/Models/SyncAdapterInstance.php+++ b/app/Models/SyncAdapterInstance.php@@ -62,6 +62,19 @@ class SyncAdapterInstance extends Modelreturn SyncAdapter::factory($this);}+ /**+ * Shared mutex key for an in-flight sync operation on this+ * instance. Pull and Push on the same instance acquire the same+ * key, so one blocks the other, but Fleet pulling doesn't block+ * Jamf pulling. CLI (snipeit:pull-inventory / snipeit:push-inventory)+ * and the UI controller methods both acquire via this key, so cron+ * + admin click can't collide on the same vendor.+ */+ public function lockKey(): string+ {+ return 'sync-adapter:'.$this->slug.':running';+ }+private static function generateUniqueSlug(string $label): string{$base = Str::slug($label);diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.phpindex 48d1c17305..2afd8c2051 100644--- a/app/SyncAdapters/SyncAdapter.php+++ b/app/SyncAdapters/SyncAdapter.php@@ -490,6 +490,16 @@ abstract class SyncAdapterreturn $this->instance->label;}+ /**+ * Public accessor for the backing instance. Blade views that need to+ * reason about per-instance state (lock keys, mapping tables, etc)+ * use through this vs relying on the protected constructor property.+ */+ public function instance(): SyncAdapterInstance+ {+ return $this->instance;+ }+public function companyId(): ?int{return $this->instance->company_id;diff --git a/app/Traits/LocksLongRunningOperation.php b/app/Traits/LocksLongRunningOperation.phpnew file mode 100644index 0000000000..9325c288f7--- /dev/null+++ b/app/Traits/LocksLongRunningOperation.php@@ -0,0 +1,67 @@+<?php++namespace App\Traits;++use Illuminate\Support\Facades\Cache;++/**+ * Shared cache-backed mutex for long-running operations that must not+ * overlap: backup, restore, LDAP sync, import, sync-adapter pulls.+ *+ * These operations have no job queue in Snipe-IT today, they+ * run synchronously inside the request/response cycle (or the Artisan+ * command). The mutex refuses the second trigger before the operation+ * body runs.+ *+ * The lock lives in the file cache store specifically (not the+ * configured default). This is deliberate: a restore wipes the+ * database as part of its work, and installs that set `CACHE_STORE` to+ * `database` would lose the lock mid-restore if we used the default+ * store. The file store survives `db:wipe` and lets the mutex outlive+ * the operation it's protecting.+ *+ * The file store is also shared across the web PHP process and the CLI+ * PHP process on a standard install (same filesystem path, same+ * process user).+ *+ * TTL on the lock is the automatic recovery for the "process died+ * without releasing" case (SIGKILL, OOM, Apache mod_reap). 30 minutes+ * is the shared default. Individual callers can override when their+ * operation is reasonably expected to run longer (restore + database+ * reload on a large install, for example). Admins recovering from a+ * stuck lock before the TTL expires can run `php artisan cache:clear`.+ *+ * The TTL being 30 minutes is largely for the CLI end of things, since the+ * web UI will die long before then and lead to a gateway timeout.+ * The CLI end of things is more likely to be long-running (LDAP sync, restore, etc).+ */+trait LocksLongRunningOperation+{+ protected function acquireOperationLock(string $key, int $ttlMinutes = 30): bool+ {+ return Cache::store('file')->add($key, true, now()->addMinutes($ttlMinutes));+ }++ protected function releaseOperationLock(string $key): void+ {+ Cache::store('file')->forget($key);+ }++ protected function isOperationLocked(string $key): bool+ {+ return Cache::store('file')->has($key);+ }++ /**+ * Return the translated "already in progress" message with the+ * operation's own label substituted in. One parameterized string+ * covers every lock in the system so we don't ship per-operation+ * copies that translators have to localize separately.+ */+ protected function operationAlreadyRunningMessage(string $operationLabelKey): string+ {+ return trans('general.operation_already_running', [+ 'operation' => trans($operationLabelKey),+ ]);+ }+}diff --git a/resources/lang/en-US/admin/settings/general.php b/resources/lang/en-US/admin/settings/general.phpindex beb4fffc46..a6d737e75c 100644--- a/resources/lang/en-US/admin/settings/general.php+++ b/resources/lang/en-US/admin/settings/general.php@@ -30,7 +30,7 @@ return ['auto_increment_assets' => 'Generate auto-incrementing asset tags','auto_increment_prefix' => 'Prefix (optional)','auto_incrementing_help' => 'Enable auto-incrementing asset tags first to set this',- 'backups' => 'Backups',+ 'backups' => 'Backups & Restore','backups_help' => 'Create, download, and restore backups ','backups_restoring' => 'Restoring from Backup','backups_clean' => 'Clean the backed-up database before restore',diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 74470700e2..7cfccb6c22 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -14,6 +14,7 @@ return ['push_nothing_configured' => 'Push aborted: no fields on the mapping table are directed "Push to vendor" and no composed-notes template is configured. Set at least one before hitting Push Now.','not_configured' => 'This adapter has not been configured yet.','sync_complete' => 'Sync complete. Synced :count host(s), :skipped skipped, :errors error(s).',+ 'sync_adapter_run' => 'This sync adapter run','sync_failed' => 'Sync failed: :summary. See storage/logs/sync-adapters.log for full details.','sync_failed_network' => 'network error','last_synced_label' => 'Last Successful Sync',diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.phpindex b0bbacb8cd..35bac78607 100644--- a/resources/lang/en-US/general.php+++ b/resources/lang/en-US/general.php@@ -542,6 +542,8 @@ return ['ldap_user_sync' => 'LDAP User Sync','synchronize' => 'Synchronize','sync_results' => 'Synchronization Results',+ 'backup_or_restore' => 'Backup or Restore',+ 'operation_already_running' => ':operation is already in progress. Please wait for it to complete before starting another.','license_serial' => 'Serial/Product Key','invalid_category' => 'Invalid or missing category','invalid_item_category_single' => 'Invalid or missing :type category. Please update the category of this :type to include a valid category before checking out.',diff --git a/resources/views/blade/sync-adapter/panel.blade.php b/resources/views/blade/sync-adapter/panel.blade.phpindex ef2693a3bf..806fc0eaf9 100644--- a/resources/views/blade/sync-adapter/panel.blade.php+++ b/resources/views/blade/sync-adapter/panel.blade.php@@ -9,7 +9,11 @@@php$slug = $adapter->name();$locked = config('app.lock_passwords') === true;- $canSync = $adapter->isEnabled() && ! $locked;+ // Per-instance mutex read: a Pull or Push in flight for this+ // adapter holds the key, so the buttons go disabled with a tooltip+ // until it clears. Server rejects duplicate triggers regardless.+ $runInProgress = \Illuminate\Support\Facades\Cache::store('file')->has($adapter->instance()->lockKey());+ $canSync = $adapter->isEnabled() && ! $locked && ! $runInProgress;// Download-link gating. We render the link only when BOTH the// persistent session pointer AND the cache entry it points at are@@ -127,15 +131,17 @@class="js-sync-dry-run-mirror"data-mirrors="{{ $slug }}_pull_dry_run">- <button- type="submit"- class="btn btn-primary js-sync-action-button"- data-dirty-guarded-by="adapter-form-{{ $slug }}"- @disabled(! $canSync)- >- <i class="fa-solid fa-cloud-arrow-down js-sync-action-icon" aria-hidden="true"></i>- <span class="js-sync-action-label">{{ trans('admin/settings/sync_adapters.pull_now') }}</span>- </button>+ <span @if ($runInProgress) data-tooltip="true" title="{{ trans('general.operation_already_running', ['operation' => trans('admin/settings/sync_adapters.sync_adapter_run')]) }}" @endif>+ <button+ type="submit"+ class="btn btn-primary js-sync-action-button"+ data-dirty-guarded-by="adapter-form-{{ $slug }}"+ @disabled(! $canSync)+ >+ <i class="fa-solid fa-cloud-arrow-down js-sync-action-icon" aria-hidden="true"></i>+ <span class="js-sync-action-label">{{ trans('admin/settings/sync_adapters.pull_now') }}</span>+ </button>+ </span></form>@if ($adapter instanceof \App\SyncAdapters\PushableAdapter && $adapter->canPush())@@ -154,15 +160,17 @@class="js-sync-dry-run-mirror"data-mirrors="{{ $slug }}_push_dry_run">- <button- type="submit"- class="btn btn-default js-sync-action-button"- data-dirty-guarded-by="adapter-form-{{ $slug }}"- @disabled(! $canSync)- >- <i class="fa-solid fa-cloud-arrow-up js-sync-action-icon" aria-hidden="true"></i>- <span class="js-sync-action-label">{{ trans('admin/settings/sync_adapters.push_now') }}</span>- </button>+ <span @if ($runInProgress) data-tooltip="true" title="{{ trans('general.operation_already_running', ['operation' => trans('admin/settings/sync_adapters.sync_adapter_run')]) }}" @endif>+ <button+ type="submit"+ class="btn btn-default js-sync-action-button"+ data-dirty-guarded-by="adapter-form-{{ $slug }}"+ @disabled(! $canSync)+ >+ <i class="fa-solid fa-cloud-arrow-up js-sync-action-icon" aria-hidden="true"></i>+ <span class="js-sync-action-label">{{ trans('admin/settings/sync_adapters.push_now') }}</span>+ </button>+ </span></form>@endifdiff --git a/resources/views/settings/backups.blade.php b/resources/views/settings/backups.blade.phpindex 4b59f128aa..008474fd10 100644--- a/resources/views/settings/backups.blade.php+++ b/resources/views/settings/backups.blade.php@@ -9,9 +9,12 @@@section('header_right')<form method="POST" action="{{ route('settings.backups.create') }}" style="display: inline">@csrf- <button class="btn btn-primary" data-safety-timeout-ms="300000" @disabled(config('app.lock_passwords'))>- {{ trans('admin/settings/general.generate_backup') }}- </button>+ {{-- Disabled when the shared backup+restore mutex is open. --}}+ <span @if ($backupRestoreRunning) data-tooltip="true" title="{{ trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]) }}" @endif>+ <button type="submit" class="btn btn-primary" data-safety-timeout-ms="300000" @disabled(config('app.lock_passwords') || $backupRestoreRunning)>+ {{ trans('admin/settings/general.generate_backup') }}+ </button>+ </span></form>@stop@@ -19,6 +22,12 @@{{-- Page content --}}@section('content')+ @if ($backupRestoreRunning)+ <x-callout type="warning" icon="warning" live="assertive">+ {{ trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]) }}+ </x-callout>+ @endif+<div class="modal modal-warning fade" tabindex="-1" role="dialog" id="backupRestoreModal"><div class="modal-dialog" role="document"><div class="modal-content">@@ -116,15 +125,17 @@</span>@endif- <button type="button"- class="btn btn-warning btn-sm restore-backup"- data-href="{{ route('settings.backups.restore', $file['filename']) }}"- data-target="#backupRestoreModal"- data-title="{{ trans('admin/settings/message.backup.restore_confirm', ['filename' => e($file['filename'])]) }}"- @disabled(config('app.lock_passwords'))>- <x-icon type="restore" />- <span class="sr-only">{{ trans('general.restore') }}</span>- </button>+ <span @if ($backupRestoreRunning) data-tooltip="true" title="{{ trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]) }}" @endif>+ <button type="button"+ class="btn btn-warning btn-sm restore-backup"+ data-href="{{ route('settings.backups.restore', $file['filename']) }}"+ data-target="#backupRestoreModal"+ data-title="{{ trans('admin/settings/message.backup.restore_confirm', ['filename' => e($file['filename'])]) }}"+ @disabled(config('app.lock_passwords') || $backupRestoreRunning)>+ <x-icon type="restore"/>+ <span class="sr-only">{{ trans('general.restore') }}</span>+ </button>+ </span>@endcan</td></tr>diff --git a/resources/views/users/ldap.blade.php b/resources/views/users/ldap.blade.phpindex 404d23e32f..9916170646 100644--- a/resources/views/users/ldap.blade.php+++ b/resources/views/users/ldap.blade.php@@ -12,6 +12,12 @@@if ($snipeSettings->ldap_enabled == 0){{ trans('admin/users/message.ldap_not_configured') }}@else+ @if ($ldapSyncRunning)+ <x-callout type="warning" icon="warning" live="assertive">+ {{ trans('general.operation_already_running', ['operation' => trans('general.ldap_sync')]) }}+ </x-callout>+ @endif+<x-form id="ldap-form"><x-box><x-callout type="legend" icon="tip" class="col-md-12">@@ -19,7 +25,7 @@<strong>{!! trans('admin/users/general.ldap_sync_intro', ['link' => 'https://snipe-it.readme.io/docs/ldap-sync#/']) !!}</strong>-+</x-callout><x-input.location-select@@ -37,10 +43,12 @@<a class="btn btn-link" href="{{ route('users.index') }}">{{ trans('button.cancel') }}</a></div><div class="text-right col-md-6">- <x-input.button class="btn-primary" id="sync">- <i id="sync-button-icon" class="fas fa-sync-alt icon-white" aria-hidden="true"></i>- <span id="sync-button-text">{{ trans('general.synchronize') }}</span>- </x-input.button>+ <span @if ($ldapSyncRunning) data-tooltip="true" title="{{ trans('general.operation_already_running', ['operation' => trans('general.ldap_sync')]) }}" @endif>+ <button type="submit" class="btn btn-primary" id="sync" @disabled($ldapSyncRunning)>+ <i id="sync-button-icon" class="fas fa-sync-alt icon-white" aria-hidden="true"></i>+ <span id="sync-button-text">{{ trans('general.synchronize') }}</span>+ </button>+ </span></div></div></x-slot:customfooter>diff --git a/tests/Feature/Livewire/ImporterMutexTest.php b/tests/Feature/Livewire/ImporterMutexTest.phpnew file mode 100644index 0000000000..7ee887fe31--- /dev/null+++ b/tests/Feature/Livewire/ImporterMutexTest.php@@ -0,0 +1,89 @@+<?php++namespace Tests\Feature\Livewire;++use App\Livewire\Importer;+use App\Models\Import;+use App\Models\User;+use Illuminate\Support\Facades\Cache;+use Livewire\Livewire;+use Tests\TestCase;++/**+ * Regression coverage for the per-file import mutex. Two admins (or+ * two tabs) attempting to process the SAME import file concurrently+ * would double-insert rows and race the slice index that drives the+ * per-slice API POSTs. Different files stay independent because the+ * key is scoped by file id.+ */+class ImporterMutexTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ $this->flushImportLocks();+ }++ protected function tearDown(): void+ {+ $this->flushImportLocks();+ parent::tearDown();+ }++ private function flushImportLocks(): void+ {+ foreach (Import::query()->pluck('id') as $id) {+ Cache::store('file')->forget('import:'.$id.':running');+ }+ }++ public function test_start_processing_is_rejected_when_the_files_lock_is_held(): void+ {+ $this->actingAs(User::factory()->superuser()->create());+ $file = Import::factory()->create();++ Cache::store('file')->put($file->lockKey(), true, now()->addMinutes(30));++ $component = Livewire::test(Importer::class)+ ->set('activeFileId', $file->id)+ ->call('startProcessing');++ $component->assertSet('processing', false);+ $component->assertSet('message_type', 'danger');+ $component->assertSet('message', trans('general.operation_already_running', [+ 'operation' => trans('general.import'),+ ]));+ }++ public function test_locks_are_scoped_per_file_so_a_second_file_can_still_start(): void+ {+ $this->actingAs(User::factory()->superuser()->create());+ [$fileA, $fileB] = Import::factory()->count(2)->create();++ Cache::store('file')->put($fileA->lockKey(), true, now()->addMinutes(30));++ $component = Livewire::test(Importer::class)+ ->set('activeFileId', $fileB->id)+ ->call('startProcessing');++ $component->assertSet('processing', true);+ $this->assertTrue(Cache::store('file')->has($fileA->lockKey()));+ $this->assertTrue(Cache::store('file')->has($fileB->lockKey()));+ }++ public function test_stop_processing_releases_the_lock(): void+ {+ $this->actingAs(User::factory()->superuser()->create());+ $file = Import::factory()->create();++ $component = Livewire::test(Importer::class)+ ->set('activeFileId', $file->id)+ ->call('startProcessing');++ $this->assertTrue(Cache::store('file')->has($file->lockKey()));++ $component->call('stopProcessing');++ $this->assertFalse(Cache::store('file')->has($file->lockKey()));+ }+}diff --git a/tests/Feature/Livewire/ImporterTest.php b/tests/Feature/Livewire/ImporterTest.phpindex c2ffe04620..b2789fbb49 100644--- a/tests/Feature/Livewire/ImporterTest.php+++ b/tests/Feature/Livewire/ImporterTest.php@@ -677,9 +677,11 @@ class ImporterTest extends TestCaseconfig(['app.lock_passwords' => true]);$user = User::factory()->canImport()->superuser()->create();+ $file = Import::factory()->create();Livewire::actingAs($user)->test(Importer::class)+ ->set('activeFileId', $file->id)->call('startProcessing')->assertSet('processing', true);}diff --git a/tests/Feature/Settings/BackupRestoreMutexTest.php b/tests/Feature/Settings/BackupRestoreMutexTest.phpnew file mode 100644index 0000000000..9fc15591d1--- /dev/null+++ b/tests/Feature/Settings/BackupRestoreMutexTest.php@@ -0,0 +1,86 @@+<?php++namespace Tests\Feature\Settings;++use App\Models\User;+use Illuminate\Support\Facades\Artisan;+use Illuminate\Support\Facades\Cache;+use Tests\TestCase;+++class BackupRestoreMutexTest extends TestCase+{+ private const LOCK_KEY = 'backup-restore:running';++ protected function setUp(): void+ {+ parent::setUp();+ Cache::store('file')->forget(self::LOCK_KEY);+ }++ protected function tearDown(): void+ {+ Cache::store('file')->forget(self::LOCK_KEY);+ parent::tearDown();+ }++ public function test_backup_is_rejected_when_the_lock_is_already_held(): void+ {+ Artisan::spy();+ Cache::store('file')->put(self::LOCK_KEY, true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.backups.create'))+ ->assertSessionHas('error', trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]));++ Artisan::shouldNotHaveReceived('call', function ($command) {+ return $command === 'snipeit:backup';+ });+ }++ public function test_restore_is_rejected_when_the_lock_is_already_held(): void+ {+ Artisan::spy();+ Cache::store('file')->put(self::LOCK_KEY, true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.backups.restore', 'latest-manual-backup-2026-01-01-00-00-00.zip'))+ ->assertSessionHas('error', trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]));++ Artisan::shouldNotHaveReceived('call', function ($command) {+ return in_array($command, ['snipeit:restore', 'db:wipe'], true);+ });+ }++ public function test_backup_releases_the_lock_after_the_artisan_call_returns(): void+ {+ Artisan::spy();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.backups.create'));++ $this->assertFalse(+ Cache::store('file')->has(self::LOCK_KEY),+ 'postBackups must release the shared backup+restore lock after Artisan returns.'+ );+ }++ public function test_backups_index_exposes_the_running_state_to_the_view(): void+ {+ Cache::store('file')->put(self::LOCK_KEY, true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('settings.backups.index'))+ ->assertOk()+ ->assertViewHas('backupRestoreRunning', true)+ ->assertSee(trans('general.operation_already_running', ['operation' => trans('general.backup_or_restore')]));+ }++ public function test_backups_index_reports_running_false_when_the_lock_is_absent(): void+ {+ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('settings.backups.index'))+ ->assertOk()+ ->assertViewHas('backupRestoreRunning', false);+ }+}diff --git a/tests/Feature/SyncAdapters/SyncAdapterMutexTest.php b/tests/Feature/SyncAdapters/SyncAdapterMutexTest.phpnew file mode 100644index 0000000000..534bc66726--- /dev/null+++ b/tests/Feature/SyncAdapters/SyncAdapterMutexTest.php@@ -0,0 +1,86 @@+<?php++namespace Tests\Feature\SyncAdapters;++use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Models\User;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Crypt;+use Tests\TestCase;+++class SyncAdapterMutexTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ $this->flushAllInstanceLocks();+ }++ protected function tearDown(): void+ {+ $this->flushAllInstanceLocks();+ parent::tearDown();+ }++ private function flushAllInstanceLocks(): void+ {+ foreach (SyncAdapterInstance::query()->pluck('slug') as $slug) {+ Cache::store('file')->forget('sync-adapter:'.$slug.':running');+ }+ }++ private function configuredFleet(): SyncAdapterInstance+ {+ $instance = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();+ $instance->active = true;+ $instance->save();+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/fleet');+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));++ return $instance->fresh();+ }++ public function test_ui_pull_is_rejected_when_the_instance_lock_is_held(): void+ {+ $fleet = $this->configuredFleet();+ Cache::store('file')->put($fleet->lockKey(), true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.adapters.sync', $fleet))+ ->assertSessionHas('error', trans('general.operation_already_running', [+ 'operation' => trans('admin/settings/sync_adapters.sync_adapter_run'),+ ]));+ }++ public function test_locks_are_scoped_per_instance_so_a_second_adapter_can_still_run(): void+ {+ // Lock fleet, trigger jamf. Jamf should proceed past the lock+ // gate (it may fail later for other config reasons, but the+ // mutex itself should NOT reject it).+ $fleet = $this->configuredFleet();+ $jamf = SyncAdapterInstance::where('slug', 'jamf')->firstOrFail();+ Cache::store('file')->put($fleet->lockKey(), true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.adapters.sync', $jamf))+ ->assertSessionMissing('error', trans('general.operation_already_running', [+ 'operation' => trans('admin/settings/sync_adapters.sync_adapter_run'),+ ]));++ // Fleet lock still held, Jamf lock was not permanently set+ // (released by the finally after whatever Jamf's path did).+ $this->assertTrue(Cache::store('file')->has($fleet->lockKey()));+ $this->assertFalse(Cache::store('file')->has($jamf->lockKey()));+ }++ public function test_cli_pull_skips_with_success_exit_when_the_instance_lock_is_held(): void+ {+ $fleet = $this->configuredFleet();+ Cache::store('file')->put($fleet->lockKey(), true, now()->addMinutes(30));++ $this->artisan('snipeit:pull-inventory', ['adapter' => 'fleet'])+ ->assertExitCode(0);+ }+}diff --git a/tests/Feature/Users/LdapSyncMutexTest.php b/tests/Feature/Users/LdapSyncMutexTest.phpnew file mode 100644index 0000000000..2e03da9518--- /dev/null+++ b/tests/Feature/Users/LdapSyncMutexTest.php@@ -0,0 +1,76 @@+<?php++namespace Tests\Feature\Users;++use App\Console\Commands\LdapSync;+use App\Models\User;+use Illuminate\Support\Facades\Artisan;+use Illuminate\Support\Facades\Cache;+use Tests\TestCase;+++class LdapSyncMutexTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Cache::store('file')->forget(LdapSync::LDAP_SYNC_LOCK);+ }++ protected function tearDown(): void+ {+ Cache::store('file')->forget(LdapSync::LDAP_SYNC_LOCK);+ parent::tearDown();+ }++ public function test_cli_sync_is_rejected_when_the_lock_is_already_held(): void+ {+ $this->settings->set(['ldap_enabled' => '1']);+ Cache::store('file')->put(LdapSync::LDAP_SYNC_LOCK, true, now()->addMinutes(30));++ $this->artisan('snipeit:ldap-sync')+ ->expectsOutput(trans('general.operation_already_running', ['operation' => trans('general.ldap_sync')]))+ ->assertExitCode(1);+ }++ public function test_cli_sync_in_json_mode_returns_already_running_as_json_payload(): void+ {+ $this->settings->set(['ldap_enabled' => '1']);+ Cache::store('file')->put(LdapSync::LDAP_SYNC_LOCK, true, now()->addMinutes(30));++ $exitCode = Artisan::call('snipeit:ldap-sync', ['--json_summary' => true]);+ $output = Artisan::output();++ $this->assertSame(1, $exitCode);+ $decoded = json_decode(trim($output), true);+ $this->assertIsArray($decoded);+ $this->assertTrue($decoded['error']);+ $this->assertSame(+ trans('general.operation_already_running', ['operation' => trans('general.ldap_sync')]),+ $decoded['error_message']+ );+ $this->assertSame([], $decoded['summary']);+ }++ public function test_ui_sync_page_exposes_running_state_to_the_view(): void+ {+ $this->settings->set(['ldap_enabled' => '1']);+ Cache::store('file')->put(LdapSync::LDAP_SYNC_LOCK, true, now()->addMinutes(30));++ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('ldap/user'))+ ->assertOk()+ ->assertViewHas('ldapSyncRunning', true)+ ->assertSee(trans('general.operation_already_running', ['operation' => trans('general.ldap_sync')]));+ }++ public function test_ui_sync_page_reports_running_false_when_the_lock_is_absent(): void+ {+ $this->settings->set(['ldap_enabled' => '1']);++ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('ldap/user'))+ ->assertOk()+ ->assertViewHas('ldapSyncRunning', false);+ }+}