-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud_servers.go
594 lines (505 loc) · 14.2 KB
/
cloud_servers.go
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
package goarubacloud
import (
"fmt"
"log"
"strings"
"time"
)
const cloudSeverListPath = "GetServers"
const cloudSeverDetailsPath = "GetServerDetails"
const cloudSeverCreatePath = "SetEnqueueServerCreation"
const cloudSeverDeletePath = "SetEnqueueServerDeletion"
// CloudServersService is an interface for interfacing with the Cloud Server
// endpoints of the Arubacloud API
type CloudServersService interface {
List() ([]CloudServer, *Response, error)
Get(int) (*CloudServerDetails, *Response, error)
Create(CloudServerCreator) (*CloudServer, *Response, error)
Delete(int) (*Response, error)
}
// CloudServersServiceOp handles communication with the Cloud Server related methods of the
// Arubacloud API.
type CloudServersServiceOp struct {
client *Client
}
var _ CloudServersService = &CloudServersServiceOp{}
// CloudServer represents a Arubacloud Cloud Server
type CloudServer struct {
Busy bool
CPUQuantity int
CompanyId int
DatacenterId DataCenterRegion
HDQuantity int
HDTotalSize int
HypervisorServerType int
HypervisorType HypervisorType
Name string
OSTemplateId int
RAMQuantity int
ServerId int
ServerStatus ServerStatus
UserId int
}
type CloudServerDetails struct {
ActiveJobs []ActiveJob
CPUQuantity CPUQuantity
CompanyId int
ControlToolActivationDate string
ControlToolInstalled bool
CreationDate string
DatacenterId DataCenterRegion
EasyCloudIPAddress EasyCloudIPAddress
EasyCloudPackageID int
HypervisorServerType int
HypervisorType HypervisorType
Name string
NetworkAdapters []NetworkAdapter
Note string
OSTemplate OSTemplateDetails
Parameters []interface{}
RAMQuantity RAMQuantity
RenewDateSmart string
ScheduledOperations []ScheduledTask
ServerId int
ServerStatus ServerStatus
Snapshots []interface{}
ToolsAvailable bool
UserId int
VirtualDVDs []interface{}
VirtualDisks []VirtualDisk
VncPort int
}
type ActiveJob struct {
JobId int
Status int
OperationName string
Progress int
ServerId int
ServerName string
CreationDate string
LastUpdateDate string
LicenseId interface{}
ResourceId int
ResourceValue interface{}
UserId int
Username string
}
type EasyCloudIPAddress struct {
Value string
SubNetMask string
Gateway string
GatewayIPv6 string
PrefixIPv6 int
SubnetPrefixIPv6 string
StartRangeIPv6 string
EndRangeIPv6 string
ServerId int
CompanyId int
ProductId int
ResourceId int
ResourceType int
UserId int
LoadBalancerID interface{}
}
type CPUQuantity struct {
CompanyId int
ProductId int
ResourceId1 int
ResourceType int
UserId int
Quantity int
}
type RAMQuantity struct {
CompanyId int
ProductId int
ResourceId int
ResourceType int
UserId int
Quantity int
}
type VirtualDisk struct {
CompanyId int
ProductId int
ResourceId int
ResourceType int
UserId int
CreationDate string
Size int
}
type ServerStatus int
const (
CREATION_IN_PROGRESS ServerStatus = 1 + iota
OFF
ON
)
var server_status = [...]string{
"CREATION IN PROGRESS",
"OFF",
"ON",
}
// String returns the name of the Datacenter.
func (m ServerStatus) String() string {
return server_status[m-1]
}
type CloudServerSmartSize int
const (
SMALL CloudServerSmartSize = 1 + iota
MEDIUM
LARGE
EXTRALARGE
)
func GetServerSmartSize(size string) (CloudServerSmartSize, error) {
switch strings.ToUpper(size) {
case "SMALL":
return SMALL, nil
case "MEDIUM":
return MEDIUM, nil
case "LARGE":
return LARGE, nil
case "EXTRALARGE":
return EXTRALARGE, nil
default:
return 0, fmt.Errorf("size '%s' is wrong. Supported values are: 'SMALL', 'MEDIUM','LARGE','EXTRALARGE'", size)
}
}
type NetworkAdapter struct {
Id int
NetworkAdapterType int
IPAddresses []IpAddress
PublicIpAddresses []PublicIpAddress
MacAddress string
ServerId int
VLan PurchasedVLAN
}
type IpAddress struct {
Value string
Gateway string
SubNetMask string
GatewayIPv6 string
PrefixIPv6 int
SubnetPrefixIPv6 string
StartRangeIPv6 string
EndRangeIPv6 string
ServerId int
CompanyId int
ProductId int
ResourceId int
ResourceType int
UserId int
LoadBalancerID interface{}
}
type PublicIpAddress struct {
PrimaryIPAddress string
PublicIpAddressResourceId int
}
type CloudServerCreator interface {
GetServerName() string
GetRequest() interface{}
SetNote(string) error
}
type CloudServerProCreator interface {
AddVirtualDisk(int) error
AddPublicIp(int) error
SetCPUQuantity(int) error
SetRAMQuantity(int) error
SetNote(string) error
GetServerName() string
GetRequest() interface{}
}
func NewCloudServerProCreateRequest(name string, admin_password string, os_template_id int) CloudServerProCreator {
createRequest := &cloudServerCreateRequestPro{
Name: name,
OSTemplateId: os_template_id,
AdministratorPassword: admin_password,
CPUQuantity: 1,
RAMQuantity: 1,
Note: "",
VirtualDisks: []CloudServerCreateVirtualDisk{},
NetworkAdaptersConfiguration: []NetworkAdapterCreateConfiguration{},
}
return createRequest
}
func NewCloudServerSmartCreateRequest(smart_server_size CloudServerSmartSize, name string, admin_password string, os_template_id int) CloudServerCreator {
return &cloudServerCreateRequestSmart{
Name: name,
OSTemplateId: os_template_id,
Note: "",
AdministratorPassword: admin_password,
CloudServerSmartType: smart_server_size,
}
}
// cloudServerCreateRequestPro represents a request to create a CloudServer PRO.
type cloudServerCreateRequestPro struct {
Name string
AdministratorPassword string
OSTemplateId int
Note string
CPUQuantity int
RAMQuantity int
VirtualDisks []CloudServerCreateVirtualDisk
NetworkAdaptersConfiguration []NetworkAdapterCreateConfiguration
}
func (r *cloudServerCreateRequestPro) AddVirtualDisk(size int) error {
if len(r.VirtualDisks) == 4 {
return NewArgError("operation", "max disk count is 4")
}
if size < 10 || size > 500 {
return NewArgError("size", "MaxSize per Disk: 500 GB. MinSize per Disk 10 GB")
}
if size%10 != 0 {
return NewArgError("size", "disk size must be a multiple of 10")
}
r.VirtualDisks = append(r.VirtualDisks, CloudServerCreateVirtualDisk{
VirtualDiskType: len(r.VirtualDisks),
Size: size,
})
return nil
}
func (r *cloudServerCreateRequestPro) AddPublicIp(resourceId int) error {
if resourceId == 0 {
return NewArgError("resourceId", "it must be > 0")
}
publicIpAddress := PublicIpAddress{PrimaryIPAddress: "true", PublicIpAddressResourceId: resourceId}
r.NetworkAdaptersConfiguration = append(r.NetworkAdaptersConfiguration, NetworkAdapterCreateConfiguration{
NetworkAdapterType: len(r.NetworkAdaptersConfiguration),
PublicIpAddresses: []PublicIpAddress{publicIpAddress},
})
return nil
}
func (r *cloudServerCreateRequestPro) SetCPUQuantity(cpu_quantity int) error {
if cpu_quantity < 1 {
return NewArgError("cpu_quantity", "it must be > 1")
}
r.CPUQuantity = cpu_quantity
return nil
}
func (r *cloudServerCreateRequestPro) SetRAMQuantity(ram_quantity int) error {
if ram_quantity < 1 {
return NewArgError("ram_quantity", "it must be > 1")
}
r.RAMQuantity = ram_quantity
return nil
}
func (r *cloudServerCreateRequestPro) SetNote(note string) error {
if len(note) > 4096 {
return NewArgError("note", "it is too long")
}
r.Note = note
return nil
}
func (r *cloudServerCreateRequestPro) GetServerName() string {
return r.Name
}
func (r *cloudServerCreateRequestPro) GetRequest() interface{} {
if len(r.VirtualDisks) == 0 {
r.VirtualDisks = append(r.VirtualDisks, CloudServerCreateVirtualDisk{
VirtualDiskType: 0,
Size: 10,
})
}
return r
}
// cloudServerCreateRequestSmart represents a request to create a CloudServer SMART.
type cloudServerCreateRequestSmart struct {
Name string `json:"Name"`
AdministratorPassword string `json:"AdministratorPassword"`
OSTemplateId int `json:"OSTemplateId"`
CloudServerSmartType CloudServerSmartSize `json:"SmartVMWarePackageID"`
Note string `json:"Note"`
}
func (r *cloudServerCreateRequestSmart) GetServerName() string {
return r.Name
}
func (r *cloudServerCreateRequestSmart) GetRequest() interface{} {
return r
}
func (r *cloudServerCreateRequestSmart) SetNote(note string) error {
if len(note) > 4096 {
return NewArgError("note", "it is too long")
}
r.Note = note
return nil
}
type hypervisorsRoot struct {
Hypervisors []Hypervisor `json:"Value"`
}
type cloudServerDetailsRoot struct {
CloudServerDetails *CloudServerDetails `json:"Value"`
}
type cloudServersRoot struct {
CloudServers []CloudServer `json:"Value"`
}
// CloudServerCreateVirtualDisk identifies a VirtualDisk to attach for the create request.
type CloudServerCreateVirtualDisk struct {
VirtualDiskType int
Size int
}
type NetworkAdapterCreateConfiguration struct {
NetworkAdapterType int
PublicIpAddresses []PublicIpAddress
}
func (s *CloudServerDetails) GetPublicIpAddress() (string, error) {
if s.EasyCloudPackageID != 0 {
return s.EasyCloudIPAddress.Value, nil
} else {
for _, network_adapter := range s.NetworkAdapters {
for _, public_ip := range network_adapter.IPAddresses {
return public_ip.Value, nil
}
}
return "", fmt.Errorf("Server %d doesn't have any public IPs assigned to it", s.ServerId)
}
}
// List all CloudServers
func (s *CloudServersServiceOp) List() ([]CloudServer, *Response, error) {
req, err := s.client.NewRequest(cloudSeverListPath, nil)
if err != nil {
return nil, nil, err
}
root := new(cloudServersRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.CloudServers, resp, err
}
// Get individual CloudServer
func (s *CloudServersServiceOp) Get(serverId int) (*CloudServerDetails, *Response, error) {
req, err := s.client.NewRequest(cloudSeverDetailsPath, ServerIdCreate{ServerId: serverId})
if err != nil {
return nil, nil, err
}
root := new(cloudServerDetailsRoot)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
return root.CloudServerDetails, resp, err
}
// Create cloudServer
func (s *CloudServersServiceOp) Create(requestCreator CloudServerCreator) (*CloudServer, *Response, error) {
if requestCreator == nil {
return nil, nil, NewArgError("requestCreator", "cannot be nil")
}
if requestCreator.GetRequest() == nil {
return nil, nil, NewArgError("request", "cannot be nil")
}
data := struct {
Server interface{} `json:"Server"`
}{requestCreator.GetRequest()}
req, err := s.client.NewRequest(cloudSeverCreatePath, data)
if err != nil {
return nil, nil, err
}
root := new(CloudServer)
resp, err := s.client.Do(req, root)
if err != nil {
return nil, resp, err
}
server, err := WaitForServerWithName(s.client, requestCreator.GetServerName())
if err != nil {
return nil, nil, err
}
return server, resp, err
}
// Delete CloudServer
func (s *CloudServersServiceOp) Delete(serverId int) (*Response, error) {
serverDetails, resp, err := s.client.CloudServers.Get(serverId)
if err != nil {
return resp, err
}
if serverDetails.ServerStatus == ON {
resp, err := s.client.CloudServerActions.PowerOff(serverId)
if err != nil {
return resp, err
}
}
err = WaitForServerStatus(s.client, serverId, OFF)
if err != nil {
return nil, err
}
req, err := s.client.NewRequest(cloudSeverDeletePath, ServerIdCreate{ServerId: serverId})
if err != nil {
return nil, err
}
resp, err = s.client.Do(req, nil)
if err != nil {
return resp, err
}
return resp, err
}
const (
// maxRetries is the amount of times we can fail before deciding
// the check is a total failure.
maxRetries = 10
)
// WaitForServerStatus waits for a cloud servers status
func WaitForServerStatus(client *Client, serverId int, status ServerStatus) error {
completed := false
failCount := 0
for !completed {
server_details, _, err := client.CloudServers.Get(serverId)
if err != nil {
if failCount <= maxRetries {
failCount++
continue
}
return err
}
if server_details.ServerStatus != status {
time.Sleep(10 * time.Second)
} else {
completed = true
}
}
return nil
}
// WaitForServerWithName waits for a server with specified name appears in the list
func WaitForServerWithName(client *Client, serverName string) (*CloudServer, error) {
completed := false
failCount := 0
var server *CloudServer
for !completed {
servers, _, err := client.CloudServers.List()
if err != nil {
if failCount <= maxRetries {
failCount++
continue
}
return nil, err
}
for _, serverItem := range servers {
if serverItem.Name == serverName {
completed = true
server = &serverItem
}
}
time.Sleep(5 * time.Second)
}
return server, nil
}
func WaitForServerCreationDone(client *Client, serverId int) error {
completed := false
for !completed {
all_jobs, _, err := client.DataCenters.GetJobs()
if err != nil {
return err
}
server_jobs := make([]ActiveJob, len(all_jobs))
for _, job := range all_jobs {
if job.ServerId == serverId {
server_jobs = append(server_jobs, job)
}
}
if len(server_jobs) == 0 {
log.Printf("[INFO] No active jobs for server %d", serverId)
completed = true
}
for _, job := range server_jobs {
log.Printf("[INFO] Server ID: %d. Operation: %s. Progress: %d%%\n",
job.ServerId, job.OperationName, job.Progress)
}
time.Sleep(15 * time.Second)
}
return nil
}