forked from caffedrine/scaleway-whmcs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scaleway.php
1859 lines (1617 loc) · 65.9 KB
/
scaleway.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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Copyright (c) 2016 1WAY HOSTING (https://1way.pro)
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.
*/
// ___ __ _
// / __\___ _ __ / _(_) __ _
// / / / _ \| '_ \| |_| |/ _` |
// / /__| (_) | | | | _| | (_| |
// \____/\___/|_| |_|_| |_|\__, |
// |___/
if (!defined("WHMCS"))
die("This file cannot be accessed directly _|_");
//I have changed paths in those classes in order to make'em work. I don't like this too...
define(MODDIR, $_SERVER['DOCUMENT_ROOT'] . "/modules/servers/scaleway/");
include(MODDIR . 'lib/phpseclib104/Net/SSH2.php');
include(MODDIR . 'lib/phpseclib104/Crypt/RSA.php');
// _ ____ ___ ____ _ _ _ ____
// / \ | _ \_ _| / ___| / \ | | | | / ___|
// / _ \ | |_) | | | | / _ \ | | | | \___ \
// / ___ \| __/| | | |___ / ___ \| |___| |___ ___) |
// /_/ \_\_| |___| \____/_/ \_\_____|_____|____/
class ScalewayApi
{
private $token = "";
private $callUrl = "";
// Status codes returned by scaleway
public $statusCodes =
[
"200" => "Scaleway API - OK",
"400" => "Scaleway API - Error 400: bad request. Missing or invalid parameter?",
"201" => "Scaleway API - Error 201: This is not an error but you should not be here!",
"204" => "Scaleway API - Error 204: A delete action performed successfully! You should not be here however!",
"401" => "Scaleway API - Error 401: auth error. No valid API key provided!",
"402" => "Scaleway API - Error 402: request failed. Parameters were valid but request failed!",
"403" => "Scaleway API - Error 403: forbidden. Insufficient privileges to access requested resource or the caller IP may be blacklisted!",
"404" => "Scaleway API - Error 404: not found 404 not found 404 not found 404 not found, what are you looking for?",
"50x" => "Scaleway API - Error 50x: means server error. Dude, this is bad..:(",
//Custom
"123" => "Error 123: means new volume creation failed. This error appear when try to allocate new volume for the new server!"
];
public static $commercialTypes =
[
// Type => processor_cores D[dedicated]/S[hared]C_RAM
"C1" => "ARM_4DC_2GB",
"C2S" => "x86_4DC_8GB",
"C2M" => "x86_8DC_16GB",
"C2L" => "x86_8DC_32GB",
//X64
"X64-2GB" => "x64_6SC_2GB",
"X64-4GB" => "x64_6SC_4GB",
"X64-8GB" => "x64_6SC_8GB",
"X64-15GB" => "x64_6SC_15GB",
"X64-30GB" => "x64_8SC_30GB",
"X64-60GB" => "x64_10SC_60GB",
"X64-120GB" => "x64_12SC_120GB",
//ARMs
"ARM64-2GB" => "ARM_4SC_2GB",
"ARM64-4GB" => "ARM_6SC_4GB",
"ARM64-8GB" => "ARM_8SC_8GB",
//PS: Strange, they say "8 Dedicated x86 64bit", x86 means 32bit...;
];
public static $availableLocations =
[
"Paris" => "par1",
"Amsterdam" => "ams1",
//Let's accept par1 and ams1 as valid locations
"par1" => "par1",
"ams1" => "ams1",
];
function __construct($tokenStr, $location)
{
$this->token = $tokenStr;
//We have to build call url with the right location (par1 or ams1)
//Example: https://cp-par1.scaleway.com
$this->callUrl = "https://cp-" . ScalewayApi::$availableLocations[$location] . ".scaleway.com";
}
// ____ _ _
//| _ \ _ __(_)_ ____ _| |_ ___ ___
//| |_) | '__| \ \ / / _` | __/ _ \/ __|
//| __/| | | |\ V / (_| | || __/\__ \
//|_| |_| |_| \_/ \__,_|\__\___||___/
//
//This is function used to call Scaleway API
private function call_scaleway_api($token, $http_method, $endpoint, $get = array(), $post = array())
{
if ( !empty($get) )
$endpoint .= '?' . http_build_query($get);
$call = curl_init();
if($endpoint == "/organizations")
curl_setopt($call, CURLOPT_URL, 'https://account.scaleway.com' . $endpoint);
else
curl_setopt($call, CURLOPT_URL, $this->callUrl . $endpoint);
curl_setopt($call, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$headers = [
"X-Auth-Token: " . $token,
"Content-Type: application/json"
];
curl_setopt($call, CURLOPT_HTTPHEADER, $headers);
curl_setopt($call, CURLOPT_RETURNTRANSFER, true);
if ($http_method == 'POST')
{
curl_setopt($call, CURLOPT_POST, true);
curl_setopt($call, CURLOPT_POSTFIELDS, json_encode($post));
}
else
{
curl_setopt($call, CURLOPT_POST, true);
curl_setopt($call, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($call, CURLOPT_POSTFIELDS, http_build_query($post));
}
$result = curl_exec($call);
$resultHttpCode = curl_getinfo($call, CURLINFO_HTTP_CODE);
curl_close($call);
if($resultHttpCode == "")
{
$tmpArr = array("message" => "Two possibilities: 1. CURL request to Scaleway failed; you may be behind a firewall! Try this to be sure check with: ping cp-par1.scaleway.com<br>2. Location passed to API is invalid!");
$result = json_encode($tmpArr);
}
//Return an arry with HTTP_CODE returned and the JSON content writen by server.
return array(
"httpCode" => $resultHttpCode,
"json" => $result
);
}
//Function to get ony main organization id as we need it for new created server
private function getMainOrganizationId()
{
$organizationsResult = $this->retrieve_organizations();
$orgReturnCode = $organizationsResult['httpCode'];
$orgJsonCode = $organizationsResult['json'];
if($orgReturnCode == 200)
{
$organizationsArray = json_decode($orgJsonCode, true);
for($i=0; $i < count($organizationsArray['organizations']); $i++)
{
$organization = $organizationsArray['organizations'][$i];
$org_id = $organization['id'];
//We need only first organization ID as there can't be created multiple organizations on a single account.
return $org_id;
break; //Just testing to see if I get warnings, not my paranoia :)
}
}
else
{
echo $this->statusCodes[$orgReturnCode];
}
}
//Server actions are: power on, power off, reboot
private function execute_server_action($action, $server_id)
{
if($action != "poweron" && $action != "poweroff" && $action != "reboot" && $action != "terminate")
{
$resp =
[
"httpCode" => "400",
"json" => "{\"error\" : \"error\"}"
];
return $resp;
}
$http_method = "POST";
$endpoint = "/servers/" . $server_id . "/action";
$postParams =
[
"action" => $action
];
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), $postParams);
return $result;
}
// ____ _ _ _
//| _ \ _ _| |__ | (_) ___ ___
//| |_) | | | | '_ \| | |/ __/ __|
//| __/| |_| | |_) | | | (__\__ \
//|_| \__,_|_.__/|_|_|\___|___/
//
//This function will return an array() with all instanced servers for the $token given
public function retrieve_servers_list()
{
$http_method = "GET";
$endpoint = "/servers";
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//This function return all organizations in JSON format
public function retrieve_organizations()
{
$http_method = "GET";
$endpoint = "/organizations";
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Function to get all images from ImageHub and created by user
public function retrieve_images()
{
$http_method = "GET";
$endpoint = "/images";
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
// Get all avilable volumes created by API owner
public function retrieve_volumes()
{
$http_method = "GET";
$endpoint = "/volumes";
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Create a new volume in order to be able to create a new server
public function create_new_volume($name, $size)
{
$http_method = "POST";
$endpoint = "/volumes";
$organization = $this->getMainOrganizationId();
$volumeType = "l_ssd";
$postParams =
[
"name" => $name,
"organization" => $organization,
"volume_type" => $volumeType,
"size" => $size
];
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), $postParams);
return $result;
}
//Get volume info by ID
public function retrieve_volume_info($id)
{
$http_method = "GET";
$endpoint = "/volumes/" . $id;
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Delete a volume by it's id
public function delete_volume($id)
{
$http_method = "DELETE";
$endpoint = "/volumes/" . $id;
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Function to instantiate a new server
public function create_new_server($name, $image, $commercial_type, $tags)
{
$http_method = "POST";
$endpoint = "/servers";
$organization = $this->getMainOrganizationId();
/*
//We create only one volume for now
$volume = $this->create_new_volume("vol1_" . $name, 50000000000);
if($volume['httpCode'] != 201)
{
//Can't create new volume so return the error encounted!
return $volume;
}
$volArry= json_decode($volume['json'], true);
$vol_id = $volArry['volume']['id'];
//By default, a volume is attached to our server. Use this to add more than one
$volumes =
[
"1" =>
[
"name" => "vol1_" . $name,
//"organization" => $this->getMainOrganizationId()
//"size" => 50,
//"volume_type" => "l_ssd"
"id" => $vol_id
]
];
*/
$postParams =
[
"organization" => $organization,
"name" => $name,
"image" => $image,
"commercial_type" => $commercial_type,
"tags" => $tags,
"enable_ipv6" => false
//"volumes" => $volumes
];
$server_creation_result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), $postParams);
if($server_creation_result['httpCode'] != 210)
{
//If created more than one volumes consider removing it as server creation failed
if(isset($vol_id))
$this->delete_volume($vol_id);
}
//Dirty code, sorry.
$srv_id = json_decode($server_creation_result["json"], true)["server"]["id"];
$this->execute_server_action("poweron", $srv_id);
return $server_creation_result;
}
//Function which return server info
public function retrieve_server_info($server_id)
{
if($server_id == "") //We have to prevent endpoint becaming /servers/{NULL}, it will print all servers and we don't want this!
$server_id = "7b6d2181-0000-0000-0000-3ebd066076f1";
$http_method = "GET";
$endpoint = "/servers/" . $server_id;
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Delete an IPv4 Address
public function delete_ip_address($ip_id)
{
$http_method = "DELETE";
$endpoint = "/ips/" . $ip_id;
$result = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
return $result;
}
//Delete a server by ID. This include IP and Volumes removal
public function server_terminate($server_id)
{
//Retrieve volume id and server state
$call = $this->retrieve_server_info($server_id);
if($call["httpCode"] != 200)
return $call;
$serverState = (json_decode($call["json"], true)["server"]["state"]);
$vol_id_attached = (json_decode($call["json"], true)["server"]["volumes"]["0"]["id"]);
$ip_id_attached = (json_decode($call["json"], true)["server"]["public_ip"]["id"]);
//Easy way
if($serverState == "running")
{
$response = $this->execute_server_action("terminate", $server_id);
return $response;
}
else if($serverState == "stopped") //Hard wa
{
$http_method = "DELETE";
$endpoint = "/servers/" . $server_id;
$response = $this->call_scaleway_api($this->token, $http_method, $endpoint, array(), array());
if ($response["httpCode"] == 204)
{
//We have deleted the server and now we have to delete volume and IP manually
$delVolRes = $this->delete_volume($vol_id_attached);
$delIpRes = $this->delete_ip_address($ip_id_attached);
if($delVolRes["httpCode"] == 204)
{
if ($delIpRes["httpCode"] == 204)
return $response;
else
return $delIpRes;
}
else
return $delVolRes;
}
return $response;
}
else
{
//Server may be booting or pending for an action. In this case we have to try after server get into a valid state
return array (
"httpCode" => "123",
"json" => json_encode(array("message" => "Server is into an intermediate state! Wait for power on/off then try again!"))
);
}
}
//Function used to suspend the server
public function server_poweroff($server_id)
{
//Suspension mean power off and storing volume offline
$result = $this->execute_server_action("poweroff", $server_id);
return $result;
}
//Function to hard reboot the server
public function server_reboot($server_id)
{
$result = $this->execute_server_action("reboot", $server_id);
return $result;
}
//Function to power on an server
public function server_poweron($server_id)
{
$result = $this->execute_server_action("poweron", $server_id);
return $result;
}
}
// ____ _____ ______ _______ ____ ____ __ __ _ _ _ _ ____ _____ __ __ _____ _ _ _____
/// ___|| ____| _ \ \ / / ____| _ \/ ___| | \/ | / \ | \ | | / \ / ___| ____| \/ | ____| \ | |_ _|
//\___ \| _| | |_) \ \ / /| _| | |_) \___ \ | |\/| | / _ \ | \| | / _ \| | _| _| | |\/| | _| | \| | | |
// ___) | |___| _ < \ V / | |___| _ < ___) | | | | |/ ___ \| |\ |/ ___ \ |_| | |___| | | | |___| |\ | | |
//|____/|_____|_| \_\ \_/ |_____|_| \_\____/ |_| |_/_/ \_\_| \_/_/ \_\____|_____|_| |_|_____|_| \_| |_|
// This class is designed to work with servers as it is more easy to use than the API class.
// If an action is not implemented in this class then you'll have to use the main class and implement by yourself.
// It's a kind of wrapper for the main ScalewayAPI class which return JSON.
// It will make your life easier as it already check the response for errors and returns the right message.
class ScalewayServer
{
protected $api = "";
protected $srvLoc = "par1"; //let's set a default value.
public $server_id = "";
//This store the API result. Usefull in case of error.
public $queryInfo = "";
public $state_detail = "";
public $image = array
(
//There are a lot more details, we keep onle those below:
"name" => "",
"arch" => "",
"id" => "",
"root_volume" => array
(
"size" => "",
"id" => "",
"volume_type" => "",
"name" => ""
)
);
public $creation_date = "";
public $public_ip = array
(
"dynamic" => false,
"id" => "",
"address" => ""
);
public $private_ip = "";
public $id = "";
public $dynamic_ip_required = false;
public $modification_date = "";
public $enable_ipv6 = false;
public $hostname = "";
public $state = "";
public $bootscript = array
(
"id" => "",
"kernel" => "",
"title" => ""
);
public $location = array
(
"platform_id" => "",
"node_id" => "",
"blade_id" => "",
"zone_id" => "",
"chassis_id" => ""
);
public $ipv6 = "";
public $commercial_type = "";
public $tags = array();
public $arch = "";
public $extra_networks = array();
public $name = "";
public $volumes = array();
public $security_group = array
(
"id" => "",
"name" => ""
);
public $organization = "";
function __construct($token, $location)
{
$this->srvLoc = $location;
$this->api = new ScalewayApi($token, $this->srvLoc);
}
public function setServerId($srv_id)
{
$this->server_id = $srv_id;
}
public function retrieveDetails()
{
$serverInfoResp = $this->api->retrieve_server_info($this->server_id);
if($serverInfoResp["httpCode"] == 200)
{
$serverInfoResp = json_decode($serverInfoResp["json"], true);
$serverInfoResp = $serverInfoResp["server"];
$this->state_detail = $serverInfoResp["state_detail"];
$this->image["name"] = $serverInfoResp["image"]["name"];
$this->image["arch"] = $serverInfoResp["image"]["arch"];
$this->image["id"] = $serverInfoResp["image"]["id"];
$this->image["root_volume"]["size"] = $serverInfoResp["image"]["root_volume"]["size"];
$this->image["root_volume"]["id"] = $serverInfoResp["image"]["root_volume"]["id"];
$this->image["root_volume"]["volume_type"] = $serverInfoResp["image"]["root_volume"]["volume_type"];
$this->image["root_volume"]["name"] = $serverInfoResp["image"]["root_volume"]["name"];
$this->creation_date = $serverInfoResp["creation_date"];
$this->public_ip["dynamic"] = $serverInfoResp["public_ip"]["dynamic"];
$this->public_ip["id"] = $serverInfoResp["public_ip"]["id"];
$this->public_ip["address"] = $serverInfoResp["public_ip"]["address"];
$this->private_ip = $serverInfoResp["private_ip"];
$this->id = $serverInfoResp["id"];
$this->dynamic_ip_required = $serverInfoResp["dynamic_ip_required"];
$this->modification_date = $serverInfoResp["modification_date"];
$this->enable_ipv6 = $serverInfoResp["enable_ipv6"];
$this->hostname = $serverInfoResp["hostname"];
$this->state = $serverInfoResp["state"];
$this->bootscript["id"] = $serverInfoResp["bootscript"]["id"];
$this->bootscript["kernel"] = $serverInfoResp["bootscript"]["kernel"];
$this->bootscript["title"] = $serverInfoResp["bootscript"]["title"];
$this->location["platform_id"] = $serverInfoResp["location"]["platform_id"];
$this->location["node_id"] = $serverInfoResp["location"]["node_id"];
$this->location["blade_id"] = isset($serverInfoResp["location"]["blade_id"])?$serverInfoResp["location"]["blade_id"]:"";
$this->location["zone_id"] = $serverInfoResp["location"]["zone_id"];
$this->location["chassis_id"] = isset($serverInfoResp["location"]["chassis_id"])?$serverInfoResp["location"]["chassis_id"]:"";
$this->ipv6 = $serverInfoResp["ipv6"];
$this->commercial_type = $serverInfoResp["commercial_type"];
$this->tags = $serverInfoResp["tags"];
$this->arch = $serverInfoResp["arch"];
$this->extra_networks = $serverInfoResp["extra_networks"];
$this->volumes = $serverInfoResp["volumes"];
$this->security_group["id"] = $serverInfoResp["security_group"]["id"];
$this->security_group["name"] = $serverInfoResp["security_group"]["name"];
$this->organization = $serverInfoResp["organization"];
$this->queryInfo = "Success!";
return true;
}
else
{
$this->queryInfo = $this->api->statusCodes[$serverInfoResp["httpCode"]];
return false;
}
}
public function create_new_server($name, $image_id, $commercial_type, $tags = array())
{
$createServerResult = $this->api->create_new_server($name, $image_id, $commercial_type, $tags);
if($createServerResult["httpCode"] == 201)
{
$serverInfo = json_decode($createServerResult["json"], true);
$serverInfo = $serverInfo["server"];
$this->server_id = $serverInfo["id"];
$this->retrieveDetails();
return true;
}
else
{
$this->queryInfo = $this->api->statusCodes[$createServerResult["httpCode"]];
return false;
}
}
public function delete_server()
{
$deleteServerResponse = $this->api->server_terminate($this->server_id);
if($deleteServerResponse["httpCode"] == 202)
{
return true;
}
else
{
$this->queryInfo = json_decode($deleteServerResponse["json"], true)["message"];
return false;
}
}
public function poweroff_server()
{
$poweroff_result = $this->api->server_poweroff($this->server_id);
if( $poweroff_result["httpCode"] == 202)
{
$this->retrieveDetails();
return true;
}
else
{
$this->queryInfo = json_decode($poweroff_result["json"], true)["message"];
return false;
}
}
public function poweron_server()
{
$poweron_result = $this->api->server_poweron($this->server_id);
if( $poweron_result["httpCode"] == 202)
{
$this->retrieveDetails();
return true;
}
else
{
$this->queryInfo = json_decode($poweron_result["json"], true)["message"];
return false;
}
}
public function reboot_server()
{
$reboot_result = $this->api->server_reboot($this->server_id);
if( $reboot_result["httpCode"] == 202)
{
$this->retrieveDetails();
return true;
}
else
{
$this->queryInfo = json_decode($reboot_result["json"], true)["message"];
return false;
}
}
public function update_info_server($newPassword, $newHostname, $puttySSHkey)
{
if( !$this->retrieveDetails() )
{
$this->queryInfo = "Cand access the server. Maybe server ID is invalid?";
return false;
}
if($this->state_detail != "booted" || $this->state != "running")
{
$this->queryInfo = "In order to change the server password it must be up and running!";
return false;
}
$ipAddr = $this->public_ip["address"];
$rsa = new Crypt_RSA();
$rsa->loadKey($puttySSHkey);
$rsa->setPassword();
try
{
$ssh = new Net_SSH2($ipAddr);
if (!$ssh->login("root", $rsa))
{
$this->queryInfo = "Net_SSH2 => failed to login to server via SSH2! => " . ($ssh->isConnected() ? 'bad username or password' : 'unable to establish connection');
return false;
}
$newLoginHead = "IF8gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgDQovIHxfICAgICAgX19fXyBfIF8g".
"ICBfICAgICAgIF8gX18gIF8gX18gX19fICANCnwgXCBcIC9cIC8gLyBfYCB8IHwgfCB8ICAgICB8ICdfIFx8ICdfXy8gXyBcIA0".
"KfCB8XCBWICBWIC8gKF98IHwgfF98IHwgIF8gIHwgfF8pIHwgfCB8IChfKSB8DQp8X3wgXF8vXF8vIFxfXyxffFxfXywgfCAoXy".
"kgfCAuX18vfF98ICBcX19fLyANCiAgICAgICAgICAgICAgICAgfF9fXy8gICAgICB8X3wgICAgICAgICAgICAgIA0K";
$ssh->exec("base64 -d <<< {$newLoginHead} > /etc/motd.head");
$ssh->setTimeout(2);
//Change root password
$ssh->write("passwd\n");
$ssh->read('Enter New UNIX password:');
$ssh->write("{$newPassword}\n");
$ssh->read('Retype new UNIX password:');
$ssh->write("{$newPassword}\n");
$ssh->read('passwd: all authentication tokens updated successfully.');
$ssh->exec("hostname {$newHostname}\n");
$ssh->write("\n");
//IF you wanna play around...
//Adding new user
$ssh->write("adduser administrator\n"); sleep(1); //Dirty, I know
$ssh->read("Enter new UNIX password:");
$ssh->write("{$newPassword}\n");
$ssh->read('Retype new UNIX password:');
$ssh->write("{$newPassword}\n");
$ssh->read("Full Name []:");
$ssh->write("\n");
$ssh->read("Room Nmber[]:");
$ssh->write("\n");
$ssh->read("Work Phone []:");
$ssh->write("\n");
$ssh->read("Home Phone []:");
$ssh->write("\n");
$ssh->read("Other []:");
$ssh->write("\n");
$ssh->read("Is this information correct? [Y/n]");
$ssh->write("Y\n");
//Don't forget to remove old SSH key
$ssh->exec("rm /root/.ssh/authorized_keys");
return true;
}
catch(Exception $e)
{
$this->queryInfo = "Net_SSH2 Exception => " . $e->getMessage();
return false;
}
}
public static function getArchByCommercialType($cType)
{
$len = strlen($cType);
if($len < 2) //to make sure we don't return default arch for null strings
return "unknown";
//We have two possible architectures to return: arm | x86_64
$cType = strtolower($cType);
if (strpos($cType, 'arm') !== false || strpos($cType, 'c1') !== false) //if contains arm/c1 in name, it is ARM architecture
{
return "arm";
}
else
{
return "x86_64";
}
}
}
// ___ __ __ _ ____ _____ ____ __ __ _ _ _ _ ____ _____ __ __ _____ _ _ _____
//|_ _| \/ | / \ / ___| ____/ ___| | \/ | / \ | \ | | / \ / ___| ____| \/ | ____| \ | |_ _|
// | || |\/| | / _ \| | _| _| \___ \ | |\/| | / _ \ | \| | / _ \| | _| _| | |\/| | _| | \| | | |
// | || | | |/ ___ \ |_| | |___ ___) | | | | |/ ___ \| |\ |/ ___ \ |_| | |___| | | | |___| |\ | | |
//|___|_| |_/_/ \_\____|_____|____/ |_| |_/_/ \_\_| \_/_/ \_\____|_____|_| |_|_____|_| \_| |_|
//Same thing, wrapper for images!
class ScalewayImages
{
public $api = "";
protected $srvLoc = "par1";
public $images = array();
public $queryInfo = "";
function __construct($token, $location)
{
$this->srvLoc = $location;
$this->api = new ScalewayApi($token, $this->srvLoc);
$this->updateImages();
}
private function updateImages()
{
$this->images = array();
$imgs = $this->api->retrieve_images();
if($imgs["httpCode"] == 200)
{
$imagesArray = json_decode($imgs["json"], true);
for($i=0; $i < count($imagesArray['images']); $i++)
{
$imageInfo = $imagesArray['images'][$i];
$image = array
(
"id" => $imageInfo["id"],
"name" => $imageInfo["name"],
"arch" => $imageInfo["arch"],
"public" => $imageInfo["public"]
);
array_push($this->images, $image);
}
//!!!!!!
//Don't know why but Scaleway has multiple IDs for the same image. We preffer to keep only one as we can't display thousands distributions names to client.
//Later update: images have different kernels...
// ?????????????
//$this->images = $this->remove_duplicates($this->images);
return true;
}
else
{
$this->queryInfo = json_decode($imgs["json"], true)["message"];
return false;
}
}
public function remove_duplicates($images = array())
{
$buffer = $images;
$images = array();
foreach($buffer as $key => $value)
{
if( !$this->in_array_custom($value, $images) )
array_push($images, $value);
}
return $images;
}
private function in_array_custom($element, $arr = array() )
{
//It's custom because we have to compare two dmenssion arrays.
foreach($arr as $k => $v)
{
if($v["name"] == $element["name"])
return true;
}
return false;
}
public function getImagesByArch($arch, $public = true)
{
if($this->updateImages())
{
$buffer = $this->images;
$this->images = array();
foreach($buffer as $key => $value)
{
//$value will be an array which has ID, NAME, ARCH and PUBLIC of image
if($value["arch"] == $arch && $value["public"] == $public)
{
array_push($this->images, $value);
}
}
return true;
}
else
{
return false;
}
}
public function getImageByName($arch, $name, $public = true)
{
if($this->updateImages())
{
$buffer = $this->images;
$this->images = array();
foreach($buffer as $key => $value)
{
//$value will be an array which has ID, NAME, ARCH and PUBLIC of image
if($value["name"] == $name && $value["public"] == $public && $value["arch"] == $arch)
{
array_push($this->images, $value);
}
}
if( count($this->images) < 1)
{
$this->queryInfo = "Image was not found on Scaleway database!";
return false;
}
else
{
return true;
}
}
else
return false;
}
public function getImageById($id, $public = true)
{
if($this->updateImages())
{
$buffer = $this->images;
$this->images = array();
foreach($buffer as $key => $value)
{
//$value will be an array which has ID, NAME, ARCH and PUBLIC of image
if ($value["id"] == $id && $value["public"] == $public)
{
array_push($this->images, $value);
}
}
return true;
}
else
return false;
}
}
//__ ___ _ __ __ ____ ____ ____ _ _ _ _ _____
//\ \ / / | | | \/ |/ ___/ ___| | _ \| | | | | | | |__ /
// \ \ /\ / /| |_| | |\/| | | \___ \ | |_) | | | | | | | / /
// \ V V / | _ | | | | |___ ___) | | _ <| |_| | |___| |___ / /_
// \_/\_/ |_| |_|_| |_|\____|____/ |_| \_\\___/|_____|_____/____|
//All WHMCS required functions are bellow
// _ ____ __ __ ___ _ _ ___ ____ _____ ____ _ _____ ___ ____
// / \ | _ \| \/ |_ _| \ | |_ _/ ___|_ _| _ \ / \|_ _/ _ \| _ \
// / _ \ | | | | |\/| || || \| || |\___ \ | | | |_) | / _ \ | || | | | |_) |
// / ___ \| |_| | | | || || |\ || | ___) || | | _ < / ___ \| || |_| | _ <
///_/ \_\____/|_| |_|___|_| \_|___|____/ |_| |_| \_\/_/ \_\_| \___/|_| \_\
function Scaleway_MetaData()
{
return array
(
'DisplayName' => 'Scaleway',
'APIVersion' => '1.1', // Use API Version 1.1
'RequiresServer' => true, // Set true if module requires a server to work
'DefaultNonSSLPort' => '1111', // Default Non-SSL Connection Port
'DefaultSSLPort' => '1112', // Default SSL Connection Port
'ServiceSingleSignOnLabel' => 'Login to Panel as User',
'AdminSingleSignOnLabel' => 'Login to Panel as Admin',
);
}
function Scaleway_ConfigOptions()
{
$commercial_types = array();
foreach(ScalewayApi::$commercialTypes as $ctype => $cval)
{
array_push($commercial_types,($ctype . " - " . $cval));
}
return array
(
// a password field type allows for masked text input
'Token' => array
(
'Type' => 'password',
'Size' => '25',
'Default' => '',
'Description' => 'Scaleway secret token - used to access your account',
),
// the yesno field type displays a single checkbox option
'IPv6' => array
(
'Type' => 'yesno',
'Description' => 'Do you want to enable IPv6? Check if available for this server!',
),
// the dropdown field type renders a select menu of options
'Commercial type' => array
(
'Type' => 'dropdown',
'Options' => $commercial_types,
'Description' => 'Choose one',
),
// the textarea field type allows for multi-line text input
'Scaleway SSH Key (Putty format [.ppk])' => array