-
Notifications
You must be signed in to change notification settings - Fork 63
/
create.go
233 lines (194 loc) · 6.52 KB
/
create.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package create
import (
"context"
"fmt"
"slices"
"strconv"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/spf13/cobra"
kraftcloud "sdk.kraft.cloud"
kcservices "sdk.kraft.cloud/services"
"kraftkit.sh/cmdfactory"
"kraftkit.sh/config"
"kraftkit.sh/internal/cli/kraft/cloud/utils"
)
type CreateOptions struct {
Auth *config.AuthConfig `noattribute:"true"`
Client kcservices.ServicesService `noattribute:"true"`
Domain []string `local:"true" long:"domain" short:"d" usage:"Specify the domain names of the service"`
SubDomain []string `local:"true" long:"subdomain" short:"s" usage:"Set the subdomains to use when creating the service"`
Metro string `noattribute:"true"`
Name string `local:"true" long:"name" short:"n" usage:"Specify the name of the service"`
Output string `local:"true" long:"output" short:"o" usage:"Set output format. Options: table,yaml,json,list" default:"table"`
Token string `noattribute:"true"`
}
// Create a KraftCloud instance.
func Create(ctx context.Context, opts *CreateOptions, args ...string) (*kcservices.CreateResponseItem, error) {
var err error
if opts == nil {
opts = &CreateOptions{}
}
// if len(opts.SubDomain) > 0 && len(opts.FQDN) > 0 {
// return nil, fmt.Errorf("the `--subdomain|-s` option is mutually exclusive with `--fqdn|--domain|-d`")
// }
if opts.Auth == nil {
opts.Auth, err = config.GetKraftCloudAuthConfig(ctx, opts.Token)
if err != nil {
return nil, fmt.Errorf("could not retrieve credentials: %w", err)
}
}
if opts.Client == nil {
opts.Client = kraftcloud.NewServicesClient(
kraftcloud.WithToken(config.GetKraftCloudTokenAuthConfig(*opts.Auth)),
)
}
var services []kcservices.CreateRequestService
if len(args) == 1 && strings.HasPrefix(args[0], "443:") && strings.Count(args[0], "/") == 0 {
split := strings.Split(args[0], ":")
if len(split) != 2 {
return nil, fmt.Errorf("malformed port expeted format EXTERNAL:INTERNAL[/HANDLER[,HANDLER...]]")
}
destPort, err := strconv.Atoi(split[1])
if err != nil {
return nil, fmt.Errorf("invalid external port: %w", err)
}
services = make([]kcservices.CreateRequestService, 0, 2)
port443 := 443
services = append(services,
kcservices.CreateRequestService{
Port: 443,
DestinationPort: &destPort,
Handlers: []kcservices.Handler{
kcservices.HandlerHTTP,
kcservices.HandlerTLS,
},
},
kcservices.CreateRequestService{
Port: 80,
DestinationPort: &port443,
Handlers: []kcservices.Handler{
kcservices.HandlerHTTP,
kcservices.HandlerRedirect,
},
},
)
} else {
services = make([]kcservices.CreateRequestService, 0, len(args))
for _, port := range args {
var service kcservices.CreateRequestService
if strings.ContainsRune(port, '/') {
split := strings.Split(port, "/")
if len(split) != 2 {
return nil, fmt.Errorf("malformed port, expected format EXTERNAL:INTERNAL[/HANDLER[,HANDLER...]]")
}
for _, handler := range strings.Split(split[1], "+") {
h := kcservices.Handler(handler)
if !slices.Contains(kcservices.Handlers(), h) {
return nil, fmt.Errorf("unknown handler: %s (choice of %v)", handler, kcservices.Handlers())
}
service.Handlers = append(service.Handlers, h)
}
port = split[0]
}
if strings.ContainsRune(port, ':') {
ports := strings.Split(port, ":")
if len(ports) != 2 {
return nil, fmt.Errorf("invalid --port value expected --port EXTERNAL:INTERNAL")
}
service.Port, err = strconv.Atoi(ports[0])
if err != nil {
return nil, fmt.Errorf("invalid internal port: %w", err)
}
dstPort, err := strconv.Atoi(ports[1])
if err != nil {
return nil, fmt.Errorf("invalid external port: %w", err)
}
service.DestinationPort = &dstPort
} else {
port, err := strconv.Atoi(port)
if err != nil {
return nil, fmt.Errorf("could not parse port number: %w", err)
}
service.Port = port
service.DestinationPort = &port
}
services = append(services, service)
}
}
req := kcservices.CreateRequest{
Services: services,
Domains: []kcservices.CreateRequestDomain{},
}
if opts.Name != "" {
req.Name = &opts.Name
}
for _, fqdn := range opts.Domain {
if !strings.HasSuffix(".", fqdn) {
fqdn += "."
}
req.Domains = append(req.Domains, kcservices.CreateRequestDomain{
Name: fqdn,
})
}
for _, subdomain := range opts.SubDomain {
dnsName := strings.TrimSuffix(subdomain, ".")
req.Domains = append(req.Domains, kcservices.CreateRequestDomain{
Name: dnsName,
})
}
sgResp, err := opts.Client.WithMetro(opts.Metro).Create(ctx, req)
if err != nil {
return nil, fmt.Errorf("creating service: %w", err)
}
sg, err := sgResp.FirstOrErr()
if err != nil {
return nil, fmt.Errorf("creating service: %w", err)
}
return sg, nil
}
func NewCmd() *cobra.Command {
cmd, err := cmdfactory.New(&CreateOptions{}, cobra.Command{
Short: "Create a service group",
Use: "create [FLAGS] EXTERNAL:INTERNAL[/HANDLER[+HANDLER...]]",
Args: cobra.MinimumNArgs(1),
Aliases: []string{"new"},
Long: "Create a service group.",
Example: heredoc.Doc(`
# Create a service group with a single service listening on port 443 named "my-service"
$ kraft cloud service create --name my-service 443:8080/http+tls
`),
Annotations: map[string]string{
cmdfactory.AnnotationHelpGroup: "kraftcloud-svc",
},
})
if err != nil {
panic(err)
}
return cmd
}
func (opts *CreateOptions) Pre(cmd *cobra.Command, _ []string) error {
err := utils.PopulateMetroToken(cmd, &opts.Metro, &opts.Token)
if err != nil {
return fmt.Errorf("could not populate metro and token: %w", err)
}
if !utils.IsValidOutputFormat(opts.Output) {
return fmt.Errorf("invalid output format: %s", opts.Output)
}
return nil
}
func (opts *CreateOptions) Run(ctx context.Context, args []string) error {
newSg, err := Create(ctx, opts, args...)
if err != nil {
return fmt.Errorf("creating service group: %w", err)
}
resp, err := opts.Client.WithMetro(opts.Metro).Get(ctx, newSg.UUID)
if err != nil {
return fmt.Errorf("getting details of service group %s: %w", newSg.UUID, err)
}
return utils.PrintServiceGroups(ctx, opts.Output, *resp)
}