-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcreate.go
More file actions
268 lines (225 loc) · 7.67 KB
/
create.go
File metadata and controls
268 lines (225 loc) · 7.67 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
261
262
263
264
265
266
267
268
package create
import (
"context"
"fmt"
"math/rand"
"time"
runtimev1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
"github.com/crossplane/crossplane-runtime/pkg/resource"
"github.com/lucasepe/codename"
"github.com/ninech/nctl/api"
"github.com/ninech/nctl/internal/format"
"github.com/theckman/yacspin"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/util/retry"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
type Cmd struct {
Filename string `short:"f" help:"Create any resource from a yaml or json file." predictor:"file"`
FromFile fromFile `cmd:"" default:"1" name:"-f <file>" help:"Create any resource from a yaml or json file."`
VCluster vclusterCmd `cmd:"" group:"infrastructure.nine.ch" name:"vcluster" help:"Create a new vcluster."`
APIServiceAccount apiServiceAccountCmd `cmd:"" group:"iam.nine.ch" name:"apiserviceaccount" aliases:"asa" help:"Create a new API Service Account."`
Project projectCmd `cmd:"" group:"management.nine.ch" name:"project" help:"Create a new project."`
Config configCmd `cmd:"" group:"deplo.io" name:"config" help:"Create a new deplo.io Project Configuration."`
Application applicationCmd `cmd:"" group:"deplo.io" name:"application" aliases:"app,application" help:"Create a new deplo.io Application."`
MySQL mySQLCmd `cmd:"" group:"storage.nine.ch" name:"mysql" help:"Create a new MySQL instance."`
MySQLDatabase mysqlDatabaseCmd `cmd:"" group:"storage.nine.ch" name:"mysqldatabase" help:"Create a new MySQL database."`
Postgres postgresCmd `cmd:"" group:"storage.nine.ch" name:"postgres" help:"Create a new PostgreSQL instance."`
PostgresDatabase postgresDatabaseCmd `cmd:"" group:"storage.nine.ch" name:"postgresdatabase" help:"Create a new PostgreSQL database."`
KeyValueStore keyValueStoreCmd `cmd:"" group:"storage.nine.ch" name:"keyvaluestore" aliases:"kvs" help:"Create a new KeyValueStore instance."`
OpenSearch openSearchCmd `cmd:"" group:"storage.nine.ch" name:"opensearch" aliases:"os" help:"Create a new OpenSearch cluster."`
CloudVirtualMachine cloudVMCmd `cmd:"" group:"infrastructure.nine.ch" name:"cloudvirtualmachine" aliases:"cloudvm" help:"Create a new CloudVM."`
ServiceConnection serviceConnectionCmd `cmd:"" group:"networking.nine.ch" name:"serviceconnection" aliases:"sc" help:"Create a new ServiceConnection."`
}
type resourceCmd struct {
Name string `arg:"" help:"Name of the new resource. A random name is generated if omitted." default:""`
Wait bool `default:"true" help:"Wait until resource is fully created."`
WaitTimeout time.Duration `default:"30m" help:"Duration to wait for resource getting ready. Only relevant if wait is set."`
}
// resultFunc is the function called on a watch event during creation. It
// should return true whenever the wait can be considered done.
type resultFunc func(watch.Event) (bool, error)
type creator struct {
client *api.Client
mg resource.Managed
kind string
}
type waitStage struct {
kind string
waitMessage *message
doneMessage *message
objectList runtimeclient.ObjectList
listOpts []runtimeclient.ListOption
onResult resultFunc
spinner *yacspin.Spinner
disableSpinner bool
// beforeWait is a hook that is called just before the wait is being run.
beforeWait func()
// afterWait is a hook that is called after the wait to clean up.
afterWait func()
}
type message struct {
icon string
text string
disabled bool
}
var watchBackoff = wait.Backoff{
Steps: 15,
Duration: 10 * time.Millisecond,
Factor: 1.0,
Jitter: 0.1,
}
func (m *message) progress() string {
if m.disabled {
return ""
}
return format.ProgressMessage(m.icon, m.text)
}
func (m *message) printSuccess() {
if m.disabled {
return
}
format.PrintSuccess(m.icon, m.text)
}
func newCreator(client *api.Client, mg resource.Managed, resourceName string) *creator {
return &creator{client: client, mg: mg, kind: resourceName}
}
func (c *creator) createResource(ctx context.Context) error {
if err := c.client.Create(ctx, c.mg); err != nil {
return fmt.Errorf("unable to create %s %q: %w", c.kind, c.mg.GetName(), err)
}
format.PrintSuccessf("🏗", "created %s %q in project %q", c.kind, c.mg.GetName(), c.mg.GetNamespace())
return nil
}
func (c *creator) wait(ctx context.Context, stages ...waitStage) error {
for _, stage := range stages {
if stage.afterWait != nil {
defer stage.afterWait()
}
stage.setDefaults(c)
spinner, err := format.NewSpinner(
stage.waitMessage.progress(),
stage.waitMessage.progress(),
)
if err != nil {
return err
}
stage.spinner = spinner
if stage.beforeWait != nil {
stage.beforeWait()
}
if err := retry.OnError(watchBackoff, isWatchError, func() error {
return stage.wait(ctx, c.client)
}); err != nil {
_ = stage.spinner.StopFail()
_ = stage.spinner.Stop()
return err
}
}
return nil
}
func (w *waitStage) setDefaults(c *creator) {
if len(w.kind) == 0 {
w.kind = c.kind
}
if w.waitMessage == nil {
w.waitMessage = &message{
text: fmt.Sprintf("waiting for %s to be ready", w.kind),
icon: "⏳",
}
}
if w.doneMessage == nil {
w.doneMessage = &message{
text: fmt.Sprintf("%s ready", w.kind),
icon: "🛫",
}
}
if len(w.listOpts) == 0 {
w.listOpts = []runtimeclient.ListOption{
runtimeclient.InNamespace(c.mg.GetNamespace()),
runtimeclient.MatchingFields{"metadata.name": c.mg.GetName()},
}
}
}
type watchError struct {
kind string
}
func (werr watchError) Error() string {
return fmt.Sprintf("error watching %s, the API might be experiencing connectivity issues", werr.kind)
}
func isWatchError(err error) bool {
_, ok := err.(watchError)
return ok
}
func (w *waitStage) wait(ctx context.Context, client *api.Client) error {
if !w.disableSpinner {
_ = w.spinner.Start()
}
return w.watch(ctx, client)
}
func (w *waitStage) watch(ctx context.Context, client *api.Client) error {
wa, err := client.Watch(ctx, w.objectList, w.listOpts...)
if err != nil {
if err == context.Canceled {
return err
}
return watchError{kind: w.kind}
}
for {
select {
case res := <-wa.ResultChan():
if res.Type == watch.Error || res.Type == "" {
return watchError{kind: w.kind}
}
done, err := w.onResult(res)
if err != nil {
_ = w.spinner.StopFail()
return err
}
if done {
wa.Stop()
_ = w.spinner.Stop()
// print out the done message directly
w.doneMessage.printSuccess()
return nil
}
case <-ctx.Done():
switch ctx.Err() {
case context.DeadlineExceeded:
msg := "timeout waiting for %s"
w.spinner.StopFailMessage(format.ProgressMessagef("", msg, w.kind))
_ = w.spinner.StopFail()
return fmt.Errorf(msg, w.kind)
case context.Canceled:
_ = w.spinner.StopFail()
return nil
}
}
}
}
func resourceAvailable(event watch.Event) (bool, error) {
mg, ok := event.Object.(resource.Managed)
if !ok {
return false, nil
}
return isAvailable(mg), nil
}
func isAvailable(mg resource.Managed) bool {
return mg.GetCondition(runtimev1.TypeReady).Reason == runtimev1.ReasonAvailable &&
mg.GetCondition(runtimev1.TypeReady).Status == corev1.ConditionTrue
}
func getName(name string) string {
if len(name) != 0 {
return name
}
return codename.Generate(rand.New(rand.NewSource(time.Now().UnixNano())), 0)
}
func stringSlice[K ~string](elems []K) []string {
s := make([]string, 0, len(elems))
for _, elem := range elems {
s = append(s, string(elem))
}
return s
}