-
Notifications
You must be signed in to change notification settings - Fork 607
/
Copy pathdeploy.go
346 lines (291 loc) · 9.8 KB
/
deploy.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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
Copyright 2020 Cortex Labs, 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 cmd
import (
"fmt"
"path"
"strings"
"github.com/cortexlabs/cortex/cli/cluster"
"github.com/cortexlabs/cortex/cli/local"
"github.com/cortexlabs/cortex/cli/types/flags"
"github.com/cortexlabs/cortex/pkg/lib/archive"
"github.com/cortexlabs/cortex/pkg/lib/errors"
"github.com/cortexlabs/cortex/pkg/lib/exit"
"github.com/cortexlabs/cortex/pkg/lib/files"
libjson "github.com/cortexlabs/cortex/pkg/lib/json"
"github.com/cortexlabs/cortex/pkg/lib/pointer"
"github.com/cortexlabs/cortex/pkg/lib/print"
"github.com/cortexlabs/cortex/pkg/lib/prompt"
s "github.com/cortexlabs/cortex/pkg/lib/strings"
"github.com/cortexlabs/cortex/pkg/lib/table"
"github.com/cortexlabs/cortex/pkg/lib/telemetry"
"github.com/cortexlabs/cortex/pkg/operator/schema"
"github.com/cortexlabs/cortex/pkg/types"
"github.com/cortexlabs/cortex/pkg/types/userconfig"
"github.com/spf13/cobra"
)
var (
_warningFileBytes = 1024 * 1024 * 10
_warningProjectBytes = 1024 * 1024 * 10
_warningFileCount = 1000
_maxFileSizeBytes int64 = 1024 * 1024 * 512
_maxProjectSizeBytes int64 = 1024 * 1024 * 512
_flagDeployEnv string
_flagDeployForce bool
_flagDeployDisallowPrompt bool
)
func deployInit() {
_deployCmd.Flags().SortFlags = false
_deployCmd.Flags().StringVarP(&_flagDeployEnv, "env", "e", getDefaultEnv(_generalCommandType), "environment to use")
_deployCmd.Flags().BoolVarP(&_flagDeployForce, "force", "f", false, "override the in-progress api update")
_deployCmd.Flags().BoolVarP(&_flagDeployDisallowPrompt, "yes", "y", false, "skip prompts")
_deployCmd.Flags().VarP(&_flagOutput, "output", "o", fmt.Sprintf("output format: one of %s", strings.Join(flags.UserOutputTypeStrings(), "|")))
}
var _deployCmd = &cobra.Command{
Use: "deploy [CONFIG_FILE]",
Short: "create or update apis",
Args: cobra.RangeArgs(0, 1),
Run: func(cmd *cobra.Command, args []string) {
env, err := ReadOrConfigureEnv(_flagDeployEnv)
if err != nil {
telemetry.Event("cli.deploy")
exit.Error(err)
}
telemetry.Event("cli.deploy", map[string]interface{}{"provider": env.Provider.String(), "env_name": env.Name})
err = printEnvIfNotSpecified(_flagDeployEnv, cmd)
if err != nil {
exit.Error(err)
}
configPath := getConfigPath(args)
projectRoot := files.Dir(configPath)
if projectRoot == _homeDir {
exit.Error(ErrorDeployFromTopLevelDir("home", env.Provider))
}
if projectRoot == "/" {
exit.Error(ErrorDeployFromTopLevelDir("root", env.Provider))
}
var deployResults []schema.DeployResult
if env.Provider == types.LocalProviderType {
projectFiles, err := findProjectFiles(env.Provider, configPath)
if err != nil {
exit.Error(err)
}
local.OutputType = _flagOutput // Set output type for the Local package
deployResults, err = local.Deploy(env, configPath, projectFiles, _flagDeployDisallowPrompt)
if err != nil {
exit.Error(err)
}
} else {
deploymentBytes, err := getDeploymentBytes(env.Provider, configPath)
if err != nil {
exit.Error(err)
}
deployResults, err = cluster.Deploy(MustGetOperatorConfig(env.Name), configPath, deploymentBytes, _flagDeployForce)
if err != nil {
exit.Error(err)
}
}
switch _flagOutput {
case flags.JSONOutputType:
bytes, err := libjson.Marshal(deployResults)
if err != nil {
exit.Error(err)
}
fmt.Println(string(bytes))
case flags.MixedOutputType:
err := mixedPrint(deployResults)
if err != nil {
exit.Error(err)
}
case flags.PrettyOutputType:
message := deployMessage(deployResults, env.Name)
if didAnyResultsError(deployResults) {
print.StderrBoldFirstBlock(message)
} else {
print.BoldFirstBlock(message)
}
}
if didAnyResultsError(deployResults) {
exit.Error(nil)
}
},
}
// Returns absolute path
func getConfigPath(args []string) string {
var configPath string
if len(args) == 0 {
configPath = "cortex.yaml"
if !files.IsFile(configPath) {
exit.Error(ErrorCortexYAMLNotFound())
}
} else {
configPath = args[0]
if err := files.CheckFile(configPath); err != nil {
exit.Error(err)
}
}
return files.RelToAbsPath(configPath, _cwd)
}
func findProjectFiles(provider types.ProviderType, configPath string) ([]string, error) {
projectRoot := files.Dir(configPath)
ignoreFns := []files.IgnoreFn{
files.IgnoreSpecificFiles(configPath),
files.IgnoreCortexDebug,
files.IgnoreHiddenFiles,
files.IgnoreHiddenFolders,
files.IgnorePythonGeneratedFiles,
}
cortexIgnorePath := path.Join(projectRoot, ".cortexignore")
if files.IsFile(cortexIgnorePath) {
cortexIgnore, err := files.GitIgnoreFn(cortexIgnorePath)
if err != nil {
return nil, err
}
ignoreFns = append(ignoreFns, cortexIgnore)
}
if provider != types.LocalProviderType {
if !_flagDeployDisallowPrompt {
ignoreFns = append(ignoreFns, files.PromptForFilesAboveSize(_warningFileBytes, "do you want to upload %s (%s)?"))
}
ignoreFns = append(ignoreFns,
files.ErrorOnBigFilesFn(_maxFileSizeBytes),
// must be the last appended IgnoreFn
files.ErrorOnProjectSizeLimit(_maxProjectSizeBytes),
)
}
projectPaths, err := files.ListDirRecursive(projectRoot, false, ignoreFns...)
if err != nil {
return nil, err
}
// Include .env file containing environment variables
dotEnvPath := path.Join(projectRoot, ".env")
if files.IsFile(dotEnvPath) {
projectPaths = append(projectPaths, dotEnvPath)
}
return projectPaths, nil
}
func getDeploymentBytes(provider types.ProviderType, configPath string) (map[string][]byte, error) {
configBytes, err := files.ReadFileBytes(configPath)
if err != nil {
return nil, err
}
uploadBytes := map[string][]byte{
"config": configBytes,
}
projectRoot := files.Dir(configPath)
projectPaths, err := findProjectFiles(provider, configPath)
if err != nil {
return nil, err
}
canSkipPromptMsg := "you can skip this prompt next time with `cortex deploy --yes`\n"
rootDirMsg := "this directory"
if projectRoot != _cwd {
rootDirMsg = fmt.Sprintf("./%s", files.DirPathRelativeToCWD(projectRoot))
}
didPromptFileCount := false
if !_flagDeployDisallowPrompt && len(projectPaths) >= _warningFileCount {
msg := fmt.Sprintf("cortex will zip %d files in %s and upload them to the cluster; we recommend that you upload large files/directories (e.g. models) to s3 and download them in your api's __init__ function, and avoid sending unnecessary files by removing them from this directory or referencing them in a .cortexignore file. Would you like to continue?", len(projectPaths), rootDirMsg)
prompt.YesOrExit(msg, canSkipPromptMsg, "")
didPromptFileCount = true
}
projectZipBytes, _, err := archive.ZipToMem(&archive.Input{
FileLists: []archive.FileListInput{
{
Sources: projectPaths,
RemovePrefix: projectRoot,
},
},
})
if err != nil {
return nil, errors.Wrap(err, "failed to zip project folder")
}
if !_flagDeployDisallowPrompt && !didPromptFileCount && len(projectZipBytes) >= _warningProjectBytes {
msg := fmt.Sprintf("cortex will zip %d files in %s (%s) and upload them to the cluster, though we recommend you upload large files (e.g. models) to s3 and download them in your api's __init__ function. Would you like to continue?", len(projectPaths), rootDirMsg, s.IntToBase2Byte(len(projectZipBytes)))
prompt.YesOrExit(msg, canSkipPromptMsg, "")
}
uploadBytes["project.zip"] = projectZipBytes
return uploadBytes, nil
}
func deployMessage(results []schema.DeployResult, envName string) string {
statusMessage := mergeResultMessages(results)
if didAllResultsError(results) {
return statusMessage
}
apiCommandsMessage := getAPICommandsMessage(results, envName)
return statusMessage + "\n\n" + apiCommandsMessage
}
func mergeResultMessages(results []schema.DeployResult) string {
var okMessages []string
var errMessages []string
for _, result := range results {
if result.Error != "" {
errMessages = append(errMessages, result.Error)
} else {
okMessages = append(okMessages, result.Message)
}
}
output := ""
if len(okMessages) > 0 {
output += strings.Join(okMessages, "\n")
if len(errMessages) > 0 {
output += "\n\n"
}
}
if len(errMessages) > 0 {
output += strings.Join(errMessages, "\n")
}
return output
}
func didAllResultsError(results []schema.DeployResult) bool {
for _, result := range results {
if result.Error == "" {
return false
}
}
return true
}
func didAnyResultsError(results []schema.DeployResult) bool {
for _, result := range results {
if result.Error != "" {
return true
}
}
return false
}
func getAPICommandsMessage(results []schema.DeployResult, envName string) string {
apiName := "<api_name>"
if len(results) == 1 {
apiName = results[0].API.Spec.Name
}
defaultEnv := getDefaultEnv(_generalCommandType)
var envArg string
if envName != defaultEnv {
envArg = " --env " + envName
}
var items table.KeyValuePairs
items.Add("cortex get"+envArg, "(show api statuses)")
items.Add(fmt.Sprintf("cortex get %s%s", apiName, envArg), "(show api info)")
for _, result := range results {
if len(result.Error) > 0 {
continue
}
if result.API != nil && result.API.Spec.Kind == userconfig.RealtimeAPIKind {
items.Add(fmt.Sprintf("cortex logs %s%s", apiName, envArg), "(stream api logs)")
break
}
}
return strings.TrimSpace(items.String(&table.KeyValuePairOpts{
Delimiter: pointer.String(""),
NumSpaces: pointer.Int(2),
}))
}