/
Client.php
221 lines (181 loc) · 5.68 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
namespace Gearman;
use Config\Object as Base;
use GearmanTask;
class Client extends Base {
const WORKLOAD_TEST = 'test client';
/**
* Клиент
* @var object
*/
protected $_Client = null;
/**
* Настройки по умолчанию
* @var array
*/
protected static $_defaults = [
'server' => ['host' => 'localhost', 'port' => 4730],
'background' => false,
'priority' => Priority::NORMAL,
'connect' => true
];
/**
* Общие данные обработки
* @var mixed
*/
protected $_data = null;
protected $_connected = false;
/**
* Данные постобработки
* @var mixed
*/
protected $_out = null;
public function __construct($namespace = null, $config = []) {
static::$_defaults = \Hash::merge(self::$_defaults, static::$_defaults);
if ($namespace) {
$config = $this->_config(__NAMESPACE__, $config);
} else {
$namespace = __NAMESPACE__;
}
parent::__construct($namespace, $config);
// соединение
if ($this->_config['connect']) {
$this->_connect();
}
}
/**
* Подключение к серверу
*
* @param bool $reconnect пепеподключение, если нужно
* @throws Exception
* @return bool
*/
protected function _connect($reconnect = true) {
// уже подключены
if (!$reconnect && $this->_connected) {
return $this->_connected;
}
// убиваем старое соедение
unset($this->_Client);
$this->_connected = false;
// ну и всё заново
$this->_Client = new \GearmanClient();
$server = (!empty($this->_config['servers']) && empty($this->_config['server']))
? $this->_config['servers'][0]
: $this->_config['server']
;
$this->_Client->addServer($server['host'], $server['port']);
// учитывая, что addServer всегда возвращает true, делаем дополнительный ping сервера для проверки его реакции
if (!$this->_Client->ping(self::WORKLOAD_TEST)) {
throw new Exception('Не удалось соединиться с сервером');
}
$this->_connected = true;
if (is_callable([$this, 'done'])) {
if (!$this->_Client->setCompleteCallback([$this, 'done'])) {
throw new Exception('Не удалось установить обработчик');
}
}
if (is_callable([$this, 'exception'])) {
if (!$this->_Client->setExceptionCallback([$this, 'exception'])) {
throw new Exception('Не удалось установить обработчик исключений');
}
}
return $this->_connected;
}
/**
* magic для вызовов методово
* @param string $method название метода
* @param array $arguments список агрументов
* @return mixed
*/
public function __call($method, $arguments) {
return call_user_func_array([$this->_Client, $method], $arguments);
}
/**
* Запуск задачи на выполнение
*
* @param bool $force
* @throws Exception
* @return mixed
*/
public function run($force = false) {
if (!$this->_Client->runTasks()) {
throw new Exception('Не удалось запустить выполнение задач: ' . $this->_Client->error());
}
return ($this->_config['background'] || $force) ? true : $this->_out;
}
/**
* Возвращает количество доступных для обработки воркеров
*
* @return int кол-во воркеров
*/
public function available() {
$info = (new Manager())->getWorkers($this->_function($this->_function));
// оставляем запас, а количество запускаемых задач берём из количества доступных / 2
$available = intval(floor(($info[3] - $info[1])/2));
return $available < 1 ? 1 : $available;
}
/**
* Определяем название метода gearmand
*
* @param string $function имя функции
* @return имя метода
*/
protected function _function($function) {
$class = get_class($this);
return (new \ReflectionClass($class))->getNamespaceName() . '\\' . $function;
}
/**
* Заглушка для добавления задачи с нормальным приоритетом
* @param string $name функция
* @param string $workload данные
*/
public function addTaskNormal($name, $workload) {
return $this->_Client->addTask($name, $workload);
}
public function addTaskNormalBackground($name, $workload) {
return $this->_Client->addTaskBackGround($name, $workload);
}
/**
* Выбор метода для добавления задачи в gearman
*
* @param mixed $data данные
* @param bool $background в фоне или нет
* @return string метод
*/
protected function _method($data = null) {
$priority = $this->_config['priority'];
if (is_array($data) && array_key_exists('priority', $data)) {
$priority = Priority::fromString($data['priority']);
}
$priority = Priority::toString($priority);
$method = ($this->_config['background']) ?
'addTask' . $priority . 'Background' :
'addTask' . $priority
;
return $method;
}
/**
* callback на выполение обработки
* @param GearmanTask $Task
* @return int
*/
public function done(GearmanTask $Task) {
$this->_out = unserialize($Task->data());
return GEARMAN_SUCCESS;
}
/**
* Обработка исключительных ситуаций
*
* @param GearmanTask $Task
* @throws AppException
* @return int
*/
public function exception(GearmanTask $Task) {
$e = unserialize($Task->data());
if (is_a($e, 'Exception')) {
throw $e;
}
return GEARMAN_SUCCESS;
}
}