-
Notifications
You must be signed in to change notification settings - Fork 62
/
pve2_api.class.php
executable file
·589 lines (532 loc) · 17.2 KB
/
pve2_api.class.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
<?php
/*
Proxmox VE APIv2 (PVE2) Client - PHP Class
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class PVE2_Exception extends RuntimeException {}
class PVE2_API {
protected $hostname;
protected $username;
protected $realm;
protected $password;
protected $port;
protected $verify_ssl;
protected $login_ticket = null;
protected $login_ticket_timestamp = null;
protected $cluster_node_list = null;
public function __construct ($hostname, $username, $realm, $password, $port = 8006, $verify_ssl = false) {
if (empty($hostname) || empty($username) || empty($realm) || empty($password) || empty($port)) {
throw new PVE2_Exception("Hostname/Username/Realm/Password/Port required for PVE2_API object constructor.", 1);
}
// Check hostname resolves.
if (gethostbyname($hostname) == $hostname && !filter_var($hostname, FILTER_VALIDATE_IP)) {
throw new PVE2_Exception("Cannot resolve {$hostname}.", 2);
}
// Check port is between 1 and 65535.
if (!filter_var($port, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 65535]])) {
throw new PVE2_Exception("Port must be an integer between 1 and 65535.", 6);
}
// Check that verify_ssl is boolean.
if (!is_bool($verify_ssl)) {
throw new PVE2_Exception("verify_ssl must be boolean.", 7);
}
$this->hostname = $hostname;
$this->username = $username;
$this->realm = $realm;
$this->password = $password;
$this->port = $port;
$this->verify_ssl = $verify_ssl;
}
/*
* bool login ()
* Performs login to PVE Server using JSON API, and obtains Access Ticket.
*/
public function login () {
// Prepare login variables.
$login_postfields = array();
$login_postfields['username'] = $this->username;
$login_postfields['password'] = $this->password;
$login_postfields['realm'] = $this->realm;
$login_postfields_string = http_build_query($login_postfields);
unset($login_postfields);
// Perform login request.
$prox_ch = curl_init();
curl_setopt($prox_ch, CURLOPT_URL, "https://{$this->hostname}:{$this->port}/api2/json/access/ticket");
curl_setopt($prox_ch, CURLOPT_POST, true);
curl_setopt($prox_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($prox_ch, CURLOPT_POSTFIELDS, $login_postfields_string);
curl_setopt($prox_ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
curl_setopt($prox_ch, CURLOPT_SSL_VERIFYHOST, $this->verify_ssl);
$login_ticket = curl_exec($prox_ch);
$login_request_info = curl_getinfo($prox_ch);
curl_close($prox_ch);
unset($prox_ch);
unset($login_postfields_string);
if (!$login_ticket) {
// SSL negotiation failed or connection timed out
$this->login_ticket_timestamp = null;
return false;
}
$login_ticket_data = json_decode($login_ticket, true);
if ($login_ticket_data == null || $login_ticket_data['data'] == null) {
// Login failed.
// Just to be safe, set this to null again.
$this->login_ticket_timestamp = null;
if ($login_request_info['ssl_verify_result'] == 1) {
throw new PVE2_Exception("Invalid SSL cert on {$this->hostname} - check that the hostname is correct, and that it appears in the server certificate's SAN list. Alternatively set the verify_ssl flag to false if you are using internal self-signed certs (ensure you are aware of the security risks before doing so).", 4);
}
return false;
} else {
// Login success.
$this->login_ticket = $login_ticket_data['data'];
// We store a UNIX timestamp of when the ticket was generated here,
// so we can identify when we need a new one expiration-wise later
// on...
$this->login_ticket_timestamp = time();
$this->reload_node_list();
return true;
}
}
# Sets the PVEAuthCookie
# Attetion, after using this the user is logged into the web interface aswell!
# Use with care, and DO NOT use with root, it may harm your system
public function setCookie() {
if (!$this->check_login_ticket()) {
throw new PVE2_Exception("Not logged into Proxmox host. No Login access ticket found or ticket expired.", 3);
}
setrawcookie("PVEAuthCookie", $this->login_ticket['ticket'], 0, "/");
}
/*
* bool check_login_ticket ()
* Checks if the login ticket is valid still, returns false if not.
* Method of checking is purely by age of ticket right now...
*/
protected function check_login_ticket () {
if ($this->login_ticket == null) {
// Just to be safe, set this to null again.
$this->login_ticket_timestamp = null;
return false;
}
if ($this->login_ticket_timestamp >= (time() + 7200)) {
// Reset login ticket object values.
$this->login_ticket = null;
$this->login_ticket_timestamp = null;
return false;
} else {
return true;
}
}
/*
* object action (string action_path, string http_method[, array put_post_parameters])
* This method is responsible for the general cURL requests to the JSON API,
* and sits behind the abstraction layer methods get/put/post/delete etc.
*/
private function action ($action_path, $http_method, $put_post_parameters = null) {
// Check if we have a prefixed / on the path, if not add one.
if (substr($action_path, 0, 1) != "/") {
$action_path = "/".$action_path;
}
if (!$this->check_login_ticket()) {
throw new PVE2_Exception("Not logged into Proxmox host. No Login access ticket found or ticket expired.", 3);
}
// Prepare cURL resource.
$prox_ch = curl_init();
curl_setopt($prox_ch, CURLOPT_URL, "https://{$this->hostname}:{$this->port}/api2/json{$action_path}");
$put_post_http_headers = array();
$put_post_http_headers[] = "CSRFPreventionToken: {$this->login_ticket['CSRFPreventionToken']}";
// Lets decide what type of action we are taking...
switch ($http_method) {
case "GET":
// Nothing extra to do.
break;
case "PUT":
curl_setopt($prox_ch, CURLOPT_CUSTOMREQUEST, "PUT");
// Set "POST" data.
$action_postfields_string = http_build_query($put_post_parameters);
curl_setopt($prox_ch, CURLOPT_POSTFIELDS, $action_postfields_string);
unset($action_postfields_string);
// Add required HTTP headers.
curl_setopt($prox_ch, CURLOPT_HTTPHEADER, $put_post_http_headers);
break;
case "POST":
curl_setopt($prox_ch, CURLOPT_POST, true);
// Set POST data.
$action_postfields_string = http_build_query($put_post_parameters);
curl_setopt($prox_ch, CURLOPT_POSTFIELDS, $action_postfields_string);
unset($action_postfields_string);
// Add required HTTP headers.
curl_setopt($prox_ch, CURLOPT_HTTPHEADER, $put_post_http_headers);
break;
case "DELETE":
curl_setopt($prox_ch, CURLOPT_CUSTOMREQUEST, "DELETE");
// No "POST" data required, the delete destination is specified in the URL.
// Add required HTTP headers.
curl_setopt($prox_ch, CURLOPT_HTTPHEADER, $put_post_http_headers);
break;
default:
throw new PVE2_Exception("Error - Invalid HTTP Method specified.", 5);
return false;
}
curl_setopt($prox_ch, CURLOPT_HEADER, true);
curl_setopt($prox_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($prox_ch, CURLOPT_COOKIE, "PVEAuthCookie=".$this->login_ticket['ticket']);
curl_setopt($prox_ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($prox_ch, CURLOPT_SSL_VERIFYHOST, false);
$action_response = curl_exec($prox_ch);
curl_close($prox_ch);
unset($prox_ch);
$split_action_response = explode("\r\n\r\n", $action_response, 2);
$header_response = $split_action_response[0];
$body_response = $split_action_response[1];
$action_response_array = json_decode($body_response, true);
$action_response_export = var_export($action_response_array, true);
// Per GH Issues #45/#47, commenting and may later expose this via option.
// error_log("----------------------------------------------\n" .
// "FULL RESPONSE:\n\n{$action_response}\n\nEND FULL RESPONSE\n\n" .
// "Headers:\n\n{$header_response}\n\nEnd Headers\n\n" .
// "Data:\n\n{$body_response}\n\nEnd Data\n\n" .
// "RESPONSE ARRAY:\n\n{$action_response_export}\n\nEND RESPONSE ARRAY\n" .
// "----------------------------------------------");
unset($action_response);
unset($action_response_export);
// Parse response, confirm HTTP response code etc.
$split_headers = explode("\r\n", $header_response);
if (substr($split_headers[0], 0, 9) == "HTTP/1.1 ") {
$split_http_response_line = explode(" ", $split_headers[0]);
if ($split_http_response_line[1] == "200") {
if ($http_method == "PUT") {
return true;
} else {
return $action_response_array['data'];
}
} else {
error_log("This API Request Failed.\n" .
"HTTP Response - {$split_http_response_line[1]}\n" .
"HTTP Error - {$split_headers[0]}");
return false;
}
} else {
error_log("Error - Invalid HTTP Response.\n" . var_export($split_headers, true));
return false;
}
if (!empty($action_response_array['data'])) {
return $action_response_array['data'];
} else {
error_log("\$action_response_array['data'] is empty. Returning false.\n" .
var_export($action_response_array['data'], true));
return false;
}
}
/*
* array reload_node_list ()
* Returns the list of node names as provided by /api2/json/nodes.
* We need this for future get/post/put/delete calls.
* ie. $this->get("nodes/XXX/status"); where XXX is one of the values from this return array.
*/
public function reload_node_list () {
$node_list = $this->get("/nodes");
if (count($node_list) > 0) {
$nodes_array = array();
foreach ($node_list as $node) {
$nodes_array[] = $node['node'];
}
$this->cluster_node_list = $nodes_array;
return true;
} else {
error_log(" Empty list of nodes returned in this cluster.");
return false;
}
}
/*
* array get_node_list ()
*
*/
public function get_node_list () {
// We run this if we haven't queried for cluster nodes as yet, and cache it in the object.
if ($this->cluster_node_list == null) {
if ($this->reload_node_list() === false) {
return false;
}
}
return $this->cluster_node_list;
}
/*
* bool|int get_next_vmid ()
* Get Last VMID from a Cluster or a Node
* returns a VMID, or false if not found.
*/
public function get_next_vmid () {
$vmid = $this->get("/cluster/nextid");
if ($vmid == null) {
return false;
} else {
return $vmid;
}
}
/*
* array get_vms ()
* Get List of all vms
*/
public function get_vms () {
$node_list = $this->get_node_list();
$result=[];
if (count($node_list) > 0) {
foreach ($node_list as $node_name) {
$vms_list = $this->get("nodes/" . $node_name . "/qemu/");
if (count($vms_list) > 0) {
$key_values = array_column($vms_list, 'vmid');
array_multisort($key_values, SORT_ASC, $vms_list);
foreach($vms_list as &$row) {
$row[node] = $node_name;
}
$result = array_merge($result, $vms_list);
}
if (count($result) > 0) {
$this->$cluster_vms_list = $result;
return $this->$cluster_vms_list;
} else {
error_log(" Empty list of vms returned in this cluster.");
return false;
}
}
} else {
error_log(" Empty list of nodes returned in this cluster.");
return false;
}
}
/*
* bool|int start_vm ($node,$vmid)
* Start specific vm
*/
public function start_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/status/start";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Started vm " . $vmid . "");
return true;
} else {
error_log("Error starting vm " . $vmid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int shutdown_vm ($node,$vmid)
* Gracefully shutdown specific vm
*/
public function shutdown_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
"timeout" => 60,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/status/shutdown";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Shutdown vm " . $vmid . "");
return true;
} else {
error_log("Error shutting down vm " . $vmid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int stop_vm ($node,$vmid)
* Force stop specific vm
*/
public function stop_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
"timeout" => 60,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/status/stop";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Stopped vm " . $vmid . "");
return true;
} else {
error_log("Error stopping vm " . $vmid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int resume_vm ($node,$vmid)
* Resume from suspend specific vm
*/
public function resume_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/status/resume";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Resumed vm " . $vmid . "");
return true;
} else {
error_log("Error resuming vm " . $vmid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int suspend_vm ($node,$vmid)
* Suspend specific vm
*/
public function suspend_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/status/suspend";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Suspended vm " . $vmid . "");
return true;
} else {
error_log("Error suspending vm " . $vmid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int clone_vm ($node,$vmid)
* Create fullclone of vm
*/
public function clone_vm ($node,$vmid) {
if(isset($vmid) && isset($node)){
$lastid = $this->get_next_vmid();
$parameters = array(
"vmid" => $vmid,
"node" => $node,
"newid" => $lastid,
"full" => true,
);
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/clone";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Cloned vm " . $vmid . " to " . $lastid . "");
return true;
} else {
error_log("Error cloning vm " . $vmid . " to " . $lastid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|int snapshot_vm ($node,$vmid,$snapname = NULL)
* Create snapshot of vm
*/
public function snapshot_vm ($node,$vmid,$snapname = NULL) {
if(isset($vmid) && isset($node)){
$lastid = $this->get_next_vmid();
if (is_null($snapname)){
$parameters = array(
"vmid" => $vmid,
"node" => $node,
"vmstate" => true,
);
} else {
$parameters = array(
"vmid" => $vmid,
"node" => $node,
"vmstate" => true,
"snapname" => $snapname,
);
}
$url = "/nodes/" . $node . "/qemu/" . $vmid . "/snapshot";
$post = $this->post($url,$parameters);
if ($post) {
error_log("Cloned vm " . $vmid . " to " . $lastid . "");
return true;
} else {
error_log("Error cloning vm " . $vmid . " to " . $lastid . "");
return false;
}
} else {
error_log("no vm or node valid");
return false;
}
}
/*
* bool|string get_version ()
* Return the version and minor revision of Proxmox Server
*/
public function get_version () {
$version = $this->get("/version");
if ($version == null) {
return false;
} else {
return $version['version'];
}
}
/*
* object/array? get (string action_path)
*/
public function get ($action_path) {
return $this->action($action_path, "GET");
}
/*
* bool put (string action_path, array parameters)
*/
public function put ($action_path, $parameters) {
return $this->action($action_path, "PUT", $parameters);
}
/*
* bool post (string action_path, array parameters)
*/
public function post ($action_path, $parameters) {
return $this->action($action_path, "POST", $parameters);
}
/*
* bool delete (string action_path)
*/
public function delete ($action_path) {
return $this->action($action_path, "DELETE");
}
// Logout not required, PVEAuthCookie tokens have a 2 hour lifetime.
}
?>