forked from PCextreme/cloudstack-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
398 lines (342 loc) · 9.74 KB
/
Client.php
File metadata and controls
398 lines (342 loc) · 9.74 KB
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
<?php
namespace PCextreme\Cloudstack;
use InvalidArgumentException;
use PCextreme\Cloudstack\Exception\ClientException;
use PCextreme\Cloudstack\Util\UrlHelpersTrait;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
class Client extends AbstractClient
{
use UrlHelpersTrait;
/**
* @var array
*/
protected $apiList;
/**
* @var string
*/
private $urlApi;
/**
* @var string
*/
private $urlClient;
/**
* @var string
*/
private $urlConsole;
/**
* @var string
*/
protected $apiKey;
/**
* @var string
*/
protected $secretKey;
/**
* @var string
*/
protected $ssoKey;
/**
* @var string
*/
private $responseError = 'errortext';
/**
* @var string
*/
private $responseCode = 'errorcode';
/**
* @var bool
*/
private $ssoEnabled = false;
/**
* Constructs a new Cloudstack client instance.
*
* @param array $options
* An array of options to set on this client. Options include
* 'apiList', 'urlApi', 'urlClient', 'urlConsole', 'apiKey',
* 'secretKey', 'responseError' and 'responseCode'.
* @param array $collaborators
* An array of collaborators that may be used to override
* this provider's default behavior. Collaborators include
* `requestFactory` and `httpClient`.
*/
public function __construct(array $options = [], array $collaborators = [])
{
$this->assertRequiredOptions($options);
$possible = $this->getConfigurableOptions();
$configured = array_intersect_key($options, array_flip($possible));
foreach ($configured as $key => $value) {
$this->$key = $value;
}
// Remove all options that are only used locally
$options = array_diff_key($options, $configured);
parent::__construct($options, $collaborators);
}
/**
* Returns all options that can be configured.
*
* @return array
*/
protected function getConfigurableOptions()
{
return array_merge($this->getRequiredOptions(), [
'apiList',
'urlClient',
'urlConsole',
'ssoKey',
'responseError',
'responseCode',
]);
}
/**
* Returns all options that are required.
*
* @return array
*/
protected function getRequiredOptions()
{
return [
'urlApi',
'apiKey',
'secretKey',
];
}
/**
* Verifies that all required options have been passed.
*
* @param array $options
* @return void
* @throws InvalidArgumentException
*/
private function assertRequiredOptions(array $options)
{
$missing = array_diff_key(array_flip($this->getRequiredOptions()), $options);
if (! empty($missing)) {
throw new InvalidArgumentException(
'Required options not defined: ' . implode(', ', array_keys($missing))
);
}
}
public function command($command, array $options = [])
{
$this->assertRequiredCommandOptions($command, $options);
$method = $this->getCommandMethod($command);
$url = $this->getCommandUrl($command, $options);
$request = $this->getRequest($method, $url, $options);
return $this->getResponse($request);
}
/**
* Verifies that all required options have been passed.
*
* @param array $options
* @return void
* @throws RuntimeException
* @throws InvalidArgumentException
*/
private function assertRequiredCommandOptions($command, array $options = [])
{
$apiList = $this->getApiList();
if (! array_key_exists($command, $apiList)) {
throw new RuntimeException(
"Call to unsupported API command [{$command}], this call is not present in the API list."
);
}
foreach ($apiList[$command]['params'] as $key => $value) {
if (! array_key_exists($key, $options) && (bool) $value['required']) {
throw new InvalidArgumentException(
"Missing argument [{$key}] for command [{$command}] must be of type [{$value['type']}]."
);
}
}
}
/**
* Returns command method based on the command.
*
* @param string $command
* @return array
*/
public function getCommandMethod($command)
{
if (in_array($command, ['login', 'deployVirtualMachine'])) {
return self::METHOD_POST;
}
return self::METHOD_GET;
}
/**
* Builds the command URL's query string.
*
* @param array $params
* @return string
*/
public function getCommandQuery(array $params)
{
return $this->signCommandParameters($params);
}
/**
* Builds the authorization URL.
*
* @param string $command
* @param array $options
* @return string
*/
public function getCommandUrl($command, array $options = [])
{
$base = $this->urlApi;
$params = $this->getCommandParameters($command, $options);
$query = $this->getCommandQuery($params);
return $this->appendQuery($base, $query);
}
/**
* Returns command parameters based on provided options.
*
* @param string $command
* @param array $options
* @return array
*/
protected function getCommandParameters($command, array $options)
{
return array_merge($options, [
'command' => $command,
'response' => 'json',
'apikey' => $this->apiKey,
]);
}
/**
* Signs the command parameters.
*
* @param array $params
* @return array
*/
protected function signCommandParameters(array $params = [])
{
if ($this->isSsoEnabled() && is_null($this->ssoKey)) {
throw new InvalidArgumentException(
'Required options not defined: ssoKey'
);
}
ksort($params);
$query = $this->buildQueryString($params);
$key = $this->isSsoEnabled() ? $this->ssoKey : $this->secretKey;
$signature = rawurlencode(base64_encode(hash_hmac(
'SHA1',
strtolower($query),
$key,
true
)));
// Reset SSO signing for the next request.
$this->ssoEnabled = false;
// To prevent the signature from being escaped we simply append
// the signature to the previously build query.
return $query . '&signature=' . $signature;
}
/**
* Get Cloudstack Client API list.
*
* Tries to load the API list from the cache directory when
* the 'apiList' on the class is empty.
*
* @return array
* @throws RuntimeException
*/
public function getApiList()
{
if (is_null($this->apiList)) {
$path = __DIR__ . '/../cache/api_list.php';
if (! file_exists($path)) {
throw new RuntimeException(
"Cloudstack Client API list not found. This file needs to be generated before using the client."
);
}
$this->apiList = require $path;
}
return $this->apiList;
}
/**
* Set Cloudstack Client API list.
*
* @param array $apiList
* @return void
*/
public function setApiList(array $apiList)
{
$this->apiList = $apiList;
}
/**
* Appends a query string to a URL.
*
* @param string $url
* @param string $query
* @return string
*/
protected function appendQuery($url, $query)
{
$query = trim($query, '?&');
if ($query) {
return $url . '?' . $query;
}
return $url;
}
/**
* Build a query string from an array.
*
* @param array $params
* @return string
*/
protected function buildQueryString(array $params)
{
return http_build_query($params, false, '&', PHP_QUERY_RFC3986);
}
/**
* Checks a provider response for errors.
*
* @param ResponseInterface $response
* @param array|string $data
* @return void
* @throws \PCextreme\Cloudstack\Exceptions\ClientException
*/
protected function checkResponse(ResponseInterface $response, $data)
{
// Cloudstack returns multidimensional responses, keyed with the
// command name. To handle errors in a generic way we need to 'reset'
// the data array. To prevent strings from breaking this we ensure we
// have an array to begin with.
$data = is_array($data) ? $data : [$data];
if (isset(reset($data)[$this->responseError])) {
$error = reset($data)[$this->responseError];
$code = $this->responseCode ? reset($data)[$this->responseCode] : 0;
throw new ClientException($error, $code, $data);
}
}
/**
* Enable SSO key signing for the next request.
*
* @param bool $enable
* @return self
*/
public function enableSso($enable = true)
{
$this->ssoEnabled = $enable;
return $this;
}
/**
* Determine if SSO signing is enabled.
*
* @return bool
*/
public function isSsoEnabled()
{
return $this->ssoEnabled;
}
/**
* Handle dynamic method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
array_unshift($parameters, $method);
return call_user_func_array(array($this, 'command'), $parameters);
}
}