Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] Add task completion callbacks #7

Merged
merged 1 commit into from
Jan 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 34 additions & 7 deletions src/Dplr/Dplr.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Dplr

protected $servers = [];

/** @var array<int, Task[]> */
protected $tasks = [];

protected $multipleThread = -1;
Expand Down Expand Up @@ -227,8 +228,13 @@ private function addTask(Task $task): self
/*
* Adding command task.
*/
public function command(string $command, string $serverGroup = null, int $timeout = null): self
{
public function command(
string $command,
string $serverGroup = null,
int $timeout = null,
callable $onSuccess = null,
callable $onFailure = null
): self {
$servers = null;
if (null !== $serverGroup) {
$servers = $this->getServersByGroup($serverGroup);
Expand All @@ -246,16 +252,26 @@ public function command(string $command, string $serverGroup = null, int $timeou
'Timeout' => ($timeout > 0 ? $timeout : $this->defaultTimeout) * 1000,
];

$this->addTask(new Task($data));
$this->addTask(new Task(
$data,
$onSuccess,
$onFailure,
));

return $this;
}

/*
* Adding uploading task.
*/
public function upload(string $localFile, string $remoteFile, string $serverGroup = null, int $timeout = null): self
{
public function upload(
string $localFile,
string $remoteFile,
string $serverGroup = null,
int $timeout = null,
callable $onSuccess = null,
callable $onFailure = null
): self {
$servers = null;
if (null !== $serverGroup) {
$servers = $this->getServersByGroup($serverGroup);
Expand All @@ -274,7 +290,11 @@ public function upload(string $localFile, string $remoteFile, string $serverGrou
'Timeout' => ($timeout > 0 ? $timeout : $this->defaultTimeout) * 1000,
];

$this->addTask(new Task($data));
$this->addTask(new Task(
$data,
$onSuccess,
$onFailure,
));

return $this;
}
Expand Down Expand Up @@ -457,16 +477,22 @@ protected function runTasks(callable $callback = null): void
if ('Reply' === $data['Type']) {
$report = new TaskReport($data, $task);
$this->reports[] = $report;

if ($callback) {
$callback($report->isSuccessful() ? '.' : 'E');
}

if ($report->isSuccessful()) {
$task->callOnSuccess();
} else {
$task->callOnFailure();
}
} elseif ('UserError' === $data['Type']) {
$this->reports[] = new TaskReport($data, $task);

if ($callback) {
$callback('J');
}
$task->callOnFailure();
} elseif ('FinalReply' === $data['Type']) {
$hosts = $data['TimedOutHosts'];
if (count($hosts)) {
Expand All @@ -482,6 +508,7 @@ protected function runTasks(callable $callback = null): void
if ($callback) {
$callback('T');
}
$task->callOnFailure();
}
}
}
Expand Down
25 changes: 23 additions & 2 deletions src/Dplr/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@ class Task implements \JsonSerializable
public const ACTIONS = [self::ACTION_SSH, self::ACTION_SCP];

protected $parameters = [];
protected $onSuccess;
protected $onFailure;

public function __construct(array $parameters)
{
public function __construct(
array $parameters,
callable $onSuccess = null,
callable $onFailure = null
) {
if (!isset($parameters['Action'])) {
throw new \InvalidArgumentException('Not found `Action` parameter.');
}
Expand All @@ -26,6 +31,8 @@ public function __construct(array $parameters)
}

$this->parameters = $parameters;
$this->onSuccess = $onSuccess;
$this->onFailure = $onFailure;
}

public function __toString()
Expand All @@ -50,4 +57,18 @@ public function jsonSerialize(): array
{
return $this->parameters;
}

public function callOnSuccess(): void
{
if (null !== $this->onSuccess) {
call_user_func($this->onSuccess);
}
}

public function callOnFailure(): void
{
if (null !== $this->onFailure) {
call_user_func($this->onFailure);
}
}
}
37 changes: 37 additions & 0 deletions tests/Dplr/Tests/DplrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,43 @@ public function testSuccessful(): void
$this->assertEquals(".\n..\n.ssh\n", $d->getSingleReportOutput());
}

public function testTaskCallbacks(): void
{
$successes = 0;
$failures = 0;
$success = function () use (&$successes) {
++$successes;
};
$failure = function () use (&$failures) {
++$failures;
};

$d = self::getDplr();
$d->command('id', 'app', null, $success, $failure);
$d->command('cat doesnotexist.log', 'app', null, $success, $failure);

$this->assertTrue($d->hasTasks());
$d->run();

$this->assertFalse($d->isSuccessful());
$this->assertFalse($d->hasTasks());
$this->assertEquals(2, $successes);
$this->assertEquals(2, $failures);

$report = $d->getReport();
$this->assertEquals(4, $report['total']);
$this->assertEquals(2, $report['successful']);
$this->assertEquals(2, $report['failed']);

$this->assertCount(2, $d->getFailed());
foreach ($d->getFailed() as $report) {
$this->assertEquals(
'CMD cat doesnotexist.log',
(string) $report->getTask()
);
}
}

public function testExceptionOnSingleReportOutputWithSeveralTasks(): void
{
$this->expectException(OutOfRangeException::class);
Expand Down
30 changes: 30 additions & 0 deletions tests/Dplr/Tests/TaskTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,34 @@ public function testScpTask(): void
json_encode($task)
);
}

public function testCallbacks(): void
{
$success = false;
$failure = false;

$task = new Task(
[
'Action' => 'scp',
'Source' => '/home/user1/1.txt',
'Target' => '/home/user2/2.txt',
],
function () use (&$success) {
$success = true;
},
function () use (&$failure) {
$failure = true;
}
);

$this->assertEquals('CPY /home/user1/1.txt -> /home/user2/2.txt', (string) $task);
$this->assertJsonStringEqualsJsonString(
'{"Action":"scp","Source":"/home/user1/1.txt","Target":"/home/user2/2.txt"}',
json_encode($task)
);
$task->callOnSuccess();
$this->assertTrue($success);
$task->callOnFailure();
$this->assertTrue($failure);
}
}