-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserviceCreate.go
More file actions
240 lines (217 loc) · 7.88 KB
/
Copy pathserviceCreate.go
File metadata and controls
240 lines (217 loc) · 7.88 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
package cmd
import (
"context"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/zeropsio/zcli/src/cmdBuilder"
"github.com/zeropsio/zcli/src/entity"
"github.com/zeropsio/zcli/src/entity/repository"
"github.com/zeropsio/zcli/src/i18n"
"github.com/zeropsio/zcli/src/terminal"
"github.com/zeropsio/zcli/src/units"
"github.com/zeropsio/zcli/src/uxBlock"
"github.com/zeropsio/zcli/src/uxBlock/models/input"
"github.com/zeropsio/zcli/src/uxBlock/styles"
"github.com/zeropsio/zcli/src/uxHelpers"
"github.com/zeropsio/zcli/src/yamlReader"
"github.com/zeropsio/zerops-go/apiError"
"github.com/zeropsio/zerops-go/errorCode"
"github.com/zeropsio/zerops-go/types"
"github.com/zeropsio/zerops-go/types/stringId"
)
const maxEnvFileSize = units.MiB
func serviceCreateCmd() *cmdBuilder.Cmd {
return cmdBuilder.NewCmd().
Use("create").
Short("Crates a new project for specified project.").
ScopeLevel(cmdBuilder.ScopeProject()).
StringFlag("zerops-yaml-path", "", i18n.T(i18n.ZeropsYamlLocation)).
StringFlag("working-dir", "./", i18n.T(i18n.BuildWorkingDir)).
StringFlag("name", "", "Service name").
StringFlag("mode", "NON_HA", "Service mode [HA, NON_HA]").
StringFlag("out", "", "Output format of command, using golang's text/template engine. Entity fields: "+formatAllowedTemplateFields(entity.ServiceFields)).
StringFlag("env-file", "", "File with envs (will be set as secrets, runtime envs can be defined in zerops.yml). Max file size is "+units.ByteCountIEC(maxEnvFileSize)).
StringFlag("env-isolation", "service", "Env isolation rule [service, none] for more info see docs https://docs.zerops.io/features/env-variables#isolation-modes").
StringFlag("ssh-isolation", "vpn", "SSH isolation rules, for more info see docs https://docs.zerops.io/references/ssh#ssh-access-control").
StringFlag("location", "", "Service location (e.g. eu-central).", cmdBuilder.HiddenFlag()).
StringSliceFlag("env", nil, "Envs to be set as secrets, runtime envs can be defined in zerops.yml. Accepts comma separated string or repeated flag. Format: {key}={value}").
BoolFlag("start-without-code", false, "Start service immediately, empty without deploy").
BoolFlag("noop", false, "Creates service only if none with the same name exists").
HelpFlag("Help for the service create command.").
LoggedUserRunFunc(func(ctx context.Context, cmdData *cmdBuilder.LoggedUserCmdData) error {
project, err := cmdData.Project.Expect("project is nil")
if err != nil {
return err
}
startWithoutCode := cmdData.Params.GetBool("start-without-code")
mode := cmdData.Params.GetString("mode")
mode = strings.ToUpper(mode)
if mode != "HA" && mode != "NON_HA" {
return errors.Errorf("Invalid --mode, expected one of [HA, NON_HA], got %s", mode)
}
envFile, err := readServiceEnvFile(cmdData)
if err != nil {
return err
}
outFormat := cmdData.Params.GetString("out")
var outTemplate *template.Template
if outFormat != "" {
outTemplate, err = template.New("out").Parse(outFormat)
if err != nil {
return errors.WithStack(err)
}
}
configContent, err := yamlReader.ReadZeropsYamlContent(
cmdData.UxBlocks,
cmdData.Params.GetString("working-dir"),
cmdData.Params.GetString("zerops-yaml-path"),
yamlReader.WithReturnErrOnZeropsYamlNotFound(false),
)
if err != nil {
return err
}
var suggestions []string
if len(configContent) > 0 {
setups, err := yamlReader.ReadZeropsYamlSetups(configContent)
if err != nil {
return err
}
suggestions = setups
}
name, err := resolveServiceName(ctx, cmdData.Params.GetString("name"), suggestions)
if err != nil {
return err
}
postService := entity.PostService{
ProjectId: project.Id,
Name: types.NewString(name),
Mode: types.NewString(mode),
EnvFile: envFile,
StartWithoutCode: types.NewBool(startWithoutCode),
SshIsolation: types.NewStringNull(cmdData.Params.GetString("ssh-isolation")),
EnvIsolation: types.NewStringNull(cmdData.Params.GetString("env-isolation")),
}
if loc := cmdData.Params.GetString("location"); loc != "" {
postService.Location = stringId.NewLocationIdNullFromString(loc)
}
// Service-level location picker is intentionally disabled for now —
// the --location flag stays available (hidden) for internal testing.
// } else if terminal.IsTerminal() {
// location, err := uxHelpers.PrintLocationSelector(ctx, cmdData.RestApiClient)
// if err != nil {
// return err
// }
// postService.Location = location.Id.LocationIdNull()
// cmdData.UxBlocks.PrintInfo(styles.InfoWithValueLine("Selected location", location.Name.String()))
// }
process, service, err := repository.PostGenericService(
ctx,
cmdData.RestApiClient,
postService,
)
if err != nil {
noop := cmdData.Params.GetBool("noop")
if apiError.HasErrorCode(err, errorCode.ServiceStackNameUnavailable) && noop {
service, err := repository.GetServiceByName(ctx, cmdData.RestApiClient, project.Id, types.NewString(name))
if err != nil {
return err
}
cmdData.UxBlocks.PrintInfoText("Service with the same name already exists")
if outTemplate != nil {
if err := outTemplate.Execute(cmdData.Stdout, service); err != nil {
return errors.WithStack(err)
}
}
return nil
}
return err
}
if err := uxHelpers.ProcessCheckWithSpinner(
ctx,
cmdData.UxBlocks,
[]uxHelpers.Process{
{
F: uxHelpers.CheckZeropsProcess(process.Id, cmdData.RestApiClient, cmdData.UxBlocks),
RunningMessage: "Creating service",
ErrorMessageMessage: "Service creation failed",
SuccessMessage: "Service created",
},
},
); err != nil {
return err
}
service, err = repository.GetServiceById(ctx, cmdData.RestApiClient, service.Id)
if err != nil {
return err
}
if outTemplate != nil {
if err := outTemplate.Execute(cmdData.Stdout, service); err != nil {
return errors.WithStack(err)
}
}
return nil
})
}
func readServiceEnvFile(cmdData *cmdBuilder.LoggedUserCmdData) (types.TextNull, error) {
var envFile types.TextNull
envFilePath := cmdData.Params.GetString("env-file")
if envFilePath != "" {
workingDir := cmdData.Params.GetString("working-dir")
absPath, err := filepath.Abs(path.Join(workingDir, envFilePath))
if err != nil {
return envFile, errors.WithStack(err)
}
stat, err := os.Stat(absPath)
if err != nil {
return envFile, errors.WithStack(err)
}
if stat.IsDir() {
return envFile, errors.New("--env-file must point to a file")
}
if stat.Size() > int64(maxEnvFileSize) {
return envFile, errors.Errorf("Env file size too large, max allowed size %s", units.ByteCountIEC(maxEnvFileSize))
}
content, err := os.ReadFile(absPath)
if err != nil {
return envFile, errors.WithStack(err)
}
envFile = types.NewTextNull(string(content))
}
envSlice := cmdData.Params.GetStringSlice("env")
if len(envSlice) > 0 {
envs := strings.Join(envSlice, "\n")
if f, filled := envFile.Get(); filled {
envFile = types.NewTextNull(f.Native() + "\n" + envs)
} else {
envFile = types.NewTextNull(envs)
}
}
return envFile, nil
}
func resolveServiceName(ctx context.Context, flagName string, suggestions []string) (string, error) {
if flagName != "" {
return flagName, nil
}
if !terminal.IsTerminal() {
return "", errors.New("Must specify name with --name")
}
label := styles.NewStringBuilder()
label.WriteString("Type ")
label.WriteStyledString(styles.SelectStyle().Bold(true), "service")
label.WriteString(" name")
return uxBlock.Run(
input.NewRoot(
ctx,
input.WithLabel(label.String()),
input.WithHelpPlaceholder(),
input.WithPlaceholderStyle(styles.HelpStyle()),
input.WithoutPrompt(),
input.WithSetSuggestions(suggestions),
),
input.GetValueFunc,
)
}