-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcreate.go
More file actions
307 lines (262 loc) · 8.04 KB
/
create.go
File metadata and controls
307 lines (262 loc) · 8.04 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
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
// Copyright 2025 PingCAP, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sqluser
import (
"context"
"fmt"
"strings"
"time"
"github.com/tidbcloud/tidbcloud-cli/internal"
"github.com/tidbcloud/tidbcloud-cli/internal/config"
"github.com/tidbcloud/tidbcloud-cli/internal/flag"
"github.com/tidbcloud/tidbcloud-cli/internal/service/cloud"
"github.com/tidbcloud/tidbcloud-cli/internal/telemetry"
"github.com/tidbcloud/tidbcloud-cli/internal/ui"
"github.com/tidbcloud/tidbcloud-cli/internal/util"
"github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/iam"
"github.com/tidbcloud/tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/cluster"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/fatih/color"
"github.com/juju/errors"
"github.com/spf13/cobra"
)
type CreateOpts struct {
interactive bool
}
const (
WaitInterval = 5 * time.Second
WaitTimeout = 2 * time.Minute
DefaultAutoPrefix = true
)
var createSQLUserField = map[string]int{
flag.User: 0,
flag.Password: 1,
}
var supportedRoles = []string{
util.ADMIN_ROLE,
util.READWRITE_ROLE,
util.READONLY_ROLE,
}
func (c CreateOpts) NonInteractiveFlags() []string {
return []string{
flag.ClusterID,
flag.User,
flag.Password,
flag.UserRole,
}
}
func (c CreateOpts) RequiredFlags() []string {
return []string{
flag.ClusterID,
flag.User,
flag.Password,
flag.UserRole,
}
}
func CreateCmd(h *internal.Helper) *cobra.Command {
opts := CreateOpts{
interactive: true,
}
var CreateCmd = &cobra.Command{
Use: "create",
Short: "Create a SQL user",
Args: cobra.NoArgs,
Annotations: make(map[string]string),
Example: fmt.Sprintf(` Create a SQL user in interactive mode:
$ %[1]s serverless sql-user create
Create a SQL user in non-interactive mode:
$ %[1]s serverless sql-user create --user <user-name> --password <password> --role <role> --cluster-id <cluster-id>`,
config.CliName),
PreRunE: func(cmd *cobra.Command, args []string) error {
flags := opts.NonInteractiveFlags()
for _, fn := range flags {
f := cmd.Flags().Lookup(fn)
if f != nil && f.Changed {
opts.interactive = false
}
}
// mark required flags in non-interactive mode
if !opts.interactive {
for _, fn := range opts.RequiredFlags() {
err := cmd.MarkFlagRequired(fn)
if err != nil {
return errors.Trace(err)
}
}
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
d, err := h.Client()
if err != nil {
return err
}
var clusterID string
var userName string
var password string
var userRole []string
var userPrefix string
var customRoles []string
if opts.interactive {
cmd.Annotations[telemetry.InteractiveMode] = "true"
if !h.IOStreams.CanPrompt {
return errors.New("The terminal doesn't support interactive mode, please use non-interactive mode")
}
// interactive mode
project, err := cloud.GetSelectedProject(ctx, h.QueryPageSize, d)
if err != nil {
return err
}
projectID := project.ID
cluster, err := cloud.GetSelectedCluster(ctx, projectID, h.QueryPageSize, d)
if err != nil {
return err
}
clusterID = cluster.ID
userPrefix = cluster.UserPrefix
uRole, err := cloud.GetSelectedBuiltinRole()
if err != nil {
return err
}
userRole = append(userRole, uRole)
// variables for input
fmt.Fprintln(h.IOStreams.Out, color.BlueString("Please input the following options"))
p := tea.NewProgram(initialCreateInputModel(userPrefix))
inputModel, err := p.Run()
if err != nil {
return errors.Trace(err)
}
if inputModel.(ui.TextInputModel).Interrupted {
return util.InterruptError
}
userName = inputModel.(ui.TextInputModel).Inputs[createSQLUserField[flag.User]].Value()
password = inputModel.(ui.TextInputModel).Inputs[createSQLUserField[flag.Password]].Value()
} else {
// non-interactive mode doesn't need projectID
cID, err := cmd.Flags().GetString(flag.ClusterID)
if err != nil {
return errors.Trace(err)
}
clusterID = cID
userPrefix, err = getUserPrefix(ctx, d, clusterID)
if err != nil {
return errors.Trace(err)
}
uName, err := cmd.Flags().GetString(flag.User)
if err != nil {
return errors.Trace(err)
}
// if the user name has the prefix, remove it
uName = util.TrimUserNamePrefix(uName, userPrefix)
userName = uName
pw, err := cmd.Flags().GetString(flag.Password)
if err != nil {
return errors.Trace(err)
}
password = pw
uRole, err := cmd.Flags().GetStringSlice(flag.UserRole)
if err != nil {
return errors.Trace(err)
}
userRole = uRole
}
builtinRole, customRoles, err := getBuiltinRoleAndCustomRoles(userRole)
if err != nil {
return errors.Trace(err)
}
if util.IsNilOrEmpty(builtinRole) {
return errors.New("built-in role must be set")
}
authMethod := util.MYSQLNATIVEPASSWORD
autoPrefix := DefaultAutoPrefix
params := &iam.ApiCreateSqlUserReq{
AuthMethod: &authMethod,
UserName: &userName,
BuiltinRole: builtinRole,
CustomRoles: customRoles,
Password: &password,
AutoPrefix: &autoPrefix,
}
_, err = d.CreateSQLUser(ctx, clusterID, params)
if err != nil {
return errors.Trace(err)
}
_, err = fmt.Fprintln(h.IOStreams.Out, color.GreenString("SQL user %s.%s is created", userPrefix, userName))
if err != nil {
return err
}
return nil
},
}
CreateCmd.Flags().StringP(flag.ClusterID, flag.ClusterIDShort, "", "The ID of the cluster.")
CreateCmd.Flags().StringP(flag.User, flag.UserShort, "", "The name of the SQL user, user prefix will be added automatically.")
CreateCmd.Flags().StringP(flag.Password, "", "", "The password of the SQL user.")
CreateCmd.Flags().StringSliceP(flag.UserRole, "", nil, fmt.Sprintf("The role(s) of the SQL user, supported roles %q", supportedRoles))
return CreateCmd
}
func initialCreateInputModel(userPrefix string) ui.TextInputModel {
m := ui.TextInputModel{
Inputs: make([]textinput.Model, len(createSQLUserField)),
}
for k, v := range createSQLUserField {
t := textinput.New()
t.Cursor.Style = config.CursorStyle
t.CharLimit = 32
switch k {
case flag.User:
// add a prefix showing the user prefix
t.Placeholder = "User Name"
t.Focus()
t.PromptStyle = config.FocusedStyle
t.TextStyle = config.FocusedStyle
t.Prompt = "> " + userPrefix + "."
case flag.Password:
t.Placeholder = "Password"
t.EchoMode = textinput.EchoPassword
t.EchoCharacter = '•'
}
m.Inputs[v] = t
}
return m
}
func getUserPrefix(ctx context.Context, d cloud.TiDBCloudClient, clusterID string) (string, error) {
cluster, err := d.GetCluster(ctx, clusterID, cluster.SERVERLESSSERVICEGETCLUSTERVIEWPARAMETER_BASIC)
if err != nil {
return "", errors.Trace(err)
}
return *cluster.UserPrefix, nil
}
func getBuiltinRoleAndCustomRoles(roles []string) (*string, []string, error) {
builtinRole := ""
customRoles := make([]string, 0, len(roles))
for _, role := range roles {
role = strings.TrimSpace(role)
if util.IsBuiltinRole(role) {
if builtinRole == "" {
switch role {
case util.ADMIN_ROLE:
builtinRole = util.ADMIN_ROLE
case util.READWRITE_ROLE:
builtinRole = util.READWRITE_ROLE
case util.READONLY_ROLE:
builtinRole = util.READONLY_ROLE
}
} else {
return nil, []string{}, errors.New("only one built-in role is allowed")
}
} else {
customRoles = append(customRoles, role)
}
}
return &builtinRole, customRoles, nil
}