forked from sazze/phpChef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chef.php
526 lines (456 loc) · 17 KB
/
Chef.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
<?php
/**
* Defines the Chef class
*
* A wrapper for the Chef HTTP API.
*
* PHP version 5
*
* @package framework.php
* @author Daniel Aharon <[email protected]>
* @license http://www.gnu.org/licenses/lgpl.html LGPL
* @copyright 2011 Sazze, Inc.
*/
namespace chef {
class Chef {
private $host;
private $port;
private $privateKey;
private $userId;
private $version;
/**
* Chef::__construct()
*
* Set the variables used for every request.
*
* @param string $hostname FQDN or IP address of the Chef server.
* @param integer $port The port that the Chef server is listening on.
* @param string $userId The client name associated with the private key.
* @param string $privateKey Either the key itself, or the filename containing the key.
* @param string $chefVersion The Chef server version.
*/
public function __construct($host, $port, $userId, $privateKey, $chefVersion = '0.9.12') {
$this->host = $host;
$this->port = $port;
$this->userId = $userId;
$this->version = $chefVersion;
if (file_exists($privateKey)) {
$this->privateKey = file_get_contents($privateKey);
} else {
$this->privateKey = $privateKey;
}
}
/**
* Chef::factory()
*
* Return a Chef instance.
*
* @param string $hostname FQDN or IP address of the Chef server.
* @param integer $port The port that the Chef server is listening on.
* @param string $privateKey Either the key itself, or the filename containing the key.
* @param string $userId The client name associated with the private key.
* @param string $chefVersion The Chef server version.
*
* @return Chef An instance of the Chef class.
*/
public static function factory($hostname, $port, $privateKey, $userId, $chefVersion = '0.9.12') {
return new static($hostname, $port, $privateKey, $userId, $chefVersion);
}
/**
* Chef::searchIndexes()
*
* @return array A list of the indexes available for search on the Chef server.
*/
public function searchIndexes() {
$uri = '/search';
return $this->httpGet($uri);
}
/**
* Chef::search()
*
* Search a Chef server index.
*
* @param string $indexName The index to search.
* @param string $searchString A valid search string. eg: 'recipes:"php::fpm"'
* @param string $sort Sort the results by the specified attribute.
* @param integer $start The result number to start from.
* @param integer $rows How many rows to return.
*
* @return array The result set.
*/
public function search($indexName, $searchString, $sort = '', $start = 0, $rows = 9999) {
$uri = '/search/' . $indexName;
$queryString = array(
'q=' . urlencode($searchString),
'rows=' . $rows
);
if ($start > 0) {
$queryString[] = 'start=' . $start;
}
// Perform the search.
$result = $this->httpGet($uri, join('&', $queryString));
// Sort the results.
if (!empty($sort)) {
static::sortSearchResult($result, $sort);
}
return $result;
}
/**
* Chef::getNodes()
*
* Retrieve the list of nodes serviced by the Chef server.
*
* @return array The list of nodes known to the Chef server.
*/
public function getNodes() {
$uri = '/nodes';
return $this->httpGet($uri);
}
/**
* Chef::getNode()
*
* Retrieve the information associated with a specific node.
*
* @param string $nodeName The name of the node.
*
* @return array An associative array containing all known info about the node.
*/
public function getNode($nodeName) {
$uri = '/nodes/' . $nodeName;
return $this->httpGet($uri);
}
/**
* Chef::getNodeRunList()
*
* Retrieve the run list of a specific node.
*
* @param string $nodeName The name of the node.
*
* @return array A list of the roles and recipes in the node's run list.
*/
public function getNodeRunList($nodeName) {
$uri = '/nodes/' . $nodeName . '/cookbooks';
return $this->httpGet($uri);
}
/**
* Chef::getRoles()
*
* Retrieve the list of roles.
*
* @return array The list of roles.
*/
public function getRoles() {
$uri = '/roles';
return $this->httpGet($uri);
}
/**
* Chef::getRole()
*
* Retrieve the specified role information.
*
* @param string $roleName The name of the role.
*
* @return array The roles and recipes contained in the specified role.
*/
public function getRole($roleName) {
$uri = '/roles/' . $roleName;
return $this->httpGet($uri);
}
/**
* Chef::getCookbooks()
*
* @return array A list of cookbooks.
*/
public function getCookbooks() {
$uri = '/cookbooks';
return $this->httpGet($uri);
}
/**
* Chef::getCookbook()
*
* Get the specified cookbook's data.
*
* @param string $cookbookName The name of the cookbook.
*
* @return array An array containing all the cookbook data.
*/
public function getCookbook($cookbookName) {
$uri = '/cookbooks/' . $cookbookName;
return $this->httpGet($uri);
}
/**
* Chef::getDataBags()
*
* Get a list of the data bags on the Chef server.
*
* @return array A list of the data bags on the Chef Server.
*/
public function getDataBags() {
$uri = '/data';
return $this->httpGet($uri);
}
/**
* Chef::getDataBagItems()
*
* Retrieve a list of the items in a data bag.
*
* @param string $dataBagName The name of the data bag.
*
* @return array A list of the items stored in the specified data bag.
*/
public function getDataBagItems($dataBagName) {
$uri = '/data/' . $dataBagName;
return $this->httpGet($uri);
}
/**
* Chef::deleteDataBagItem()
*
* Delete a data bag item.
*
* @param string $dataBagName The name of the data bag containing the item.
* @param string $itemName The name of the data bag item.
*
* @return array The contents of the data bag item.
*/
public function deleteDataBagItem($dataBagName, $itemName) {
$uri = '/data/' . $dataBagName . '/' . $itemName;
return $this->httpDelete($uri);
}
/**
* Chef::getDataBagItem()
*
* Get the contents of a data bag item.
*
* @param string $dataBagName The name of the data bag containing the item.
* @param string $itemID The ID of the data bag item.
*
* @return array The contents of the data bag item.
*/
public function getDataBagItem($dataBagName, $itemID) {
$uri = '/data/' . $dataBagName . '/' . $itemID;
return $this->httpGet($uri);
}
/**
* Chef::postDataBagItem()
*
* Creates a data bag item.
*
* @param string $dataBagName The name of the data bag containing the item.
* @param array $itemContents The JSON formatted contents of the data bag item. Must contain an "id" field.
*
* @return array Response code
*/
public function postDataBagItem($dataBagName, $itemContents) {
$uri = '/data/'. $dataBagName;
return $this->httpPost($uri, $itemContents);
}
/**
* Chef::putDataBagItem()
*
* Updates the contents of a data bag item.
*
* @param string $dataBagName The name of the data bag containing the item.
* @param string $itemID The ID of the data bag item.
* @param array $itemContents The contents of the data bag item.
*
* @return array The contents of the data bag item.
*/
public function putDataBagItem($dataBagName, $itemID, $itemContents) {
$uri = '/data/'. $dataBagName . '/' . $itemID;
return $this->httpPut($uri, $itemContents);
}
/**
* Chef::httpDelete()
*
* Perform a DELETE request to the Chef server.
*
* @param string $uri The request URI.
* @param string $queryString The query string.
*
* @return array An associative array generated from the JSON response.
*/
private function httpDelete($uri) {
$headers = $this->requestHeaders($uri, 'DELETE', '', $this->userId, $this->privateKey);
$headers['X-Chef-Version'] = $this->version;
$headers['Accept'] = 'application/json';
$request = new \HttpRequest(
'http://' . $this->host . ':' . $this->port . $uri,
HTTP_METH_DELETE,
array(
'headers' => $headers
)
);
$response = $request->send();
return json_decode($response->getBody(), true);
}
/**
* Chef::httpGet()
*
* Perform a GET request to the Chef server.
*
* @param string $uri The request URI.
* @param string $queryString The query string (for searching).
*
* @return array An associative array generated from the JSON response.
*/
private function httpGet($uri, $queryString = '') {
$headers = $this->requestHeaders($uri, 'GET', '', $this->userId, $this->privateKey);
$headers['X-Chef-Version'] = $this->version;
$headers['Accept'] = 'application/json';
if (!empty($queryString)) {
$uri .= '?' . $queryString;
}
$request = new \HttpRequest(
'http://' . $this->host . ':' . $this->port . $uri,
HTTP_METH_GET,
array(
'headers' => $headers
)
);
$response = $request->send();
return json_decode($response->getBody(), true);
}
/**
* Chef::httpPut()
*
* Perform a PUT request to the Chef server.
*
* @param string $uri The request URI.
* @param string $queryString The query string.
* @param array $requestBody A JSON object
*
* @return array An associative array generated from the JSON response.
*/
private function httpPut($uri, $requestBody) {
$headers['X-Chef-Version'] = $this->version;
$headers = $this->requestHeaders($uri, 'PUT', $requestBody, $this->userId, $this->privateKey);
$headers['Accept'] = 'application/json';
$request = new \HttpRequest(
'http://' . $this->host . ':' . $this->port . $uri,
HTTP_METH_PUT,
array(
'headers' => $headers
)
);
$request->setContentType('application/json');
$request->addPutData($requestBody);
$response = $request->send();
return json_decode($response->getBody(), true);
}
/**
* Chef::httpPost()
*
* Perform a POST request to the Chef server.
*
* @param string $uri The request URI.
* @param array $requestBody A JSON object
*
* @return array An associative array generated from the JSON response.
*/
private function httpPost($uri, $requestBody) {
$headers['X-Chef-Version'] = $this->version;
$headers = $this->requestHeaders($uri, 'POST', $requestBody, $this->userId, $this->privateKey);
$headers['Accept'] = 'application/json';
$request = new \HttpRequest(
'http://' . $this->host . ':' . $this->port . $uri,
HTTP_METH_POST,
array(
'headers' => $headers
)
);
$request->setContentType('application/json');
$request->addBody($requestBody);
$response = $request->send();
return json_decode($response->getBody(), true);
}
/**
* Chef::requestHeaders()
*
* Generate the encrypted header entries for the Chef request.
*
* @param string $uri The request URI.
* @param string $httpMethod The HTTP request method GET, or PUT. PUT not implemented yet.
* @param string $body The body of the request.
* @param string $userId The Chef server client name.
* @param string $privateKey The RSA private key for the client.
*
* @return array The headers specific to Chef server requests.
*/
private static function requestHeaders($uri, $httpMethod, $body, $userId, $privateKey) {
$timestamp = new \DateTime(null, new \DateTimeZone('UTC'));
$timestamp = substr($timestamp->format(\DateTime::ISO8601), 0, -5) . 'Z';
$hashedBody = base64_encode(sha1($body, true));
$headers = array(
'X-Ops-Sign' => 'version=1.0',
'X-Ops-UserId' => $userId,
'X-Ops-Timestamp' => $timestamp,
'X-Ops-Content-Hash' => $hashedBody
);
$reqSig = static::requestSignature($uri, $httpMethod, $hashedBody, $timestamp, $userId, $privateKey);
for ($index = 0; $index < strlen($reqSig); $index += 60) {
$key = 'X-Ops-Authorization-' . (string) (($index / 60) + 1);
$headers[$key] = substr($reqSig, $index, 60);
}
return $headers;
}
/**
* Chef::requestSignature()
*
* @param string $uri The request URI.
* @param string $httpMethod The HTTP request method GET, or PUT. PUT not implemented yet.
* @param string $hashedBody The hashed (base64 encoded SHA1) body of the request.
* @param string $timestamp ISO 8601 format using T as the separator. The timezone must be UTC, using Z as the indicator. eg: 2010-12-04T15:47:49Z
* @param string $userId The Chef server client name.
* @param string $privateKey The RSA private key for the client.
*/
private static function requestSignature($uri, $httpMethod, $hashedBody, $timestamp, $userId, $privateKey) {
$httpMethod = strtoupper($httpMethod);
$hashedUri = base64_encode(sha1($uri, true));
$reqSig =
"Method:$httpMethod\n" .
"Hashed Path:$hashedUri\n" .
"X-Ops-Content-Hash:$hashedBody\n" .
"X-Ops-Timestamp:$timestamp\n" .
"X-Ops-UserId:$userId";
openssl_private_encrypt($reqSig, $crypted, $privateKey);
return base64_encode($crypted);
}
/**
* Chef::arrayFlatten()
*
* Create a flattened copy of an array.
*
* @param array $arr The array to flatten. Duplicate keys will be overwritten.
*
* @return array A copy of the array that has been flattened.
*/
private static function arrayFlatten(array $arr) {
$output = array();
array_walk_recursive(
$arr,
function($value, $key) use (&$output) {
$output[$key] = $value;
}
);
return $output;
}
private static function arrayKeySearch($key, $arr) {
$arrIt = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
foreach ($arrIt as $sub) {
$subArray = $arrIt->getSubIterator();
if (array_key_exists($key, $subArray)) {
return $subArray[$key];
}
}
return null;
}
private static function sortSearchResult(&$arr, $sortBy) {
$values = array();
foreach ($arr['rows'] as $element) {
$values[] = static::arrayKeySearch($sortBy, $element);
}
array_multisort($values, $arr['rows']);
}
}
}
?>