forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
push.go
680 lines (573 loc) · 21.3 KB
/
push.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package application
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"github.com/blang/semver"
. "github.com/cloudfoundry/cli/cf/i18n"
"github.com/cloudfoundry/cli/flags"
"github.com/cloudfoundry/cli/cf/actors"
"github.com/cloudfoundry/cli/cf/api"
"github.com/cloudfoundry/cli/cf/api/applications"
"github.com/cloudfoundry/cli/cf/api/authentication"
"github.com/cloudfoundry/cli/cf/api/stacks"
"github.com/cloudfoundry/cli/cf/app_files"
"github.com/cloudfoundry/cli/cf/command_registry"
"github.com/cloudfoundry/cli/cf/commands/service"
"github.com/cloudfoundry/cli/cf/configuration/core_config"
"github.com/cloudfoundry/cli/cf/errors"
"github.com/cloudfoundry/cli/cf/formatters"
"github.com/cloudfoundry/cli/cf/manifest"
"github.com/cloudfoundry/cli/cf/models"
"github.com/cloudfoundry/cli/cf/requirements"
"github.com/cloudfoundry/cli/cf/terminal"
"github.com/cloudfoundry/cli/words/generator"
)
type Push struct {
ui terminal.UI
config core_config.Reader
manifestRepo manifest.ManifestRepository
appStarter ApplicationStarter
appStopper ApplicationStopper
serviceBinder service.ServiceBinder
appRepo applications.ApplicationRepository
domainRepo api.DomainRepository
routeRepo api.RouteRepository
serviceRepo api.ServiceRepository
stackRepo stacks.StackRepository
authRepo authentication.AuthenticationRepository
wordGenerator generator.WordGenerator
actor actors.PushActor
zipper app_files.Zipper
appfiles app_files.AppFiles
}
func init() {
command_registry.Register(&Push{})
}
func (cmd *Push) MetaData() command_registry.CommandMetadata {
fs := make(map[string]flags.FlagSet)
fs["b"] = &flags.StringFlag{ShortName: "b", Usage: T("Custom buildpack by name (e.g. my-buildpack) or Git URL (e.g. 'https://github.com/cloudfoundry/java-buildpack.git') or Git URL with a branch or tag (e.g. 'https://github.com/cloudfoundry/java-buildpack.git#v3.3.0' for 'v3.3.0' tag). To use built-in buildpacks only, specify 'default' or 'null'")}
fs["c"] = &flags.StringFlag{ShortName: "c", Usage: T("Startup command, set to null to reset to default start command")}
fs["d"] = &flags.StringFlag{ShortName: "d", Usage: T("Domain (e.g. example.com)")}
fs["f"] = &flags.StringFlag{ShortName: "f", Usage: T("Path to manifest")}
fs["i"] = &flags.IntFlag{ShortName: "i", Usage: T("Number of instances")}
fs["k"] = &flags.StringFlag{ShortName: "k", Usage: T("Disk limit (e.g. 256M, 1024M, 1G)")}
fs["m"] = &flags.StringFlag{ShortName: "m", Usage: T("Memory limit (e.g. 256M, 1024M, 1G)")}
fs["hostname"] = &flags.StringFlag{Name: "hostname", ShortName: "n", Usage: T("Hostname (e.g. my-subdomain)")}
fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Path to app directory or to a zip file of the contents of the app directory")}
fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Stack to use (a stack is a pre-built file system, including an operating system, that can run apps)")}
fs["t"] = &flags.StringFlag{ShortName: "t", Usage: T("Maximum time (in seconds) for CLI to wait for application start, other server side timeouts may apply")}
fs["docker-image"] = &flags.StringFlag{Name: "docker-image", ShortName: "o", Usage: T("Docker-image to be used (e.g. user/docker-image-name)")}
fs["health-check-type"] = &flags.StringFlag{Name: "health-check-type", ShortName: "u", Usage: T("Application health check type (e.g. 'port' or 'none')")}
fs["no-hostname"] = &flags.BoolFlag{Name: "no-hostname", Usage: T("Map the root domain to this app")}
fs["no-manifest"] = &flags.BoolFlag{Name: "no-manifest", Usage: T("Ignore manifest file")}
fs["no-route"] = &flags.BoolFlag{Name: "no-route", Usage: T("Do not map a route to this app and remove routes from previous pushes of this app")}
fs["no-start"] = &flags.BoolFlag{Name: "no-start", Usage: T("Do not start an app after pushing")}
fs["random-route"] = &flags.BoolFlag{Name: "random-route", Usage: T("Create a random route for this app")}
fs["route-path"] = &flags.StringFlag{Name: "route-path", Usage: T("Path for the route")}
return command_registry.CommandMetadata{
Name: "push",
ShortName: "p",
Description: T("Push a new app or sync changes to an existing app"),
Usage: T("Push a single app (with or without a manifest):\n") + T(" CF_NAME push APP_NAME [-b BUILDPACK_NAME] [-c COMMAND] [-d DOMAIN] [-f MANIFEST_PATH] [--docker-image DOCKER_IMAGE]\n") + T(" [-i NUM_INSTANCES] [-k DISK] [-m MEMORY] [--hostname HOST] [-p PATH] [-s STACK] [-t TIMEOUT] [-u HEALTH_CHECK_TYPE] [--route-path ROUTE_PATH]\n") +
" [--no-hostname] [--no-manifest] [--no-route] [--no-start]\n" +
"\n" + T(" Push multiple apps with a manifest:\n") + T(" CF_NAME push [-f MANIFEST_PATH]\n"),
Flags: fs,
}
}
func (cmd *Push) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
if len(fc.Args()) > 1 {
cmd.ui.Failed(T("Incorrect Usage.\n\n") + command_registry.Commands.CommandUsage("push"))
}
var reqs []requirements.Requirement
if fc.String("route-path") != "" {
requiredVersion, err := semver.Make("2.36.0")
if err != nil {
panic(err.Error())
}
reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--route-path'", requiredVersion))
}
reqs = append(reqs, []requirements.Requirement{
requirementsFactory.NewLoginRequirement(),
requirementsFactory.NewTargetedSpaceRequirement(),
}...)
return reqs, nil
}
func (cmd *Push) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {
cmd.ui = deps.Ui
cmd.config = deps.Config
cmd.manifestRepo = deps.ManifestRepo
//set appStarter
appCommand := command_registry.Commands.FindCommand("start")
appCommand = appCommand.SetDependency(deps, false)
cmd.appStarter = appCommand.(ApplicationStarter)
//set appStopper
appCommand = command_registry.Commands.FindCommand("stop")
appCommand = appCommand.SetDependency(deps, false)
cmd.appStopper = appCommand.(ApplicationStopper)
//set serviceBinder
appCommand = command_registry.Commands.FindCommand("bind-service")
appCommand = appCommand.SetDependency(deps, false)
cmd.serviceBinder = appCommand.(service.ServiceBinder)
cmd.appRepo = deps.RepoLocator.GetApplicationRepository()
cmd.domainRepo = deps.RepoLocator.GetDomainRepository()
cmd.routeRepo = deps.RepoLocator.GetRouteRepository()
cmd.serviceRepo = deps.RepoLocator.GetServiceRepository()
cmd.stackRepo = deps.RepoLocator.GetStackRepository()
cmd.authRepo = deps.RepoLocator.GetAuthenticationRepository()
cmd.wordGenerator = deps.WordGenerator
cmd.actor = deps.PushActor
cmd.zipper = deps.AppZipper
cmd.appfiles = deps.AppFiles
return cmd
}
func (cmd *Push) Execute(c flags.FlagContext) {
appsFromManifest := cmd.getAppParamsFromManifest(c)
appFromContext := cmd.getAppParamsFromContext(c)
appSet := cmd.createAppSetFromContextAndManifest(appFromContext, appsFromManifest)
_, err := cmd.authRepo.RefreshAuthToken()
if err != nil {
cmd.ui.Failed(err.Error())
return
}
routeActor := actors.NewRouteActor(cmd.ui, cmd.routeRepo)
for _, appParams := range appSet {
if appParams.Name == nil {
cmd.ui.Failed(T("Error: No name found for app"))
}
cmd.fetchStackGuid(&appParams)
if c.IsSet("docker-image") {
diego := true
appParams.Diego = &diego
}
var app models.Application
existingApp, err := cmd.appRepo.Read(*appParams.Name)
switch err.(type) {
case nil:
cmd.ui.Say(T("Updating app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
map[string]interface{}{
"AppName": terminal.EntityNameColor(existingApp.Name),
"OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
"Username": terminal.EntityNameColor(cmd.config.Username())}))
if appParams.EnvironmentVars != nil {
for key, val := range existingApp.EnvironmentVars {
if _, ok := (*appParams.EnvironmentVars)[key]; !ok {
(*appParams.EnvironmentVars)[key] = val
}
}
}
app, err = cmd.appRepo.Update(existingApp.Guid, appParams)
if err != nil {
cmd.ui.Failed(err.Error())
}
case *errors.ModelNotFoundError:
spaceGuid := cmd.config.SpaceFields().Guid
appParams.SpaceGuid = &spaceGuid
cmd.ui.Say(T("Creating app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
map[string]interface{}{
"AppName": terminal.EntityNameColor(*appParams.Name),
"OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
"Username": terminal.EntityNameColor(cmd.config.Username())}))
app, err = cmd.appRepo.Create(appParams)
if err != nil {
cmd.ui.Failed(err.Error())
}
default:
cmd.ui.Failed(err.Error())
}
cmd.ui.Ok()
cmd.ui.Say("")
cmd.updateRoutes(routeActor, app, appParams)
if c.String("docker-image") == "" {
err := cmd.actor.ProcessPath(*appParams.Path, cmd.processPathCallback(*appParams.Path, app))
if err != nil {
cmd.ui.Failed(
T("Error processing app files: {{.Error}}",
map[string]interface{}{
"Error": err.Error(),
}),
)
return
}
}
if appParams.ServicesToBind != nil {
cmd.bindAppToServices(*appParams.ServicesToBind, app)
}
cmd.restart(app, appParams, c)
}
}
func (cmd *Push) processPathCallback(path string, app models.Application) func(string) {
return func(appDir string) {
localFiles, err := cmd.appfiles.AppFilesInDir(appDir)
if err != nil {
cmd.ui.Failed(
T("Error processing app files in '{{.Path}}': {{.Error}}",
map[string]interface{}{
"Path": path,
"Error": err.Error(),
}),
)
}
if len(localFiles) == 0 {
cmd.ui.Failed(
T("No app files found in '{{.Path}}'",
map[string]interface{}{
"Path": path,
}),
)
}
cmd.ui.Say(T("Uploading {{.AppName}}...",
map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))
err = cmd.uploadApp(app.Guid, appDir, path, localFiles)
if err != nil {
cmd.ui.Failed(fmt.Sprintf(T("Error uploading application.\n{{.ApiErr}}",
map[string]interface{}{"ApiErr": err.Error()})))
return
}
cmd.ui.Ok()
}
}
func (cmd *Push) updateRoutes(routeActor actors.RouteActor, app models.Application, appParams models.AppParams) {
defaultRouteAcceptable := len(app.Routes) == 0
routeDefined := appParams.Domains != nil || !appParams.IsHostEmpty() || appParams.NoHostname
if appParams.NoRoute {
if len(app.Routes) == 0 {
cmd.ui.Say(T("App {{.AppName}} is a worker, skipping route creation",
map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))
} else {
routeActor.UnbindAll(app)
}
return
}
if routeDefined || defaultRouteAcceptable {
if appParams.Domains == nil {
cmd.processDomainsAndBindRoutes(appParams, routeActor, app, cmd.findDomain(nil))
} else {
for _, d := range *(appParams.Domains) {
cmd.processDomainsAndBindRoutes(appParams, routeActor, app, cmd.findDomain(&d))
}
}
}
}
func (cmd *Push) processDomainsAndBindRoutes(appParams models.AppParams, routeActor actors.RouteActor, app models.Application, domain models.DomainFields) {
if appParams.IsHostEmpty() {
cmd.createAndBindRoute(nil, appParams.UseRandomHostname, routeActor, app, appParams.NoHostname, domain, appParams.RoutePath)
} else {
for _, host := range *(appParams.Hosts) {
cmd.createAndBindRoute(&host, appParams.UseRandomHostname, routeActor, app, appParams.NoHostname, domain, appParams.RoutePath)
}
}
}
func (cmd *Push) createAndBindRoute(host *string, UseRandomHostname bool, routeActor actors.RouteActor, app models.Application, noHostName bool, domain models.DomainFields, routePath *string) {
var hostname string
if !noHostName {
switch {
case host != nil:
hostname = *host
case UseRandomHostname:
hostname = hostNameForString(app.Name) + "-" + cmd.wordGenerator.Babble()
default:
hostname = hostNameForString(app.Name)
}
}
var route models.Route
if routePath != nil {
route = routeActor.FindOrCreateRoute(hostname, domain, *routePath)
} else {
route = routeActor.FindOrCreateRoute(hostname, domain, "")
}
routeActor.BindRoute(app, route)
}
var forbiddenHostCharRegex = regexp.MustCompile("[^a-z0-9-]")
var whitespaceRegex = regexp.MustCompile(`[\s_]+`)
func hostNameForString(name string) string {
name = strings.ToLower(name)
name = whitespaceRegex.ReplaceAllString(name, "-")
name = forbiddenHostCharRegex.ReplaceAllString(name, "")
return name
}
func (cmd *Push) findDomain(domainName *string) (domain models.DomainFields) {
domain, err := cmd.domainRepo.FirstOrDefault(cmd.config.OrganizationFields().Guid, domainName)
if err != nil {
cmd.ui.Failed(err.Error())
}
return
}
func (cmd *Push) bindAppToServices(services []string, app models.Application) {
for _, serviceName := range services {
serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceName)
if err != nil {
cmd.ui.Failed(T("Could not find service {{.ServiceName}} to bind to {{.AppName}}",
map[string]interface{}{"ServiceName": serviceName, "AppName": app.Name}))
return
}
cmd.ui.Say(T("Binding service {{.ServiceName}} to app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.Username}}...",
map[string]interface{}{
"ServiceName": terminal.EntityNameColor(serviceInstance.Name),
"AppName": terminal.EntityNameColor(app.Name),
"OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
"SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name),
"Username": terminal.EntityNameColor(cmd.config.Username())}))
err = cmd.serviceBinder.BindApplication(app, serviceInstance, nil)
switch httpErr := err.(type) {
case errors.HttpError:
if httpErr.ErrorCode() == errors.APP_ALREADY_BOUND {
err = nil
}
}
if err != nil {
cmd.ui.Failed(T("Could not bind to service {{.ServiceName}}\nError: {{.Err}}",
map[string]interface{}{"ServiceName": serviceName, "Err": err.Error()}))
}
cmd.ui.Ok()
}
}
func (cmd *Push) fetchStackGuid(appParams *models.AppParams) {
if appParams.StackName == nil {
return
}
stackName := *appParams.StackName
cmd.ui.Say(T("Using stack {{.StackName}}...",
map[string]interface{}{"StackName": terminal.EntityNameColor(stackName)}))
stack, err := cmd.stackRepo.FindByName(stackName)
if err != nil {
cmd.ui.Failed(err.Error())
return
}
cmd.ui.Ok()
appParams.StackGuid = &stack.Guid
}
func (cmd *Push) restart(app models.Application, params models.AppParams, c flags.FlagContext) {
if app.State != T("stopped") {
cmd.ui.Say("")
app, _ = cmd.appStopper.ApplicationStop(app, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name)
}
cmd.ui.Say("")
if c.Bool("no-start") {
return
}
if params.HealthCheckTimeout != nil {
cmd.appStarter.SetStartTimeoutInSeconds(*params.HealthCheckTimeout)
}
cmd.appStarter.ApplicationStart(app, cmd.config.OrganizationFields().Name, cmd.config.SpaceFields().Name)
}
func (cmd *Push) getAppParamsFromManifest(c flags.FlagContext) []models.AppParams {
if c.Bool("no-manifest") {
return []models.AppParams{}
}
var path string
if c.String("f") != "" {
path = c.String("f")
} else {
var err error
path, err = os.Getwd()
if err != nil {
cmd.ui.Failed(T("Could not determine the current working directory!"), err)
}
}
m, err := cmd.manifestRepo.ReadManifest(path)
if err != nil {
if m.Path == "" && c.String("f") == "" {
return []models.AppParams{}
}
cmd.ui.Failed(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()}))
}
apps, err := m.Applications()
if err != nil {
cmd.ui.Failed("Error reading manifest file:\n%s", err)
}
cmd.ui.Say(T("Using manifest file {{.Path}}\n",
map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)}))
return apps
}
func (cmd *Push) createAppSetFromContextAndManifest(contextApp models.AppParams, manifestApps []models.AppParams) []models.AppParams {
var err error
var apps []models.AppParams
switch len(manifestApps) {
case 0:
if contextApp.Name == nil {
cmd.ui.Failed(
T("Manifest file is not found in the current directory, please provide either an app name or manifest") +
"\n\n" +
command_registry.Commands.CommandUsage("push"),
)
} else {
err = addApp(&apps, contextApp)
}
case 1:
manifestApps[0].Merge(&contextApp)
err = addApp(&apps, manifestApps[0])
default:
selectedAppName := contextApp.Name
contextApp.Name = nil
if !contextApp.IsEmpty() {
cmd.ui.Failed("%s", T("Incorrect Usage. Command line flags (except -f) cannot be applied when pushing multiple apps from a manifest file."))
}
if selectedAppName != nil {
var foundApp bool
for _, appParams := range manifestApps {
if appParams.Name != nil && *appParams.Name == *selectedAppName {
foundApp = true
addApp(&apps, appParams)
}
}
if !foundApp {
err = errors.New(T("Could not find app named '{{.AppName}}' in manifest", map[string]interface{}{"AppName": *selectedAppName}))
}
} else {
for _, manifestApp := range manifestApps {
addApp(&apps, manifestApp)
}
}
}
if err != nil {
cmd.ui.Failed(T("Error: {{.Err}}", map[string]interface{}{"Err": err.Error()}))
}
return apps
}
func addApp(apps *[]models.AppParams, app models.AppParams) error {
if app.Name == nil {
return errors.New(T("App name is a required field"))
}
if app.Path == nil {
cwd, err := os.Getwd()
if err != nil {
return err
}
app.Path = &cwd
}
*apps = append(*apps, app)
return nil
}
func (cmd *Push) getAppParamsFromContext(c flags.FlagContext) models.AppParams {
appParams := models.AppParams{
NoRoute: c.Bool("no-route"),
UseRandomHostname: c.Bool("random-route"),
NoHostname: c.Bool("no-hostname"),
}
if len(c.Args()) > 0 {
appParams.Name = &c.Args()[0]
}
if c.String("n") != "" {
appParams.Hosts = &[]string{c.String("n")}
}
if c.String("route-path") != "" {
routePath := c.String("route-path")
appParams.RoutePath = &routePath
}
if c.String("b") != "" {
buildpack := c.String("b")
if buildpack == "null" || buildpack == "default" {
buildpack = ""
}
appParams.BuildpackUrl = &buildpack
}
if c.String("c") != "" {
command := c.String("c")
if command == "null" || command == "default" {
command = ""
}
appParams.Command = &command
}
if c.String("d") != "" {
appParams.Domains = &[]string{c.String("d")}
}
if c.IsSet("i") {
instances := c.Int("i")
if instances < 1 {
cmd.ui.Failed(T("Invalid instance count: {{.InstancesCount}}\nInstance count must be a positive integer",
map[string]interface{}{"InstancesCount": instances}))
}
appParams.InstanceCount = &instances
}
if c.String("k") != "" {
diskQuota, err := formatters.ToMegabytes(c.String("k"))
if err != nil {
cmd.ui.Failed(T("Invalid disk quota: {{.DiskQuota}}\n{{.Err}}",
map[string]interface{}{"DiskQuota": c.String("k"), "Err": err.Error()}))
}
appParams.DiskQuota = &diskQuota
}
if c.String("m") != "" {
memory, err := formatters.ToMegabytes(c.String("m"))
if err != nil {
cmd.ui.Failed(T("Invalid memory limit: {{.MemLimit}}\n{{.Err}}",
map[string]interface{}{"MemLimit": c.String("m"), "Err": err.Error()}))
}
appParams.Memory = &memory
}
if c.String("docker-image") != "" {
dockerImage := c.String("docker-image")
appParams.DockerImage = &dockerImage
}
if c.String("p") != "" {
path := c.String("p")
appParams.Path = &path
}
if c.String("s") != "" {
stackName := c.String("s")
appParams.StackName = &stackName
}
if c.String("t") != "" {
timeout, err := strconv.Atoi(c.String("t"))
if err != nil {
cmd.ui.Failed("Error: %s", fmt.Errorf(T("Invalid timeout param: {{.Timeout}}\n{{.Err}}",
map[string]interface{}{"Timeout": c.String("t"), "Err": err.Error()})))
}
appParams.HealthCheckTimeout = &timeout
}
if healthCheckType := c.String("u"); healthCheckType != "" {
if healthCheckType != "port" && healthCheckType != "none" {
cmd.ui.Failed("Error: %s", fmt.Errorf(T("Invalid health-check-type param: {{.healthCheckType}}",
map[string]interface{}{"healthCheckType": healthCheckType})))
}
appParams.HealthCheckType = &healthCheckType
}
return appParams
}
func (cmd *Push) uploadApp(appGuid, appDir, appDirOrZipFile string, localFiles []models.AppFileFields) error {
uploadDir, err := ioutil.TempDir("", "apps")
if err != nil {
return err
}
defer os.RemoveAll(uploadDir)
remoteFiles, hasFileToUpload, err := cmd.actor.GatherFiles(localFiles, appDir, uploadDir)
if err != nil {
return err
}
zipFile, err := ioutil.TempFile("", "uploads")
if err != nil {
return err
}
defer func() {
zipFile.Close()
os.Remove(zipFile.Name())
}()
if hasFileToUpload {
err = cmd.zipper.Zip(uploadDir, zipFile)
if err != nil {
if emptyDirErr, ok := err.(*errors.EmptyDirError); ok {
return emptyDirErr
}
return fmt.Errorf("%s: %s", T("Error zipping application"), err.Error())
}
zipFileSize, err := cmd.zipper.GetZipSize(zipFile)
if err != nil {
return err
}
zipFileCount := cmd.appfiles.CountFiles(uploadDir)
if zipFileCount > 0 {
cmd.ui.Say(T("Uploading app files from: {{.Path}}", map[string]interface{}{"Path": appDir}))
cmd.ui.Say(T("Uploading {{.ZipFileBytes}}, {{.FileCount}} files",
map[string]interface{}{
"ZipFileBytes": formatters.ByteSize(zipFileSize),
"FileCount": zipFileCount}))
}
}
return cmd.actor.UploadApp(appGuid, zipFile, remoteFiles)
}