-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathgenerate_payload.go
More file actions
260 lines (228 loc) · 8.09 KB
/
Copy pathgenerate_payload.go
File metadata and controls
260 lines (228 loc) · 8.09 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
package generatepayload
import (
"context"
"encoding/json"
"fmt"
"github.com/stackitcloud/stackit-cli/internal/pkg/types"
loadbalancer "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
"github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
"github.com/stackitcloud/stackit-cli/internal/pkg/fileutils"
"github.com/stackitcloud/stackit-cli/internal/pkg/flags"
"github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
"github.com/stackitcloud/stackit-cli/internal/pkg/services/load-balancer/client"
"github.com/stackitcloud/stackit-cli/internal/pkg/utils"
"github.com/spf13/cobra"
)
const (
loadBalancerNameFlag = "lb-name"
filePathFlag = "file-path"
)
type inputModel struct {
*globalflags.GlobalFlagModel
LoadBalancerName *string
FilePath *string
}
var (
defaultPayloadListener = &loadbalancer.Listener{
DisplayName: utils.Ptr(""),
Port: utils.Ptr(int32(0)),
Protocol: loadbalancer.ListenerProtocol("").Ptr(),
ServerNameIndicators: []loadbalancer.ServerNameIndicator{
{
Name: utils.Ptr(""),
},
},
TargetPool: utils.Ptr(""),
Tcp: &loadbalancer.OptionsTCP{
IdleTimeout: utils.Ptr(""),
},
Udp: &loadbalancer.OptionsUDP{
IdleTimeout: utils.Ptr(""),
},
}
defaultPayloadNetwork = &loadbalancer.Network{
NetworkId: utils.Ptr(""),
Role: loadbalancer.NetworkRole("").Ptr(),
}
defaultPayloadTargetPool = &loadbalancer.TargetPool{
ActiveHealthCheck: &loadbalancer.ActiveHealthCheck{
HealthyThreshold: utils.Ptr(int32(0)),
Interval: utils.Ptr(""),
IntervalJitter: utils.Ptr(""),
Timeout: utils.Ptr(""),
UnhealthyThreshold: utils.Ptr(int32(0)),
},
Name: utils.Ptr(""),
SessionPersistence: &loadbalancer.SessionPersistence{
UseSourceIpAddress: utils.Ptr(false),
},
TargetPort: utils.Ptr(int32(0)),
Targets: []loadbalancer.Target{
{
DisplayName: utils.Ptr(""),
Ip: utils.Ptr(""),
},
},
}
DefaultCreateLoadBalancerPayload = loadbalancer.CreateLoadBalancerPayload{
ExternalAddress: utils.Ptr(""),
Listeners: []loadbalancer.Listener{
*defaultPayloadListener,
},
Name: utils.Ptr(""),
Networks: []loadbalancer.Network{
*defaultPayloadNetwork,
},
Options: &loadbalancer.LoadBalancerOptions{
AccessControl: &loadbalancer.LoadbalancerOptionAccessControl{
AllowedSourceRanges: []string{
"",
},
},
EphemeralAddress: utils.Ptr(false),
Observability: &loadbalancer.LoadbalancerOptionObservability{
Logs: &loadbalancer.LoadbalancerOptionLogs{
CredentialsRef: utils.Ptr(""),
PushUrl: utils.Ptr(""),
},
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: utils.Ptr(""),
PushUrl: utils.Ptr(""),
},
},
PrivateNetworkOnly: utils.Ptr(false),
},
TargetPools: []loadbalancer.TargetPool{
*defaultPayloadTargetPool,
},
}
)
func NewCmd(params *types.CmdParams) *cobra.Command {
cmd := &cobra.Command{
Use: "generate-payload",
Short: "Generates a payload to create/update a Load Balancer",
Long: fmt.Sprintf("%s\n%s",
"Generates a JSON payload with values to be used as --payload input for load balancer creation or update.",
"See https://docs.api.stackit.cloud/documentation/load-balancer/version/v1#tag/Load-Balancer/operation/APIService_CreateLoadBalancer for information regarding the payload structure.",
),
Args: args.NoArgs,
Example: examples.Build(
examples.NewExample(
`Generate a payload, and adapt it with custom values for the different configuration options`,
`$ stackit load-balancer generate-payload --file-path ./payload.json`,
`<Modify payload in file, if needed>`,
`$ stackit load-balancer create --payload @./payload.json`),
examples.NewExample(
`Generate a payload with values of an existing load balancer, and adapt it with custom values for the different configuration options`,
`$ stackit load-balancer generate-payload --lb-name xxx --file-path ./payload.json`,
`<Modify payload in file>`,
`$ stackit load-balancer update xxx --payload @./payload.json`),
examples.NewExample(
`Generate a payload with values of an existing load balancer, and preview it in the terminal`,
`$ stackit load-balancer generate-payload --lb-name xxx`),
),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
model, err := parseInput(params.Printer, cmd, args)
if err != nil {
return err
}
// Configure API client
apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion)
if err != nil {
return err
}
if model.LoadBalancerName == nil {
createPayload := DefaultCreateLoadBalancerPayload
return outputCreateResult(params.Printer, model.FilePath, &createPayload)
}
req := buildRequest(ctx, model, apiClient)
resp, err := req.Execute()
if err != nil {
return fmt.Errorf("read load balancer: %w", err)
}
listeners := modifyListener(resp)
updatePayload := &loadbalancer.UpdateLoadBalancerPayload{
ExternalAddress: resp.ExternalAddress,
Listeners: listeners,
Name: resp.Name,
Networks: resp.Networks,
Options: resp.Options,
TargetPools: resp.TargetPools,
Version: resp.Version,
}
return outputUpdateResult(params.Printer, model.FilePath, updatePayload)
},
}
configureFlags(cmd)
return cmd
}
func configureFlags(cmd *cobra.Command) {
cmd.Flags().StringP(loadBalancerNameFlag, "n", "", "If set, generates the payload with the current values of the given load balancer. If unset, generates the payload with empty values")
cmd.Flags().StringP(filePathFlag, "f", "", "If set, writes the payload to the given file. If unset, writes the payload to the standard output")
}
func parseInput(p *print.Printer, cmd *cobra.Command, _ []string) (*inputModel, error) {
globalFlags := globalflags.Parse(p, cmd)
loadBalancerName := flags.FlagToStringPointer(p, cmd, loadBalancerNameFlag)
// If load balancer name is provided, projectId is needed as well
if loadBalancerName != nil && globalFlags.ProjectId == "" {
return nil, &errors.ProjectIdError{}
}
model := inputModel{
GlobalFlagModel: globalFlags,
LoadBalancerName: loadBalancerName,
FilePath: flags.FlagToStringPointer(p, cmd, filePathFlag),
}
p.DebugInputModel(model)
return &model, nil
}
func buildRequest(ctx context.Context, model *inputModel, apiClient *loadbalancer.APIClient) loadbalancer.ApiGetLoadBalancerRequest {
req := apiClient.DefaultAPI.GetLoadBalancer(ctx, model.ProjectId, model.Region, *model.LoadBalancerName)
return req
}
func outputCreateResult(p *print.Printer, filePath *string, payload *loadbalancer.CreateLoadBalancerPayload) error {
if payload == nil {
return fmt.Errorf("loadbalancer payload is empty")
}
payloadBytes, err := json.MarshalIndent(*payload, "", " ")
if err != nil {
return fmt.Errorf("marshal create load balancer payload: %w", err)
}
if filePath != nil {
err = fileutils.WriteToFile(utils.PtrString(filePath), string(payloadBytes))
if err != nil {
return fmt.Errorf("write create load balancer payload to the file: %w", err)
}
} else {
p.Outputln(string(payloadBytes))
}
return nil
}
func outputUpdateResult(p *print.Printer, filePath *string, payload *loadbalancer.UpdateLoadBalancerPayload) error {
if payload == nil {
return fmt.Errorf("loadbalancer payload is empty")
}
payloadBytes, err := json.MarshalIndent(*payload, "", " ")
if err != nil {
return fmt.Errorf("marshal update load balancer payload: %w", err)
}
if filePath != nil {
err = fileutils.WriteToFile(utils.PtrString(filePath), string(payloadBytes))
if err != nil {
return fmt.Errorf("write update load balancer payload to the file: %w", err)
}
} else {
p.Outputln(string(payloadBytes))
}
return nil
}
func modifyListener(resp *loadbalancer.LoadBalancer) []loadbalancer.Listener {
listeners := resp.Listeners
for i := range listeners {
listeners[i].Name = nil
}
return listeners
}