-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathganeti-rapi.php
More file actions
414 lines (353 loc) · 14.2 KB
/
ganeti-rapi.php
File metadata and controls
414 lines (353 loc) · 14.2 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
/*
Copyright (C) 2012 Raphaël Enrici / Root 42 / Garage Developer
This program is free software; you can redistribute it and/or modify
it under the terms of the license chosen by its author
As of september 2012:
Currently the license is not definitely chosen, if you are in doubt
consider this work as GPL either version 2 or later although we may
chose something more friendly with commercial products in a near
future (BSD or Artistic).
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Please note that most of the work done here is mostly inspired by
the original python code of the RAPI client that you can find on the
ganeti repository. Please see: http://code.google.com/p/ganeti/
*/
namespace ganeti\rapi;
// Active assert
assert_options(ASSERT_ACTIVE, 1);
class GanetiRapiClient
{
const GANETI_RAPI_VERSION = 2;
const USER_AGENT = 'PHP Ganeti RAPI Client';
const HTTP_DELETE = "DELETE";
const HTTP_GET = "GET";
const HTTP_PUT = "PUT";
const HTTP_POST = "POST";
const HTTP_OK = 200;
const HTTP_NOT_FOUND = 404;
const HTTP_APP_JSON = "application/json";
const REPLACE_DISK_PRI = "replace_on_primary";
const REPLACE_DISK_SECONDARY = "replace_on_secondary";
const REPLACE_DISK_CHG = "replace_new_secondary";
const REPLACE_DISK_AUTO = "replace_auto";
const NODE_EVAC_PRI = "primary-only";
const NODE_EVAC_SEC = "secondary-only";
const NODE_EVAC_ALL = "all";
const NODE_ROLE_DRAINED = "drained";
const NODE_ROLE_MASTER_CANDIATE = "master-candidate";
const NODE_ROLE_MASTER = "master";
const NODE_ROLE_OFFLINE = "offline";
const NODE_ROLE_REGULAR = "regular";
const JOB_STATUS_QUEUED = "queued";
const JOB_STATUS_WAITING = "waiting";
const JOB_STATUS_CANCELING = "canceling";
const JOB_STATUS_RUNNING = "running";
const JOB_STATUS_CANCELED = "canceled";
const JOB_STATUS_SUCCESS = "success";
const JOB_STATUS_ERROR = "error";
private static $JOB_STATUS_FINALIZED = array(
JOB_STATUS_CANCELED => JOB_STATUS_CANCELED,
JOB_STATUS_SUCCESS => JOB_STATUS_SUCCESS,
JOB_STATUS_ERROR => JOB_STATUS_ERROR,
);
private $host;
private $port;
private $username;
private $password;
private $baseUrl;
// function GanetiRapiClient($host, $port=5080, $username=NULL,
function __construct($host, $port=5080, $username=NULL,
$password=NULL)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
try {
$address = inet_pton("$host");
if(strlen($address) == 4) {
# IPV4
$this->baseUrl = "https://$host:$port";
} elseif (strlen($address) == 16) {
# IPV6
$this->baseUrl = 'https://[$host]:$port';
} else {
# We should never get here
# TODO: RAISE AN ERROR ?
echo 'FIXME: WE SHOULD NOT BE THERE\n';
}
} catch (\Exception $e) {
# TODO: handle this correctly
echo 'Exception received: ', $e->getMessage() , "\n";
}
if (!is_null($username)) {
if (is_null($password))
throw new \Exception('Password not specified');
} elseif (!is_null($password)) {
throw new \Exception('Specified password without username');
}
}
private function createCurl() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_NOSIGNAL, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, self::USER_AGENT);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: ".self::HTTP_APP_JSON,
"Content-Type: ".self::HTTP_APP_JSON,
));
# TODO: reproduce assert from client.py
if (!is_null($this->username)) {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD,
$this->username.":".$this->password);
}
# TODO: reproduce curl callables from client.py
# curl_setopt($ch, CURLOPT_SSLVERSION, 3);
# curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
# curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
# curl_setopt($ch, CURLOPT_HEADER, false);
# curl_setopt($ch, CURLOPT_POST, true);
# curl_setopt($ch, CURLOPT_POSTFIELDS, $p );
# curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# curl_setopt($ch, CURLOPT_URL, $submit_url);
return $ch;
}
private static function encodeQuery($query) {
# TODO: please code me
$result = array();
/* while (list($name,$value) = each($query)) {
//foreach ($query as $e) {
list($name,$value) = $e;
print "name: $name\n";
print "value: $value\n";
}
*/
// TOERASE:
$result = $query;
return $result;
}
private function sendRequest($method,$path,$query=NULL,$content=NULL) {
/*
Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
@type method: string
@param method: HTTP method to use
@type path: string
@param path: HTTP URL path
@type query: list of two-tuples
@param query: query arguments to pass to urllib.urlencode
@type content: str or None
@param content: HTTP body content
@rtype: str
@return: JSON-Decoded response
@raises CertificateError: If an invalid SSL certificate is found
@raises GanetiApiError: If an invalid response is returned
*/
assert($path[0] == '/');
$ch = $this->createCurl();
$encodedContent = "";
if (!is_null($content))
$encodedContent = json_encode($content);
$urlParts = array($this->baseUrl,$path);
if (!is_null($query)) {
array_push($urlParts,'?');
array_push($urlParts,http_build_query($this->encodeQuery($query)));
}
$url = implode($urlParts);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "".$method);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedContent);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ( ! $response = curl_exec($ch) ) {
$err = curl_error($ch);
$errnum = curl_errno($ch);
# TODO bis: make 60 an 77 explicit constants
# _CURLE_SSL_CACERT = 60
# _CURLE_SSL_CACERT_BADFILE = 77
# TODO: code CertificateError Exception type
if ($errnum == 60 || $errnum == 77)
throw new \Exception('SSL certificate error '.$err);
curl_setopt($ch, CURLOPT_POSTFIELDS, "" );
# TODO: code GanetiApiError Exception type
throw new \Exception('GANETI API error '.$err);
}
# Get HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
# When asking RAPI server for the version, the result is not
# json encoded... So we return the result as is
if ( !$responseContent = json_decode($response) )
$responseContent = $response;
if ($httpCode != self::HTTP_OK) {
if (gettype($responseContent) == 'object') {
$msg = $responseContent->code." ".
$responseContent->message.": ".
$responseContent->explain;
} else
$msg = $responseContent;
#TODO: code GanetiApiError throw new Exception('GANETI API error '.$msg,
# $code = $httpCode);
throw new \Exception('GANETI API error '.$msg);
}
return $responseContent;
}
public function getVersion() {
return $this->sendRequest(self::HTTP_GET, "/version");
}
public function getFeatures() {
# TODO: add checks as they are written in the client.py
return $this->sendRequest(self::HTTP_GET, "/".self::GANETI_RAPI_VERSION."/features");
}
public function getOperatingSystems() {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/os",
NULL,NULL);
}
public function getInfo() {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/info",
NULL,NULL);
}
public function redistributeConfig() {
return $this->sendRequest(self::HTTP_PUT,
"/".self::GANETI_RAPI_VERSION."/redistribute-config",
NULL,NULL);
}
public function modifyCluster($body=array()) {
return $this->sendRequest(self::HTTP_PUT,
"/".self::GANETI_RAPI_VERSION."/modify",
NULL,$body);
}
public function getClusterTags() {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/tags",
NULL,NULL);
}
public function addClusterTags($tags,$dryRun=FALSE) {
// TODO: please code me
/*return $this->sendRequest(self::HTTP_PUT,
"/".self::GANETI_RAPI_VERSION."/tags",
$query,NULL);
*/
}
public function deleteClusterTags($tags,$dryRun=FALSE) {
// TODO: please code me
/*return $this->sendRequest(self::HTTP_DELETE,
"/".self::GANETI_RAPI_VERSION."/tags",
$query,NULL);
*/
}
public function getInstances($bulk=FALSE) {
$query=array();
if ($bulk)
$query["bulk"] = 1;
$instances = $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/instances",
$query,NULL);
if ($bulk)
return $instances;
else {
// TODO: please CHECK ME
// return [i["id"] for i in instances]
//print_r($instances);
$result=array();
foreach ($instances as $i) {
array_push($result,$i->id);
}
return $result;
}
}
public function getInstance($instance) {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/instances/".$instance,
NULL,NULL);
}
public function getInstanceInfo($instance, $static=NULL) {
$query=array();
if ($rebootType)
$query["static"] = $static;
else
$query = NULL;
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/instances/".$instance."/info",
$query,NULL);
}
public function rebootInstance($instance, $rebootType = NULL,
$ignoreSecondaries = NULL,
$dryRun = FALSE) {
$query=array();
if ($rebootType)
$query["type"] = $rebootType;
if ($ignoreSecondaries)
$query["ignore_secondaries"] = $ignoreSecondaries;
if ($dryRun)
$query["dry-run"] = 1;
return $this->sendRequest(self::HTTP_POST,
"/".self::GANETI_RAPI_VERSION."/instances/".$instance."/reboot",
$query,NULL);
}
public function shutdownInstance($instance,$dryRun = FALSE,
$noRemember = FALSE) {
$query=array();
if ($dryRun)
$query["dry-run"] = 1;
if ($noRemember)
$query["no-remember"] = 1;
return $this->sendRequest(self::HTTP_PUT,
"/".self::GANETI_RAPI_VERSION."/instances/".$instance."/shutdown",
$query,NULL);
}
public function getInstanceConsole($instance) {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/instances/".$instance."/console",
NULL,NULL);
}
public function getJobs() {
$jobs = $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/jobs",
NULL,NULL);
$result=array();
foreach ($jobs as $i) {
array_push($result,$i->id);
}
return $result;
}
public function getJobStatus($jobId) {
return $this->sendRequest(self::HTTP_GET,
"/".self::GANETI_RAPI_VERSION."/jobs/".$jobId,
$query,NULL);
}
public function waitForJobCompletion($jobId,$period=5,$retries=-1) {
while($retries != 0) {
$jobRes = $this->getJobStatus($jobId);
if($jobRes && $jobRes->status == self::JOB_STATUS_SUCCESS) {
return TRUE;
} elseif (!$jobRes ||
in_array($jobRes->status,self::$JOB_STATUS_FINALIZED)) {
return FALSE;
}
if ($period)
sleep($period);
if ($retries > 0)
$retries--;
}
return FALSE;
}
public function cancelJob($jobId, $dryRun = FALSE) {
$query=array();
if ($dryRun)
$query["dry-run"] = 1;
return $this->sendRequest(self::HTTP_DELETE,
"/".self::GANETI_RAPI_VERSION."/jobs/".$jobId,
$query,NULL);
}
}