-
Notifications
You must be signed in to change notification settings - Fork 8
/
port.go
511 lines (443 loc) · 15.1 KB
/
port.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
package megaport
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"time"
)
// PortService is an interface for interfacing with the Port endpoints of the Megaport API.
type PortService interface {
// BuyPort buys a port from the Megaport Port API.
BuyPort(ctx context.Context, req *BuyPortRequest) (*BuyPortResponse, error)
// ValidatePortOrder validates a port order in the Megaport Products API.
ValidatePortOrder(ctx context.Context, req *BuyPortRequest) error
// ListPorts lists all ports in the Megaport Port API.
ListPorts(ctx context.Context) ([]*Port, error)
// GetPort gets a single port in the Megaport Port API.
GetPort(ctx context.Context, portId string) (*Port, error)
// ModifyPort modifies a port in the Megaport Port API.
ModifyPort(ctx context.Context, req *ModifyPortRequest) (*ModifyPortResponse, error)
// DeletePort deletes a port in the Megaport Port API.
DeletePort(ctx context.Context, req *DeletePortRequest) (*DeletePortResponse, error)
// RestorePort restores a port in the Megaport Port API.
RestorePort(ctx context.Context, portId string) (*RestorePortResponse, error)
// LockPort locks a port in the Megaport Port API.
LockPort(ctx context.Context, portId string) (*LockPortResponse, error)
// UnlockPort unlocks a port in the Megaport Port API.
UnlockPort(ctx context.Context, portId string) (*UnlockPortResponse, error)
// CheckPortVLANAvailability checks if a VLAN is available on a port in the Megaport Products API.
CheckPortVLANAvailability(ctx context.Context, portId string, vlan int) (bool, error)
// ListPortResourceTags lists the resource tags for a port in the Megaport Port API.
ListPortResourceTags(ctx context.Context, portID string) (map[string]string, error)
// UpdatePortResourceTags updates the resource tags for a port in the Megaport Port API.
UpdatePortResourceTags(ctx context.Context, portID string, tags map[string]string) error
}
// NewPortService creates a new instance of the Port Service.
func NewPortService(c *Client) *PortServiceOp {
return &PortServiceOp{
Client: c,
}
}
// PortServiceOp handles communication with Port methods of the Megaport API.
type PortServiceOp struct {
Client *Client
}
// BuyPortRequest represents a request to buy a port.
type BuyPortRequest struct {
Name string `json:"name"`
Term int `json:"term"`
PortSpeed int `json:"portSpeed"`
LocationId int `json:"locationId"`
Market string `json:"market"`
LagCount int `json:"lagCount"` // A lag count of 1 or higher will order the port as a single LAG
MarketPlaceVisibility bool `json:"marketPlaceVisibility"`
DiversityZone string `json:"diversityZone"`
CostCentre string `json:"costCentre"`
PromoCode string `json:"promoCode"`
ResourceTags map[string]string `json:"resourceTags"`
WaitForProvision bool // Wait until the VXC provisions before returning
WaitForTime time.Duration // How long to wait for the VXC to provision if WaitForProvision is true (default is 5 minutes)
}
// BuyPortResponse represents a response from buying a port.
type BuyPortResponse struct {
TechnicalServiceUIDs []string
}
// GetPortRequest represents a request to get a port.
type GetPortRequest struct {
PortID string
}
// ModifyPortRequest represents a request to modify a port.
type ModifyPortRequest struct {
PortID string
Name string
MarketplaceVisibility *bool
CostCentre string
ContractTermMonths *int
WaitForUpdate bool // Wait until the Port updates before returning
WaitForTime time.Duration // How long to wait for the Port to update if WaitForUpdate is true (default is 5 minutes)
}
// ModifyPortResponse represents a response from modifying a port.
type ModifyPortResponse struct {
IsUpdated bool
}
// DeletePortRequest represents a request to delete a port.
type DeletePortRequest struct {
PortID string
DeleteNow bool
}
// DeletePortResponse represents a response from deleting a port.
type DeletePortResponse struct {
IsDeleting bool
}
// RestorePortRequest represents a request to restore a port.
type RestorePortRequest struct {
PortID string
}
// RestorePortResponse represents a response from restoring a port.
type RestorePortResponse struct {
IsRestored bool
}
// LockPortRequest represents a request to lock a port.
type LockPortRequest struct {
PortID string
}
// LockPortResponse represents a response from locking a port.
type LockPortResponse struct {
IsLocking bool
}
// UnlockPortRequest represents a request to unlock a port.
type UnlockPortRequest struct {
PortID string
}
// UnlockPortResponse represents a response from unlocking a port.
type UnlockPortResponse struct {
IsUnlocking bool
}
// BuyPort buys a port from the Megaport Port API.
func (svc *PortServiceOp) BuyPort(ctx context.Context, req *BuyPortRequest) (*BuyPortResponse, error) {
if req.Term != 1 && req.Term != 12 && req.Term != 24 && req.Term != 36 {
return nil, ErrInvalidTerm
}
buyOrder := createPortOrder(req)
responseBody, responseError := svc.Client.ProductService.ExecuteOrder(ctx, buyOrder)
if responseError != nil {
return nil, responseError
}
orderInfo := PortOrderResponse{}
unmarshalErr := json.Unmarshal(*responseBody, &orderInfo)
if unmarshalErr != nil {
return nil, unmarshalErr
}
toReturn := &BuyPortResponse{
TechnicalServiceUIDs: []string{},
}
for _, d := range orderInfo.Data {
toReturn.TechnicalServiceUIDs = append(toReturn.TechnicalServiceUIDs, d.TechnicalServiceUID)
}
// wait until the Port is provisioned before returning if requested by the user
if req.WaitForProvision {
toWait := req.WaitForTime
if toWait == 0 {
toWait = 5 * time.Minute
}
ticker := time.NewTicker(30 * time.Second) // check on the provision status every 30 seconds
timer := time.NewTimer(toWait)
defer ticker.Stop()
defer timer.Stop()
for {
select {
case <-timer.C:
return nil, fmt.Errorf("time expired waiting for Port %s to provision", toReturn.TechnicalServiceUIDs)
case <-ctx.Done():
return nil, fmt.Errorf("context expired waiting for Port %s to provision", toReturn.TechnicalServiceUIDs)
case <-ticker.C:
ports := []*Port{}
for _, uid := range toReturn.TechnicalServiceUIDs {
portDetails, err := svc.GetPort(ctx, uid)
if err != nil {
return nil, err
}
ports = append(ports, portDetails)
}
// if all ports are ready return
numReady := 0
for _, port := range ports {
if slices.Contains(SERVICE_STATE_READY, port.ProvisioningStatus) {
numReady++
}
}
if numReady == len(ports) {
return toReturn, nil
}
}
}
} else {
// return the service UID right away if the user doesn't want to wait for provision
return toReturn, nil
}
}
func createPortOrder(req *BuyPortRequest) []PortOrder {
return []PortOrder{{
Name: req.Name,
Term: req.Term,
ProductType: "MEGAPORT",
PortSpeed: req.PortSpeed,
LocationID: req.LocationId,
Config: PortOrderConfig{
DiversityZone: req.DiversityZone,
},
Virtual: false,
Market: req.Market,
LagPortCount: req.LagCount,
MarketplaceVisibility: req.MarketPlaceVisibility,
CostCentre: req.CostCentre,
PromoCode: req.PromoCode,
ResourceTags: toProductResourceTags(req.ResourceTags),
}}
}
func (svc *PortServiceOp) ValidatePortOrder(ctx context.Context, req *BuyPortRequest) error {
if req.Term != 1 && req.Term != 12 && req.Term != 24 && req.Term != 36 {
return ErrInvalidTerm
}
buyOrder := createPortOrder(req)
return svc.Client.ProductService.ValidateProductOrder(ctx, buyOrder)
}
// ListPorts lists all ports in the Megaport Port API.
func (svc *PortServiceOp) ListPorts(ctx context.Context) ([]*Port, error) {
path := "/v2/products"
url := svc.Client.BaseURL.JoinPath(path).String()
req, err := svc.Client.NewRequest(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
response, err := svc.Client.Do(ctx, req, nil)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, fileErr := io.ReadAll(response.Body)
if fileErr != nil {
return nil, fileErr
}
parsed := ParsedProductsResponse{}
unmarshalErr := json.Unmarshal(body, &parsed)
if unmarshalErr != nil {
return nil, unmarshalErr
}
ports := []*Port{}
for _, unmarshaledData := range parsed.Data {
// The products query response will likely contain non-port objects. As a result
// we need to initially Unmarshal as ParsedProductsResponse so that we may iterate
// over the entries in Data then re-Marshal those entries so that we may Unmarshal
// them as Port (and `continue` where that doesn't work). We could write a custom
// deserializer to avoid this but that is a lot of work for a performance
// optimization which is likely irrelevant in practice.
// Unfortunately I know of no better (maintainable) method of making this work.
remarshaled, err := json.Marshal(unmarshaledData)
if err != nil {
svc.Client.Logger.WarnContext(ctx, fmt.Sprintf("Could not remarshal %v as port.", err.Error()))
continue
}
port := Port{}
unmarshalErr = json.Unmarshal(remarshaled, &port)
if unmarshalErr != nil {
svc.Client.Logger.WarnContext(ctx, fmt.Sprintf("Could not unmarshal %v as port.", unmarshalErr.Error()))
continue
}
ports = append(ports, &port)
}
return ports, nil
}
// GetPort gets a single port in the Megaport Port API.
func (svc *PortServiceOp) GetPort(ctx context.Context, portId string) (*Port, error) {
path := "/v2/product/" + portId
url := svc.Client.BaseURL.JoinPath(path).String()
clientReq, err := svc.Client.NewRequest(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
response, err := svc.Client.Do(ctx, clientReq, nil)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, fileErr := io.ReadAll(response.Body)
if fileErr != nil {
return nil, fileErr
}
portDetails := PortResponse{}
unmarshalErr := json.Unmarshal(body, &portDetails)
if unmarshalErr != nil {
return nil, unmarshalErr
}
return &portDetails.Data, nil
}
// ModifyPort modifies a port in the Megaport Port API.
func (svc *PortServiceOp) ModifyPort(ctx context.Context, req *ModifyPortRequest) (*ModifyPortResponse, error) {
if len(req.CostCentre) > 255 {
return nil, ErrCostCentreTooLong
}
modifyReq := &ModifyProductRequest{
ProductID: req.PortID,
ProductType: PRODUCT_MEGAPORT,
Name: req.Name,
CostCentre: req.CostCentre,
MarketplaceVisibility: req.MarketplaceVisibility,
}
if req.ContractTermMonths != nil {
modifyReq.ContractTermMonths = *req.ContractTermMonths
}
modifyRes, err := svc.Client.ProductService.ModifyProduct(ctx, modifyReq)
if err != nil {
return nil, err
}
toReturn := &ModifyPortResponse{
IsUpdated: modifyRes.IsUpdated,
}
// wait until the Port is updated before returning if requested by the user
if req.WaitForUpdate {
toWait := req.WaitForTime
if toWait == 0 {
toWait = 5 * time.Minute
}
ticker := time.NewTicker(30 * time.Second) // check on the update status every 30 seconds
timer := time.NewTimer(toWait)
defer ticker.Stop()
defer timer.Stop()
for {
select {
case <-timer.C:
return nil, fmt.Errorf("time expired waiting for Port %s to update", req.PortID)
case <-ctx.Done():
return nil, fmt.Errorf("context expired waiting for Port %s to update", req.PortID)
case <-ticker.C:
portDetails, err := svc.GetPort(ctx, req.PortID)
if err != nil {
return nil, err
}
if slices.Contains(SERVICE_STATE_READY, portDetails.ProvisioningStatus) {
return toReturn, nil
}
}
}
} else {
// return the response right away if the user doesn't want to wait for update
return toReturn, nil
}
}
// DeletePort deletes a port in the Megaport Port API.
func (svc *PortServiceOp) DeletePort(ctx context.Context, req *DeletePortRequest) (*DeletePortResponse, error) {
_, err := svc.Client.ProductService.DeleteProduct(ctx, &DeleteProductRequest{
ProductID: req.PortID,
DeleteNow: req.DeleteNow,
})
if err != nil {
return nil, err
}
return &DeletePortResponse{
IsDeleting: true,
}, nil
}
// RestorePort restores a port in the Megaport Port API.
func (svc *PortServiceOp) RestorePort(ctx context.Context, portId string) (*RestorePortResponse, error) {
_, err := svc.Client.ProductService.RestoreProduct(ctx, portId)
if err != nil {
return nil, err
}
return &RestorePortResponse{
IsRestored: true,
}, nil
}
// LockPort locks a port in the Megaport Port API.
func (svc *PortServiceOp) LockPort(ctx context.Context, portId string) (*LockPortResponse, error) {
port, err := svc.GetPort(ctx, portId)
if err != nil {
return nil, err
}
if !port.Locked {
_, err = svc.Client.ProductService.ManageProductLock(ctx, &ManageProductLockRequest{
ProductID: portId,
ShouldLock: true,
})
if err != nil {
return nil, err
}
return &LockPortResponse{IsLocking: true}, nil
} else {
return nil, ErrPortAlreadyLocked
}
}
// UnlockPort unlocks a port in the Megaport Port API.
func (svc *PortServiceOp) UnlockPort(ctx context.Context, portId string) (*UnlockPortResponse, error) {
port, err := svc.GetPort(ctx, portId)
if err != nil {
return nil, err
}
if port.Locked {
_, err = svc.Client.ProductService.ManageProductLock(ctx, &ManageProductLockRequest{
ProductID: portId,
ShouldLock: false,
})
if err != nil {
return nil, err
}
return &UnlockPortResponse{IsUnlocking: true}, nil
} else {
return nil, ErrPortNotLocked
}
}
func (svc *PortServiceOp) CheckPortVLANAvailability(ctx context.Context, portId string, vlan int) (bool, error) {
if vlan < 0 || vlan > 4094 {
return false, ErrInvalidVLAN
}
_, err := svc.GetPort(ctx, portId)
if err != nil {
return false, err
}
path := "/v2/product/port/" + portId + "/vlan"
params := url.Values{}
params.Add("vlan", fmt.Sprintf("%d", vlan))
url := svc.Client.BaseURL.JoinPath(path)
url.RawQuery = params.Encode()
urlStr := url.String()
clientReq, err := svc.Client.NewRequest(ctx, http.MethodGet, urlStr, nil)
if err != nil {
return false, err
}
response, err := svc.Client.Do(ctx, clientReq, nil)
if err != nil {
return false, err
}
defer response.Body.Close()
body, fileErr := io.ReadAll(response.Body)
if fileErr != nil {
return false, err
}
vlanResponse := PortVLANAvailabilityAPIResponse{}
unmarshalErr := json.Unmarshal(body, &vlanResponse)
if unmarshalErr != nil {
return false, unmarshalErr
}
if slices.Contains(vlanResponse.Data, vlan) {
return true, nil
}
return false, nil
}
// ListPortResourceTags lists the resource tags for a port in the Megaport Port API.
func (svc *PortServiceOp) ListPortResourceTags(ctx context.Context, portID string) (map[string]string, error) {
tags, err := svc.Client.ProductService.ListProductResourceTags(ctx, portID)
if err != nil {
return nil, err
}
return fromProductResourceTags(tags), nil
}
func (svc *PortServiceOp) UpdatePortResourceTags(ctx context.Context, portID string, tags map[string]string) error {
productTags := toProductResourceTags(tags)
return svc.Client.ProductService.UpdateProductResourceTags(ctx, portID, &UpdateProductResourceTagsRequest{
ResourceTags: productTags,
})
}