From a5a4bc6e64857ffc6881b88ee27f33593fca7f20 Mon Sep 17 00:00:00 2001 From: Steve Sutton Date: Tue, 4 Jun 2019 10:56:06 -0400 Subject: [PATCH] Add glmLock trait Trait to use for locking processes. --- classes/glmLockTrait.php | 57 ++++++++++++++++++++++++++++++++++++++++ index.php | 3 +++ 2 files changed, 60 insertions(+) create mode 100644 classes/glmLockTrait.php diff --git a/classes/glmLockTrait.php b/classes/glmLockTrait.php new file mode 100644 index 00000000..71c7d5a3 --- /dev/null +++ b/classes/glmLockTrait.php @@ -0,0 +1,57 @@ + 'defaultLockName', + 'timeout' => 30, + 'wait' => false, + ); + $config = array_merge( $defaultConfig, $config ); + + // Check for currently running process + $myId = rand(); + + // Try to get any current DB Lock + $lockName = $config['lockName']; + $lock = get_option( $lockName ); + + // If another instance is doing a database update + // (If we got something back that's a 2 el array that doesn't have my ID and hasn't expired) + if ( $lock && is_array( $lock ) && count( $lock ) == 2 && $lock[0] != $myId && $lock[1] > microtime( true ) ) { + trigger_error('GlmLock::requestLock() - Lock Name: '.$config['lockName'].' - Instance: '.$myId.'. - Another instance is processing', E_USER_NOTICE ); + return false; + } else { + trigger_error('GlmLock::requestLock() - Lock Name: '.$config['lockName'].' - Instance: '.$myId.' - This instance trying to lock', E_USER_NOTICE ); + + // Add our ID and timeout then wait a second + add_option( $lockName, array( $myId, ( microtime( true ) + $config['timeout'] ) ) ); + sleep( 1 ); + + // Make sure this instance has the lock + $lock = get_option( $lockName ); + if ( $lock && is_array( $lock ) && count( $lock ) == 2 && $lock[0] == $myId && $lock[1] > microtime( true ) ) { + return $lock; + } else { + return false; + } + } + + return $lock; + } + + public function requestUnLock( $config ) + { + // Setup Default config + $defaultConfig = array( + 'lockName' => 'defaultLockName', + ); + $config = array_merge( $defaultConfig, $config ); + + delete_option( $config['lockName'] ); + trigger_error('GlmLock::requestUnLock() - Lock Name: '.$config['lockName'].' - Removed', E_USER_NOTICE ); + } +} diff --git a/index.php b/index.php index 5a37a4d0..1c38dd52 100755 --- a/index.php +++ b/index.php @@ -361,6 +361,9 @@ require_once GLM_MEMBERS_PLUGIN_PATH . '/lib/smartyTemplateSupport.php'; // Load Script and Style Registry require_once GLM_MEMBERS_PLUGIN_PATH . '/classes/scriptRegistry.php'; +// Load GlmLock Trait +require_once GLM_MEMBERS_PLUGIN_PATH . '/classes/glmLockTrait.php'; + // Check all database tables for all registered add-ons, allow install/update, and add various items if (glmCheckDatabase('install')) { -- 2.17.1