shmSize = intval(getenv('GOOGLE_CLOUD_BATCH_SHM_SIZE')); if ($this->shmSize === 0) { $this->shmSize = self::DEFAULT_SHM_SIZE; } $this->perm = octdec(getenv('GOOGLE_CLOUD_BATCH_PERM')); if ($this->perm === 0) { $this->perm = self::DEFAULT_PERM; } $this->project = getenv('GOOGLE_CLOUD_BATCH_PROJECT'); if ($this->project === false) { $this->project = self::DEFAULT_PROJECT; } $this->sysvKey = ftok(__FILE__, $this->project); $this->semid = sem_get($this->sysvKey, 1, $this->perm, 1); } /** * Acquire a lock. * * @return bool */ public function lock() { return sem_acquire($this->semid); } /** * Release a lock. * * @return bool */ public function unlock() { return sem_release($this->semid); } /** * Save the given JobConfig. * * @param JobConfig $config A JobConfig to save. * @return bool * @throws \RuntimeException when failed to attach to the shared memory or serialization fails */ public function save(\DeliciousBrains\WP_Offload_Media\Gcp\Google\Cloud\Core\Batch\JobConfig $config) { $shmid = shm_attach($this->sysvKey, $this->shmSize, $this->perm); if ($shmid === false) { throw new \RuntimeException('Failed to attach to the shared memory'); } // If the variable write fails, clear the memory and re-raise the exception try { $result = shm_put_var($shmid, self::VAR_KEY, $config); } catch (\Exception $e) { $this->clear(); throw new \RuntimeException($e->getMessage()); } finally { shm_detach($shmid); } return $result; } /** * Load a JobConfig from the storage. * * @return JobConfig * @throws \RuntimeException when failed to attach to the shared memory or deserialization fails */ public function load() { $shmid = shm_attach($this->sysvKey, $this->shmSize, $this->perm); if ($shmid === false) { throw new \RuntimeException('Failed to attach to the shared memory'); } if (!shm_has_var($shmid, self::VAR_KEY)) { $result = new \DeliciousBrains\WP_Offload_Media\Gcp\Google\Cloud\Core\Batch\JobConfig(); } else { $result = shm_get_var($shmid, self::VAR_KEY); } shm_detach($shmid); if ($result === false) { throw new \RuntimeException('Failed to deserialize data from shared memory'); } return $result; } /** * Clear the JobConfig from storage. */ public function clear() { $shmid = shm_attach($this->sysvKey, $this->shmSize, $this->perm); shm_remove_var($shmid, self::VAR_KEY); } }