Implementeer RedisTaskStorage en andere features (#4)
Add 'addTasks' method to `Tasks` class Implemented basic RedisTaskStorage. - Fixed bug where worker is not provided with bootstrap by ShellExecutor. - Added composer and Redis to Dockerfile - Added more output to ParallelSuperVisor Updated config format. Implemented changes to binaries. Binaries now accept a 'bootstrap' argument, allowing the developer to load a custom bootstrap from the project they're working on. This allows Async to run in the same environment as the project it's part of. Co-authored-by: Abel Hoogeveen <abel@techfuze.net> Reviewed-on: #4
This commit is contained in:
parent
d35f15114b
commit
db962e96e1
@ -3,5 +3,9 @@ FROM php:7.3-cli-buster
|
||||
RUN apt-get update &&\
|
||||
apt-get install --no-install-recommends --assume-yes --quiet procps ca-certificates curl git &&\
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
# PDO
|
||||
RUN docker-php-ext-install pdo_mysql
|
||||
|
||||
# Install Redis
|
||||
RUN pecl install redis-5.1.1 && docker-php-ext-enable redis
|
||||
|
||||
# Install Composer
|
||||
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
|
@ -40,7 +40,9 @@ use FuzeWorks\Async\Tasks;
|
||||
use FuzeWorks\Async\TasksException;
|
||||
use FuzeWorks\Exception\InvalidArgumentException;
|
||||
use FuzeWorks\Exception\LibraryException;
|
||||
use FuzeWorks\Factory;
|
||||
|
||||
// First perform a PHP version check
|
||||
if (version_compare('7.1.0', PHP_VERSION, '>')) {
|
||||
fwrite(
|
||||
STDERR,
|
||||
@ -63,35 +65,56 @@ $autoloaders = [
|
||||
];
|
||||
foreach ($autoloaders as $file)
|
||||
if (file_exists($file))
|
||||
require($file);
|
||||
require_once($file);
|
||||
|
||||
// If a bootstrap is provided, use that one
|
||||
$arguments = getopt('', ['bootstrap:']);
|
||||
if (!isset($arguments['bootstrap']) || empty($arguments['bootstrap']))
|
||||
{
|
||||
fwrite(STDERR, "Could not load supervisor. No bootstrap provided.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
|
||||
// Load the file. If it doesn't exist, fail.
|
||||
$bootstrap = $arguments['bootstrap'];
|
||||
if (!file_exists($bootstrap))
|
||||
{
|
||||
fwrite(STDERR, "Could not load supervisor. Provided bootstrap doesn't exist.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
// Load the bootstrap
|
||||
/** @var Factory $container */
|
||||
$container = require($bootstrap);
|
||||
|
||||
// Check if container is a Factory
|
||||
if (!$container instanceof Factory)
|
||||
{
|
||||
fwrite(STDERR, "Could not load supervisor. Provided bootstrap is not a valid bootstrap.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
// Check if the Async library is already loaded. If not, load it.
|
||||
// @todo: Better check in libraries for existing library
|
||||
try {
|
||||
// Open configurator
|
||||
$configurator = new FuzeWorks\Configurator();
|
||||
|
||||
// Set up basic settings
|
||||
$configurator->setTimeZone('Europe/Amsterdam');
|
||||
$configurator->setTempDirectory(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'temp');
|
||||
$configurator->setLogDirectory(dirname(__FILE__). DIRECTORY_SEPARATOR . 'log');
|
||||
|
||||
// Add Async library
|
||||
$configurator->deferComponentClassMethod('libraries', 'addLibraryClass', null, 'async', '\FuzeWorks\Async\Tasks');
|
||||
|
||||
// Debug
|
||||
$configurator->enableDebugMode()->setDebugAddress('ALL');
|
||||
|
||||
// Create container
|
||||
$container = $configurator->createContainer();
|
||||
|
||||
// RUN THE APP
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
} catch (LibraryException $e) {
|
||||
$container->libraries->addLibraryClass('async', '\FuzeWorks\Async\Tasks');
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
}
|
||||
|
||||
$supervisor = $lib->getSuperVisor();
|
||||
// And finally, run the supervisor
|
||||
try {
|
||||
$supervisor = $lib->getSuperVisor($bootstrap);
|
||||
while ($supervisor->cycle() === SuperVisor::RUNNING) {
|
||||
usleep(250000);
|
||||
}
|
||||
|
||||
// Write results
|
||||
fwrite(STDOUT, "SuperVisor finished scheduled tasks.");
|
||||
} catch (InvalidArgumentException | TasksException | LibraryException $e) {
|
||||
fwrite(STDERR, sprintf('FuzeWorks Async could not load.' . PHP_EOL .
|
||||
'Exception: ' . $e->getMessage() . PHP_EOL)
|
||||
|
125
bin/worker
Normal file
125
bin/worker
Normal file
@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* FuzeWorks Async Library
|
||||
*
|
||||
* The FuzeWorks PHP FrameWork
|
||||
*
|
||||
* Copyright (C) 2013-2020 TechFuze
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* @author TechFuze
|
||||
* @copyright Copyright (c) 2013 - 2020, TechFuze. (http://techfuze.net)
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
*
|
||||
* @link http://techfuze.net/fuzeworks
|
||||
* @since Version 1.0.0
|
||||
*
|
||||
* @version Version 1.0.0
|
||||
*/
|
||||
use FuzeWorks\Async\Tasks;
|
||||
use FuzeWorks\Async\TasksException;
|
||||
use FuzeWorks\Exception\InvalidArgumentException;
|
||||
use FuzeWorks\Exception\LibraryException;
|
||||
use FuzeWorks\Factory;
|
||||
|
||||
|
||||
// First perform a PHP version check
|
||||
if (version_compare('7.1.0', PHP_VERSION, '>')) {
|
||||
fwrite(
|
||||
STDERR,
|
||||
sprintf(
|
||||
'FuzeWorks Async requires PHP 7.1 or higher.' . PHP_EOL .
|
||||
'You are using PHP %s (%s).' . PHP_EOL,
|
||||
PHP_VERSION,
|
||||
PHP_BINARY
|
||||
)
|
||||
);
|
||||
|
||||
die(1);
|
||||
}
|
||||
|
||||
// First load composer
|
||||
$autoloaders = [
|
||||
__DIR__ . '/../../autoload.php',
|
||||
__DIR__ . '/../vendor/autoload.php',
|
||||
__DIR__ . '/vendor/autoload.php'
|
||||
];
|
||||
foreach ($autoloaders as $file)
|
||||
if (file_exists($file))
|
||||
require_once($file);
|
||||
|
||||
// If a bootstrap is provided, use that one
|
||||
$arguments = getopt('', ['bootstrap:']);
|
||||
if (!isset($arguments['bootstrap']) || empty($arguments['bootstrap']))
|
||||
{
|
||||
fwrite(STDERR, "Could not load worker. No bootstrap provided.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
|
||||
// Load the file. If it doesn't exist, fail.
|
||||
$file = $arguments['bootstrap'];
|
||||
if (!file_exists($file))
|
||||
{
|
||||
fwrite(STDERR, "Could not load worker. Provided bootstrap doesn't exist.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
// Load the bootstrap
|
||||
/** @var Factory $container */
|
||||
$container = require($file);
|
||||
|
||||
// Check if container is a Factory
|
||||
if (!$container instanceof Factory)
|
||||
{
|
||||
fwrite(STDERR, "Could not load worker. Provided bootstrap is not a valid bootstrap.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
// Check if the Async library is already loaded. If not, load it.
|
||||
// @todo: Better check in libraries for existing library
|
||||
try {
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
} catch (LibraryException $e) {
|
||||
$container->libraries->addLibraryClass('async', '\FuzeWorks\Async\Tasks');
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
}
|
||||
|
||||
// Fetch arguments for the worker
|
||||
$arguments = getopt("t:p::");
|
||||
if (!isset($arguments['t']))
|
||||
{
|
||||
fwrite(STDERR, "Could not load worker. No taskID provided.");
|
||||
die(1);
|
||||
}
|
||||
|
||||
// Prepare arguments
|
||||
$taskID = base64_decode($arguments['t']);
|
||||
$post = isset($arguments['p']);
|
||||
|
||||
// RUN THE APP
|
||||
$worker = $lib->getWorker();
|
||||
$worker->run($taskID, $post);
|
||||
|
||||
fwrite(STDOUT,'Finished task \'' . $taskID . "'");
|
||||
?>
|
@ -15,12 +15,16 @@
|
||||
"require": {
|
||||
"php": ">=7.2.0",
|
||||
"fuzeworks/core": "~1.2.0",
|
||||
"ext-json": "*"
|
||||
"ext-json": "*",
|
||||
"ext-redis": "*"
|
||||
},
|
||||
"require-dev": {
|
||||
"fuzeworks/tracycomponent": "~1.2.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"FuzeWorks\\Async\\": "src/FuzeWorks/Async"
|
||||
}
|
||||
},
|
||||
"bin": ["bin/supervisor"]
|
||||
"bin": ["bin/supervisor", "bin/worker"]
|
||||
}
|
@ -42,12 +42,30 @@ return array(
|
||||
'type' => 'ArrayTaskStorage',
|
||||
|
||||
// For ArrayTaskStorage, first parameter is the file location of the array storage
|
||||
'parameters' => [dirname(__FILE__) . DS . 'storage.php']
|
||||
'parameters' => [
|
||||
'filename' => dirname(__FILE__) . DS . 'storage.php'
|
||||
],
|
||||
|
||||
// For RedisTaskStorage, parameters are connection properties
|
||||
#'parameters' => [
|
||||
# // Type can be 'tcp' or 'unix'
|
||||
# 'socket_type' => 'tcp',
|
||||
# // If socket_type == 'unix', set the socket here
|
||||
# 'socket' => null,
|
||||
# // If socket_type == 'tcp', set the host here
|
||||
# 'host' => 'localhost',
|
||||
#
|
||||
# 'password' => null,
|
||||
# 'port' => 6379,
|
||||
# 'timeout' => 0
|
||||
#]
|
||||
],
|
||||
'Executor' => [
|
||||
'type' => 'ShellExecutor',
|
||||
|
||||
// For ShellExecutor, first parameter is the file location of the worker script
|
||||
'parameters' => [dirname(__FILE__) . DS . 'worker.php']
|
||||
'parameters' => [
|
||||
'workerFile' => dirname(__FILE__) . DS . 'bin' . DS . 'worker'
|
||||
]
|
||||
]
|
||||
);
|
@ -45,22 +45,28 @@ class ShellExecutor implements Executor
|
||||
|
||||
private $binary;
|
||||
private $worker;
|
||||
private $bootstrapFile;
|
||||
private $stdout = "> /dev/null";
|
||||
private $stderr = "2> /dev/null";
|
||||
|
||||
/**
|
||||
* ShellExecutor constructor.
|
||||
*
|
||||
* @param string $workerFile The worker script that shall run individual tasks
|
||||
* @param string $bootstrapFile
|
||||
* @param array $parameters
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function __construct(string $workerFile)
|
||||
public function __construct(string $bootstrapFile, array $parameters)
|
||||
{
|
||||
// Fetch workerFile
|
||||
$workerFile = $parameters['workerFile'];
|
||||
|
||||
// First determine the PHP binary
|
||||
$this->binary = PHP_BINDIR . DS . 'php';
|
||||
$this->bootstrapFile = $bootstrapFile;
|
||||
|
||||
if (!file_exists($workerFile))
|
||||
throw new TasksException("Could not construct ShellExecutor. Worker script does not exist.");
|
||||
throw new TasksException("Could not construct ShellExecutor. ShellWorker script does not exist.");
|
||||
|
||||
$this->worker = $workerFile;
|
||||
}
|
||||
@ -77,7 +83,7 @@ class ShellExecutor implements Executor
|
||||
public function startTask(Task $task, bool $post = false): Task
|
||||
{
|
||||
// First prepare the command used to spawn workers
|
||||
$commandString = "$this->binary $this->worker %s ".($post ? 'post' : 'run')." $this->stdout $this->stderr & echo $!";
|
||||
$commandString = "$this->binary $this->worker --bootstrap=".$this->bootstrapFile." -t %s ".($post ? 'p' : '')." $this->stdout $this->stderr & echo $!";
|
||||
|
||||
// Then execute the command using the base64_encoded string of the taskID
|
||||
$output = $this->shellExec($commandString, [base64_encode($task->getId())]);
|
||||
|
@ -42,7 +42,7 @@ use FuzeWorks\Exception\EventException;
|
||||
use FuzeWorks\Logger;
|
||||
use FuzeWorks\Priority;
|
||||
|
||||
class Worker
|
||||
class ShellWorker
|
||||
{
|
||||
|
||||
/**
|
||||
@ -75,7 +75,11 @@ class Worker
|
||||
public function run(string $taskID, bool $post = false)
|
||||
{
|
||||
// First fetch the task
|
||||
$task = $this->taskStorage->getTaskById($taskID);
|
||||
try {
|
||||
$task = $this->taskStorage->getTaskById($taskID);
|
||||
} catch (TasksException $e) {
|
||||
throw new TasksException("Could not run worker. Task not found.");
|
||||
}
|
||||
|
||||
// Fire a taskHandleEvent
|
||||
/** @var TaskHandleEvent $event */
|
||||
@ -159,6 +163,10 @@ class Worker
|
||||
$errors = $this->getErrors();
|
||||
$this->output('', $errors);
|
||||
|
||||
// If no task is set yet, abort error logging to task
|
||||
if (is_null($this->task))
|
||||
return;
|
||||
|
||||
try {
|
||||
// Write to TaskStorage
|
||||
if (!$this->post)
|
@ -97,6 +97,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
|
||||
// Modify the task in TaskStorage
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
// DELAYED: If task is delayed, and enough time has passed, change the status back to pending
|
||||
@ -104,6 +105,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
{
|
||||
$task->setStatus(Task::PENDING);
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
// CANCELLED/COMPLETED: remove the task if requested to do so
|
||||
@ -139,6 +141,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
|
||||
// If any changes have been made, they should be written to TaskStorage
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
// FAILED: if a process has failed, attempt to rety if requested to do so
|
||||
@ -161,6 +164,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
$task = $this->executor->startTask($task);
|
||||
$task->setStatus(Task::RUNNING);
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@ -176,6 +180,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
$task->setStatus(Task::CANCELLED);
|
||||
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
// SUCCESS: if a task has succeeded, see if it needs a postHandler
|
||||
@ -191,6 +196,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
$task->setStatus(Task::COMPLETED);
|
||||
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
// POST: when a task is currently running in it's postHandler
|
||||
@ -226,6 +232,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
|
||||
// If any changes have been made, they should be written to TaskStorage
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
|
||||
}
|
||||
@ -263,6 +270,7 @@ class ParallelSuperVisor implements SuperVisor
|
||||
|
||||
// Save changes to TaskStorage
|
||||
$this->taskStorage->modifyTask($task);
|
||||
fwrite(STDOUT, "\nChanged status of task '".$task->getId()."' to status " . Task::getStatusType($task->getStatus()));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,6 +39,14 @@ namespace FuzeWorks\Async;
|
||||
interface TaskStorage
|
||||
{
|
||||
|
||||
/**
|
||||
* TaskStorage constructor.
|
||||
*
|
||||
* @throws TasksException
|
||||
* @param array $parameters from config file
|
||||
*/
|
||||
public function __construct(array $parameters);
|
||||
|
||||
/**
|
||||
* Add a task to the TaskStorage.
|
||||
*
|
||||
|
@ -60,13 +60,13 @@ class ArrayTaskStorage implements TaskStorage
|
||||
protected $tasks = [];
|
||||
|
||||
/**
|
||||
* ArrayTaskStorage constructor.
|
||||
*
|
||||
* @param string $fileName Name of the Storage file
|
||||
* @throws TasksException
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __construct(string $fileName)
|
||||
public function __construct(array $parameters)
|
||||
{
|
||||
// Load the filename for this taskStorage
|
||||
$fileName = $parameters['filename'];
|
||||
|
||||
if (!file_exists($fileName))
|
||||
throw new TasksException("Could not construct ArrayTaskStorage. Storage file '$fileName' doesn't exist.");
|
||||
|
||||
|
278
src/FuzeWorks/Async/TaskStorage/RedisTaskStorage.php
Normal file
278
src/FuzeWorks/Async/TaskStorage/RedisTaskStorage.php
Normal file
@ -0,0 +1,278 @@
|
||||
<?php
|
||||
/**
|
||||
* FuzeWorks Async Library
|
||||
*
|
||||
* The FuzeWorks PHP FrameWork
|
||||
*
|
||||
* Copyright (C) 2013-2020 TechFuze
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* @author TechFuze
|
||||
* @copyright Copyright (c) 2013 - 2020, TechFuze. (http://techfuze.net)
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
*
|
||||
* @link http://techfuze.net/fuzeworks
|
||||
* @since Version 1.0.0
|
||||
*
|
||||
* @version Version 1.0.0
|
||||
*/
|
||||
|
||||
namespace FuzeWorks\Async\TaskStorage;
|
||||
use FuzeWorks\Async\Task;
|
||||
use FuzeWorks\Async\TasksException;
|
||||
use FuzeWorks\Async\TaskStorage;
|
||||
use Redis;
|
||||
use RedisException;
|
||||
|
||||
class RedisTaskStorage implements TaskStorage
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Redis
|
||||
*/
|
||||
protected $conn;
|
||||
|
||||
protected $indexSet = 'async_index';
|
||||
protected $key_prefix = 'async_task_';
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __construct(array $parameters)
|
||||
{
|
||||
// Attempt to connect to Redis
|
||||
try {
|
||||
$this->conn = new Redis();
|
||||
|
||||
// Afterwards connect to server
|
||||
$socketType = $parameters['socket_type'];
|
||||
if ($socketType == 'unix')
|
||||
$success = $this->conn->connect($parameters['socket']);
|
||||
elseif ($socketType == 'tcp')
|
||||
$success = $this->conn->connect($parameters['host'], $parameters['port'], $parameters['timeout']);
|
||||
else
|
||||
$success = false;
|
||||
|
||||
// If unsuccessful, return false
|
||||
if (!$success)
|
||||
throw new TasksException("Could not construct RedisTaskStorage. Failed to connect.");
|
||||
|
||||
// Otherwise attempt authentication, if needed
|
||||
if (isset($parameters['password']) && !$this->conn->auth($parameters['password']))
|
||||
throw new TasksException("Could not construct RedisTaskStorage. Authentication failure.");
|
||||
} catch (RedisException $e) {
|
||||
throw new TasksException("Could not construct RedisTaskStorage. RedisException thrown: '" . $e->getMessage() . "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function addTask(Task $task): bool
|
||||
{
|
||||
// Check if the task doesn't exist yet
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Query the index
|
||||
$isMember = $this->conn->sIsMember($this->indexSet, $taskId);
|
||||
if ($isMember)
|
||||
throw new TasksException("Could not add Task to TaskStorage. Task '$taskId' already exists.");
|
||||
|
||||
// Serialize the task and save it
|
||||
$taskData = serialize($task);
|
||||
$this->conn->set($this->key_prefix . $taskId, $taskData);
|
||||
$this->conn->sAdd($this->indexSet, $taskId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function readTasks(): array
|
||||
{
|
||||
return $this->refreshTasks();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function refreshTasks()
|
||||
{
|
||||
// First fetch an array of all tasks in the set
|
||||
$taskList = $this->conn->sMembers($this->indexSet);
|
||||
|
||||
// Go over each taskId and fetch the specific task
|
||||
$tasks = [];
|
||||
foreach ($taskList as $taskId)
|
||||
$tasks[] = unserialize($this->conn->get($this->key_prefix . $taskId));
|
||||
|
||||
return $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getTaskById(string $identifier): Task
|
||||
{
|
||||
// Query the index
|
||||
$isMember = $this->conn->sIsMember($this->indexSet, $identifier);
|
||||
if (!$isMember)
|
||||
throw new TasksException("Could not get task by ID. Task not found.");
|
||||
|
||||
// Fetch the task
|
||||
/** @var Task $task */
|
||||
$task = unserialize($this->conn->get($this->key_prefix . $identifier));
|
||||
|
||||
// Return the task
|
||||
return $task;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function modifyTask(Task $task): bool
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if it exists
|
||||
$isMember = $this->conn->sIsMember($this->indexSet, $taskId);
|
||||
if (!$isMember)
|
||||
throw new TasksException("Could not modify task. Task '$taskId' already exists.");
|
||||
|
||||
// And write the data
|
||||
$taskData = serialize($task);
|
||||
return $this->conn->set($this->key_prefix . $taskId, $taskData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function deleteTask(Task $task): bool
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if it exists
|
||||
$isMember = $this->conn->sIsMember($this->indexSet, $taskId);
|
||||
if (!$isMember)
|
||||
throw new TasksException("Could not modify task. Task '$taskId' already exists.");
|
||||
|
||||
// Delete the key
|
||||
$this->conn->del($this->key_prefix . $taskId);
|
||||
$this->conn->sRem($this->indexSet, $taskId);
|
||||
|
||||
// Remove all task output and post output
|
||||
$settings = $task->getRetrySettings();
|
||||
$maxRetries = $settings['maxRetries'];
|
||||
for ($i=0;$i<=$maxRetries;$i++)
|
||||
{
|
||||
// First remove all possible task output
|
||||
if ($this->conn->exists($this->key_prefix . $taskId . '_output_' . $i))
|
||||
$this->conn->del($this->key_prefix . $taskId . '_output_' . $i);
|
||||
|
||||
if ($this->conn->exists($this->key_prefix . $taskId . '_post_' . $i))
|
||||
$this->conn->del($this->key_prefix . $taskId . '_post_' . $i);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function writeTaskOutput(Task $task, string $output, string $errors, int $statusCode, int $attempt = 0): bool
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if the key already exists
|
||||
if ($this->conn->exists($this->key_prefix . $taskId . '_output_' . $attempt))
|
||||
throw new TasksException("Could not write task output. Output already written.");
|
||||
|
||||
// Prepare contents
|
||||
$contents = ['taskId' => $task->getId(), 'output' => $output, 'errors' => $errors, 'statusCode' => $statusCode];
|
||||
$data = serialize($contents);
|
||||
|
||||
// Write contents
|
||||
return $this->conn->set($this->key_prefix . $taskId . '_output_' . $attempt, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function writePostOutput(Task $task, string $output, string $errors, int $statusCode, int $attempt = 0): bool
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if the key already exists
|
||||
if ($this->conn->exists($this->key_prefix . $taskId . '_post_' . $attempt))
|
||||
throw new TasksException("Could not write post output. Output already written.");
|
||||
|
||||
// Prepare contents
|
||||
$contents = ['taskId' => $task->getId(), 'output' => $output, 'errors' => $errors, 'statusCode' => $statusCode];
|
||||
$data = serialize($contents);
|
||||
|
||||
// Write contents
|
||||
return $this->conn->set($this->key_prefix . $taskId . '_post_' . $attempt, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function readTaskOutput(Task $task, int $attempt = 0): ?array
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if the key already exists
|
||||
if (!$this->conn->exists($this->key_prefix . $taskId . '_output_' . $attempt))
|
||||
return null;
|
||||
|
||||
// Load and convert the data
|
||||
$data = $this->conn->get($this->key_prefix . $taskId . '_output_' . $attempt);
|
||||
$data = unserialize($data);
|
||||
|
||||
return ['output' => $data['output'], 'errors' => $data['errors'], 'statusCode' => $data['statusCode']];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function readPostOutput(Task $task, int $attempt = 0): ?array
|
||||
{
|
||||
// First get the task ID
|
||||
$taskId = $task->getId();
|
||||
|
||||
// Check if the key already exists
|
||||
if (!$this->conn->exists($this->key_prefix . $taskId . '_post_' . $attempt))
|
||||
return null;
|
||||
|
||||
// Load and convert the data
|
||||
$data = $this->conn->get($this->key_prefix . $taskId . '_post_' . $attempt);
|
||||
$data = unserialize($data);
|
||||
|
||||
return ['output' => $data['output'], 'errors' => $data['errors'], 'statusCode' => $data['statusCode']];
|
||||
}
|
||||
}
|
@ -68,21 +68,23 @@ class Tasks implements iLibrary
|
||||
* @return bool
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function queueTask(Task $task): bool
|
||||
public function addTask(Task $task): bool
|
||||
{
|
||||
$taskStorage = $this->getTaskStorage();
|
||||
return $taskStorage->addTask($task);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $bootstrapFile
|
||||
* @return SuperVisor
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function getSuperVisor(): SuperVisor
|
||||
public function getSuperVisor(string $bootstrapFile): SuperVisor
|
||||
{
|
||||
$cfg = $this->cfg->get('SuperVisor');
|
||||
$class = 'FuzeWorks\Async\Supervisors\\' . $cfg['type'];
|
||||
$parameters = isset($cfg['parameters']) && is_array($cfg['parameters']) ? $cfg['parameters'] : [];
|
||||
array_unshift($parameters, $this->getTaskStorage(), $this->getExecutor());
|
||||
array_unshift($parameters, $this->getTaskStorage(), $this->getExecutor($bootstrapFile));
|
||||
if (!class_exists($class, true))
|
||||
throw new TasksException("Could not get SuperVisor. Type of '$class' not found.");
|
||||
|
||||
@ -94,12 +96,12 @@ class Tasks implements iLibrary
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Worker
|
||||
* @return ShellWorker
|
||||
* @throws TasksException
|
||||
*/
|
||||
public function getWorker(): Worker
|
||||
public function getWorker(): ShellWorker
|
||||
{
|
||||
return new Worker($this->getTaskStorage());
|
||||
return new ShellWorker($this->getTaskStorage());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -116,7 +118,7 @@ class Tasks implements iLibrary
|
||||
if (!class_exists($class, true))
|
||||
throw new TasksException("Could not get TaskStorage. Type of '$class' not found.");
|
||||
|
||||
$object = new $class(...$parameters);
|
||||
$object = new $class($parameters);
|
||||
if (!$object instanceof TaskStorage)
|
||||
throw new TasksException("Could not get TaskStorage. Type '$class' is not instanceof TaskStorage.");
|
||||
|
||||
@ -126,10 +128,11 @@ class Tasks implements iLibrary
|
||||
/**
|
||||
* Fetch the Executor based on the configured type
|
||||
*
|
||||
* @param string $bootstrapFile
|
||||
* @return Executor
|
||||
* @throws TasksException
|
||||
*/
|
||||
protected function getExecutor(): Executor
|
||||
protected function getExecutor(string $bootstrapFile): Executor
|
||||
{
|
||||
$cfg = $this->cfg->get('Executor');
|
||||
$class = 'FuzeWorks\Async\Executors\\' . $cfg['type'];
|
||||
@ -137,7 +140,7 @@ class Tasks implements iLibrary
|
||||
if (!class_exists($class, true))
|
||||
throw new TasksException("Could not get Executor. Type of '$class' not found.");
|
||||
|
||||
$object = new $class(...$parameters);
|
||||
$object = new $class($bootstrapFile, $parameters);
|
||||
if (!$object instanceof Executor)
|
||||
throw new TasksException("Could not get Executor. Type '$class' is not instanceof Executor.");
|
||||
|
||||
|
@ -1,70 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* FuzeWorks Async Library
|
||||
*
|
||||
* The FuzeWorks PHP FrameWork
|
||||
*
|
||||
* Copyright (C) 2013-2020 TechFuze
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* @author TechFuze
|
||||
* @copyright Copyright (c) 2013 - 2020, TechFuze. (http://techfuze.net)
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
*
|
||||
* @link http://techfuze.net/fuzeworks
|
||||
* @since Version 1.0.0
|
||||
*
|
||||
* @version Version 1.0.0
|
||||
*/
|
||||
|
||||
use FuzeWorks\Async\SuperVisor;
|
||||
use FuzeWorks\Async\Tasks;
|
||||
use FuzeWorks\Logger;
|
||||
|
||||
require_once('vendor/autoload.php');
|
||||
|
||||
// Open configurator
|
||||
$configurator = new FuzeWorks\Configurator();
|
||||
|
||||
// Set up basic settings
|
||||
$configurator->setTimeZone('Europe/Amsterdam');
|
||||
$configurator->setTempDirectory(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'temp');
|
||||
$configurator->setLogDirectory(dirname(__FILE__). DIRECTORY_SEPARATOR . 'log');
|
||||
|
||||
// Add Async library
|
||||
$configurator->deferComponentClassMethod('libraries', 'addLibraryClass', null, 'async', '\FuzeWorks\Async\Tasks');
|
||||
|
||||
// Debug
|
||||
$configurator->enableDebugMode()->setDebugAddress('ALL');
|
||||
|
||||
// Create container
|
||||
$container = $configurator->createContainer();
|
||||
|
||||
// Add lib
|
||||
Logger::enableScreenLog();
|
||||
|
||||
// RUN THE APP
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
|
||||
$supervisor = $lib->getSuperVisor();
|
||||
while ($supervisor->cycle() === SuperVisor::RUNNING) {
|
||||
usleep(250000);
|
||||
}
|
68
worker.php
68
worker.php
@ -1,68 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* FuzeWorks Async Library
|
||||
*
|
||||
* The FuzeWorks PHP FrameWork
|
||||
*
|
||||
* Copyright (C) 2013-2020 TechFuze
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* @author TechFuze
|
||||
* @copyright Copyright (c) 2013 - 2020, TechFuze. (http://techfuze.net)
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
*
|
||||
* @link http://techfuze.net/fuzeworks
|
||||
* @since Version 1.0.0
|
||||
*
|
||||
* @version Version 1.0.0
|
||||
*/
|
||||
use FuzeWorks\Async\Tasks;
|
||||
|
||||
require_once('vendor/autoload.php');
|
||||
|
||||
// Open configurator
|
||||
$configurator = new FuzeWorks\Configurator();
|
||||
|
||||
// Set up basic settings
|
||||
$configurator->setTimeZone('Europe/Amsterdam');
|
||||
$configurator->setTempDirectory(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'temp');
|
||||
$configurator->setLogDirectory(dirname(__FILE__). DIRECTORY_SEPARATOR . 'log');
|
||||
|
||||
// Add Async library
|
||||
$configurator->deferComponentClassMethod('libraries', 'addLibraryClass', null, 'async', '\FuzeWorks\Async\Tasks');
|
||||
|
||||
// Debug
|
||||
$configurator->enableDebugMode()->setDebugAddress('ALL');
|
||||
|
||||
// Create container
|
||||
$container = $configurator->createContainer();
|
||||
|
||||
// Prepare arguments
|
||||
$script = array_shift($argv);
|
||||
$taskID = array_shift($argv);
|
||||
$taskID = base64_decode($taskID);
|
||||
$mode = trim(array_shift($argv));
|
||||
$post = ($mode === 'post' ? true : false);
|
||||
|
||||
// RUN THE APP
|
||||
/** @var Tasks $lib */
|
||||
$lib = $container->libraries->get('async');
|
||||
$worker = $lib->getWorker();
|
||||
$worker->run($taskID, $post);
|
Loading…
Reference in New Issue
Block a user