-
Notifications
You must be signed in to change notification settings - Fork 5
/
Client.php
607 lines (528 loc) · 17.6 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
<?php
namespace Aternos\Etcd;
use Aternos\Etcd\Exception\InvalidLeaseException;
use Aternos\Etcd\Exception\NoResponseException;
use Aternos\Etcd\Exception\Status\InvalidResponseStatusCodeException;
use Aternos\Etcd\Exception\Status\ResponseStatusCodeExceptionFactory;
use Etcdserverpb\AuthClient;
use Etcdserverpb\AuthenticateRequest;
use Etcdserverpb\AuthenticateResponse;
use Etcdserverpb\Compare;
use Etcdserverpb\Compare\CompareResult;
use Etcdserverpb\Compare\CompareTarget;
use Etcdserverpb\DeleteRangeRequest;
use Etcdserverpb\DeleteRangeResponse;
use Etcdserverpb\KVClient;
use Etcdserverpb\LeaseClient;
use Etcdserverpb\LeaseGrantRequest;
use Etcdserverpb\LeaseGrantResponse;
use Etcdserverpb\LeaseKeepAliveRequest;
use Etcdserverpb\LeaseKeepAliveResponse;
use Etcdserverpb\LeaseRevokeRequest;
use Etcdserverpb\PutRequest;
use Etcdserverpb\PutResponse;
use Etcdserverpb\RangeRequest;
use Etcdserverpb\RangeResponse;
use Etcdserverpb\RequestOp;
use Etcdserverpb\ResponseOp;
use Etcdserverpb\TxnRequest;
use Etcdserverpb\TxnResponse;
use Grpc\ChannelCredentials;
use Mvccpb\KeyValue;
/**
* Class Client
*
* @author Matthias Neid
*/
class Client implements ClientInterface
{
/**
* @var string
*/
protected $hostname;
/**
* @var bool
*/
protected $username;
/**
* @var bool
*/
protected $password;
/**
* @var int
*/
protected $timeout;
/**
* @var string
*/
protected $token;
/**
* @var KVClient
*/
protected $kvClient;
/**
* @var AuthClient
*/
protected $authClient;
/**
* @var LeaseClient
*/
protected $leaseClient;
/**
* Client constructor.
*
* @param string $hostname
* @param bool $username
* @param bool $password
* @param int $timeout in microseconds, default 1 second
*/
public function __construct($hostname = "localhost:2379", $username = false, $password = false, $timeout = 1000000)
{
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->timeout = $timeout;
}
/**
* @param string|null $key
* @return string
*/
public function getHostname(?string $key = null): string
{
return $this->hostname;
}
/**
* Put a value into the key store
*
* @param string $key
* @param mixed $value
* @param bool $prevKv Get the previous key value in the response
* @param int $leaseID
* @param bool $ignoreLease Ignore the current lease
* @param bool $ignoreValue Updates the key using its current value
*
* @return string|null Returns previous value if $prevKv is set to true
* @throws InvalidResponseStatusCodeException
*/
public function put(string $key, $value, bool $prevKv = false, int $leaseID = 0, bool $ignoreLease = false, bool $ignoreValue = false)
{
$client = $this->getKvClient();
$request = new PutRequest();
$request->setKey($key);
$request->setValue($value);
$request->setPrevKv($prevKv);
$request->setIgnoreLease($ignoreLease);
$request->setIgnoreValue($ignoreValue);
$request->setLease($leaseID);
/** @var PutResponse $response */
list($response, $status) = $client->Put($request, $this->getMetaData(), $this->getOptions())->wait();
$this->validateStatus($status);
if ($prevKv) {
return $response->getPrevKv()->getValue();
}
}
/**
* Get a key value
*
* @param string $key
* @return bool|string
* @throws InvalidResponseStatusCodeException
*/
public function get(string $key)
{
$client = $this->getKvClient();
$request = new RangeRequest();
$request->setKey($key);
/** @var RangeResponse $response */
list($response, $status) = $client->Range($request, $this->getMetaData(), $this->getOptions())->wait();
$this->validateStatus($status);
$field = $response->getKvs();
if (count($field) === 0) {
return false;
}
return $field[0]->getValue();
}
/**
* Delete a key
*
* @param string $key
* @return bool
* @throws InvalidResponseStatusCodeException
*/
public function delete(string $key)
{
$client = $this->getKvClient();
$request = new DeleteRangeRequest();
$request->setKey($key);
/** @var DeleteRangeResponse $response */
list($response, $status) = $client->DeleteRange($request, $this->getMetaData(), $this->getOptions())->wait();
$this->validateStatus($status);
if ($response->getDeleted() > 0) {
return true;
} else {
return false;
}
}
/**
* Put $value if $key value matches $previousValue otherwise $returnNewValueOnFail
*
* @param string $key
* @param string $value The new value to set
* @param bool|string $compareValue The previous value to compare against
* @param bool $returnNewValueOnFail
* @return bool|string
* @throws InvalidResponseStatusCodeException
*/
public function putIf(string $key, string $value, $compareValue, bool $returnNewValueOnFail = false)
{
$operation = $this->getPutOperation($key, $value);
$compare = $this->getCompareForIf($key, $compareValue);
$failOperation = $this->getFailOperation($key, $returnNewValueOnFail);
$response = $this->txnRequest([$operation], $failOperation, [$compare]);
return $this->getIfResponse($returnNewValueOnFail, $response);
}
/**
* Delete if $key value matches $previous value otherwise $returnNewValueOnFail
*
* @param string $key
* @param bool|string $compareValue The previous value to compare against
* @param bool $returnNewValueOnFail
* @return bool|string
* @throws InvalidResponseStatusCodeException
*/
public function deleteIf(string $key, $compareValue, bool $returnNewValueOnFail = false)
{
$operation = $this->getDeleteOperation($key);
$compare = $this->getCompareForIf($key, $compareValue);
$failOperation = $this->getFailOperation($key, $returnNewValueOnFail);
$response = $this->txnRequest([$operation], $failOperation, [$compare]);
return $this->getIfResponse($returnNewValueOnFail, $response);
}
/**
* Get leaseID which can be used with etcd's put
*
* @param int $ttl time-to-live in seconds
* @return int
* @throws InvalidResponseStatusCodeException
*/
public function getLeaseID(int $ttl)
{
$lease = $this->getLeaseClient();
$leaseRequest = new LeaseGrantRequest();
$leaseRequest->setTTL($ttl);
/** @var LeaseGrantResponse $response */
list($response, $status) = $lease->LeaseGrant($leaseRequest, $this->getMetaData())->wait();
$this->validateStatus($status);
return (int)$response->getID();
}
/**
* Revoke existing leaseID
*
* @param int $leaseID
* @throws InvalidResponseStatusCodeException
*/
public function revokeLeaseID(int $leaseID)
{
$lease = $this->getLeaseClient();
$leaseRequest = new LeaseRevokeRequest();
$leaseRequest->setID($leaseID);
list(, $status) = $lease->LeaseRevoke($leaseRequest, $this->getMetaData())->wait();
$this->validateStatus($status);
}
/**
* Refresh chosen leaseID
*
* @param int $leaseID
* @return int lease TTL
* @throws InvalidResponseStatusCodeException|NoResponseException|InvalidLeaseException
*/
public function refreshLease(int $leaseID)
{
$lease = $this->getLeaseClient();
$leaseBidi = $lease->LeaseKeepAlive($this->getMetaData());
$leaseKeepAlive = new LeaseKeepAliveRequest();
$leaseKeepAlive->setID($leaseID);
/** @noinspection PhpParamsInspection */
$leaseBidi->write($leaseKeepAlive);
$leaseBidi->writesDone();
/** @var LeaseKeepAliveResponse $response */
$response = $leaseBidi->read();
$leaseBidi->cancel();
if($response === null || empty($response->getID()) || (int)$response->getID() !== $leaseID)
throw new NoResponseException('Could not refresh lease ID: ' . $leaseID);
if((int)$response->getTTL() === 0)
throw new InvalidLeaseException('Invalid lease ID or expired lease');
return (int)$response->getTTL();
}
/**
* Execute $requestOperations if Compare succeeds, execute $failureOperations otherwise if defined
*
* @param RequestOp[] $requestOperations operations to perform on success, array of RequestOp objects
* @param RequestOp[]|null $failureOperations operations to perform on failure, array of RequestOp objects
* @param Compare[] $compare array of Compare objects
* @return TxnResponse
* @throws InvalidResponseStatusCodeException
*/
public function txnRequest(array $requestOperations, ?array $failureOperations, array $compare): TxnResponse
{
$client = $this->getKvClient();
$request = new TxnRequest();
$request->setCompare($compare);
$request->setSuccess($requestOperations);
if($failureOperations !== null)
$request->setFailure($failureOperations);
/** @var TxnResponse $response */
list($response, $status) = $client->Txn($request, $this->getMetaData(), $this->getOptions())->wait();
$this->validateStatus($status);
return $response;
}
/**
* Transform TxnResponse into more friendly array
*
* @param TxnResponse $txnResponse return value of txnRequest method
* @param string|null $type returns only chosen type if defined,
* can be one of those: response_range, response_put, response_delete_range, response_txn
* @param bool $simpleArray return just simple array containing values,
* example: ['value1', 'value2']
* @return array example: [
* [
* 'type' => 'response_range',
* 'values' => [
* 'key' => 'key',
* 'value' => '2',
* 'version' => 3
* ]
* ]
* ]
*/
public function getResponses(TxnResponse $txnResponse, ?string $type = null, bool $simpleArray = false): array
{
$v = $r = [];
/** @var ResponseOp $response */
foreach ($txnResponse->getResponses() as $response) {
if ($type !== null && $type !== $response->getResponse())
continue;
$values = [];
if ($response->getResponseRange() !== null) {
/** @var KeyValue $field */
foreach ($response->getResponseRange()->getKvs() as $field) {
$v[] = $field->getValue();
$values[] = [
'key' => $field->getKey(),
'value' => $field->getValue(),
'version' => $field->getVersion()
];
}
}
$r[] = ['type' => $response->getResponse(), 'values' => $values];
}
return ($simpleArray) ? $v : $r;
}
/**
* Creates RequestOp of Get operation for requestIf method
*
* @param string $key
* @return RequestOp
*/
public function getGetOperation(string $key): RequestOp
{
$request = new RangeRequest();
$request->setKey($key);
$operation = new RequestOp();
$operation->setRequestRange($request);
return $operation;
}
/**
* Creates RequestOp of Put operation for requestIf method
*
* @param string $key
* @param string $value
* @param int $leaseId
* @return RequestOp
*/
public function getPutOperation(string $key, string $value, int $leaseId = 0): RequestOp
{
$request = new PutRequest();
$request->setKey($key);
$request->setValue($value);
if($leaseId !== 0)
$request->setLease($leaseId);
$operation = new RequestOp();
$operation->setRequestPut($request);
return $operation;
}
/**
* Creates RequestOp of Delete operation for requestIf method
*
* @param string $key
* @return RequestOp
*/
public function getDeleteOperation(string $key): RequestOp
{
$request = new DeleteRangeRequest();
$request->setKey($key);
$operation = new RequestOp();
$operation->setRequestDeleteRange($request);
return $operation;
}
/**
* Get an instance of Compare
*
* @param string $key
* @param string $value
* @param int $result see CompareResult class for available constants
* @param int $target check constants in the CompareTarget class for available values
* @return Compare
*/
public function getCompare(string $key, string $value, int $result, int $target): Compare
{
$compare = new Compare();
$compare->setKey($key);
$compare->setValue($value);
$compare->setTarget($target);
$compare->setResult($result);
return $compare;
}
/**
* Get an instance of LeaseClient
*
* @return LeaseClient
*/
protected function getLeaseClient(): LeaseClient
{
if (!$this->leaseClient) {
$this->leaseClient = new LeaseClient($this->hostname, [
'credentials' => ChannelCredentials::createInsecure()
]);
}
return $this->leaseClient;
}
/**
* Get an instance of KVClient
*
* @return KVClient
*/
protected function getKvClient(): KVClient
{
if (!$this->kvClient) {
$this->kvClient = new KVClient($this->hostname, [
'credentials' => ChannelCredentials::createInsecure()
]);
}
return $this->kvClient;
}
/**
* Get an instance of AuthClient
*
* @return AuthClient
*/
protected function getAuthClient(): AuthClient
{
if (!$this->authClient) {
$this->authClient = new AuthClient($this->hostname, [
'credentials' => ChannelCredentials::createInsecure()
]);
}
return $this->authClient;
}
/**
* Get an authentication token
*
* @return string
* @throws InvalidResponseStatusCodeException
*/
protected function getAuthenticationToken(): string
{
if (!$this->token) {
$client = $this->getAuthClient();
$request = new AuthenticateRequest();
$request->setName($this->username);
$request->setPassword($this->password);
/** @var AuthenticateResponse $response */
list($response, $status) = $client->Authenticate($request, [], $this->getOptions())->wait();
$this->validateStatus($status);
$this->token = $response->getToken();
}
return $this->token;
}
/**
* Add authentication token metadata if necessary
*
* @param array $metadata
* @return array
* @throws InvalidResponseStatusCodeException
*/
protected function getMetaData($metadata = []): array
{
if ($this->username && $this->password) {
$metadata = array_merge(["token" => [$this->getAuthenticationToken()]], $metadata);
}
return $metadata;
}
/**
* Add timeout
*
* @param array $options
* @return array
*/
protected function getOptions($options = []): array
{
return array_merge(["timeout" => $this->timeout], $options);
}
/**
* @param $status
* @throws InvalidResponseStatusCodeException
*/
protected function validateStatus($status)
{
if ($status->code !== 0) {
throw ResponseStatusCodeExceptionFactory::getExceptionByCode($status->code, $status->details);
}
}
/**
* @param string $key
* @param string|bool $compareValue
* @return Compare
*/
protected function getCompareForIf(string $key, $compareValue): Compare
{
if ($compareValue === false) {
$compare = $this->getCompare($key, '0', CompareResult::EQUAL, CompareTarget::VERSION);
} else {
$compare = $this->getCompare($key, $compareValue, CompareResult::EQUAL, CompareTarget::VALUE);
}
return $compare;
}
/**
* @param bool $returnNewValueOnFail
* @param TxnResponse $response
* @return bool|string
*/
protected function getIfResponse(bool $returnNewValueOnFail, TxnResponse $response)
{
if ($returnNewValueOnFail && !$response->getSucceeded()) {
/** @var ResponseOp $responseOp */
$responseOp = $response->getResponses()[0];
$getResponse = $responseOp->getResponseRange();
$field = $getResponse->getKvs();
if (count($field) === 0) {
return false;
}
return $field[0]->getValue();
} else {
return $response->getSucceeded();
}
}
/**
* @param string $key
* @param bool $returnNewValueOnFail
* @return array|null
*/
protected function getFailOperation(string $key, bool $returnNewValueOnFail)
{
$failOperation = null;
if ($returnNewValueOnFail)
$failOperation = [$this->getGetOperation($key)];
return $failOperation;
}
}