-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
ddevapp.go
1547 lines (1299 loc) · 47.1 KB
/
ddevapp.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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ddevapp
import (
"fmt"
"github.com/mattn/go-isatty"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"github.com/drud/ddev/pkg/globalconfig"
"golang.org/x/crypto/ssh/terminal"
"strings"
osexec "os/exec"
"path"
"time"
"github.com/drud/ddev/pkg/appimport"
"github.com/drud/ddev/pkg/appports"
"github.com/drud/ddev/pkg/archive"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/exec"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/util"
"github.com/drud/ddev/pkg/version"
"github.com/fsouza/go-dockerclient"
"github.com/lextoumbourou/goodhosts"
"github.com/mattn/go-shellwords"
)
// containerWaitTimeout is the max time we wait for all containers to become ready.
var containerWaitTimeout = 61
// bgsyncWaitTimeout is time time in seconds to wait for the bgsync container
// to become ready. This is normally just the normal container start time + docker cp
var bgsyncWaitTimeout = 900
// bgsyncSyncWaitTimeout is the max time in seconds we wait for bgsync to be syncing.
var bgsyncSyncWaitTimeout = 600
// SiteRunning defines the string used to denote running sites.
const SiteRunning = "running"
// SiteStarting
const SiteStarting = "starting"
// SiteNotFound defines the string used to denote a site where the containers were not found/do not exist.
const SiteNotFound = "not found"
// SiteDirMissing defines the string used to denote when a site is missing its application directory.
const SiteDirMissing = "app directory missing"
// SiteConfigMissing defines the string used to denote when a site is missing its .ddev/config.yml file.
const SiteConfigMissing = ".ddev/config.yaml missing"
// SiteStopped defines the string used to denote when a site is in the stopped state.
const SiteStopped = "stopped"
// DdevFileSignature is the text we use to detect whether a settings file is managed by us.
// If this string is found, we assume we can replace/update the file.
const DdevFileSignature = "#ddev-generated"
// DdevApp is the struct that represents a ddev app, mostly its config
// from config.yaml.
type DdevApp struct {
APIVersion string `yaml:"APIVersion"`
Name string `yaml:"name"`
Type string `yaml:"type"`
Docroot string `yaml:"docroot"`
PHPVersion string `yaml:"php_version"`
WebserverType string `yaml:"webserver_type"`
WebImage string `yaml:"webimage,omitempty"`
BgsyncImage string `yaml:"bgsyncimage,omitempty"`
DBImage string `yaml:"dbimage,omitempty"`
DBAImage string `yaml:"dbaimage,omitempty"`
RouterHTTPPort string `yaml:"router_http_port"`
RouterHTTPSPort string `yaml:"router_https_port"`
XdebugEnabled bool `yaml:"xdebug_enabled"`
AdditionalHostnames []string `yaml:"additional_hostnames"`
AdditionalFQDNs []string `yaml:"additional_fqdns"`
MariaDBVersion string `yaml:"mariadb_version"`
WebcacheEnabled bool `yaml:"webcache_enabled"`
NFSMountEnabled bool `yaml:"nfs_mount_enabled"`
ConfigPath string `yaml:"-"`
AppRoot string `yaml:"-"`
Platform string `yaml:"-"`
Provider string `yaml:"provider,omitempty"`
DataDir string `yaml:"-"`
SiteSettingsPath string `yaml:"-"`
SiteLocalSettingsPath string `yaml:"-"`
providerInstance Provider `yaml:"-"`
Commands map[string][]Command `yaml:"hooks,omitempty"`
UploadDir string `yaml:"upload_dir,omitempty"`
WorkingDir map[string]string `yaml:"working_dir,omitempty"`
OmitContainers []string `yaml:"omit_containers,omitempty"`
}
// GetType returns the application type as a (lowercase) string
func (app *DdevApp) GetType() string {
return strings.ToLower(app.Type)
}
// Init populates DdevApp config based on the current working directory.
// It does not start the containers.
func (app *DdevApp) Init(basePath string) error {
newApp, err := NewApp(basePath, "")
if err != nil {
return err
}
err = newApp.ValidateConfig()
if err != nil {
return err
}
*app = *newApp
web, err := app.FindContainerByType("web")
if err != nil {
return err
}
if web != nil {
containerApproot := web.Labels["com.ddev.approot"]
isSameFile, err := fileutil.IsSameFile(containerApproot, app.AppRoot)
if err != nil {
return err
}
if !isSameFile {
return fmt.Errorf("a project (web container) in %s state already exists for %s that was created at %s", web.State, app.Name, containerApproot).(webContainerExists)
}
return nil
}
// Init() is just putting together the DdevApp struct, the containers do
// not have to exist (app doesn't have to have been started, so the fact
// we didn't find any is not an error.
return nil
}
// FindContainerByType will find a container for this site denoted by the containerType if it is available.
func (app *DdevApp) FindContainerByType(containerType string) (*docker.APIContainers, error) {
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
"com.docker.compose.service": containerType,
}
return dockerutil.FindContainerByLabels(labels)
}
// Describe returns a map which provides detailed information on services associated with the running site.
func (app *DdevApp) Describe() (map[string]interface{}, error) {
shortRoot := RenderHomeRootedDir(app.GetAppRoot())
appDesc := make(map[string]interface{})
appDesc["name"] = app.GetName()
appDesc["hostnames"] = app.GetHostnames()
appDesc["status"] = app.SiteStatus()
appDesc["sync_status"], _ = app.SyncStatus()
appDesc["type"] = app.GetType()
appDesc["approot"] = app.GetAppRoot()
appDesc["shortroot"] = shortRoot
appDesc["httpurl"] = app.GetHTTPURL()
appDesc["httpsurl"] = app.GetHTTPSURL()
appDesc["urls"] = app.GetAllURLs()
// Only show extended status for running sites.
if app.SiteStatus() == SiteRunning {
dbinfo := make(map[string]interface{})
dbinfo["username"] = "db"
dbinfo["password"] = "db"
dbinfo["dbname"] = "db"
dbinfo["host"] = "db"
dbPublicPort, err := app.GetPublishedPort("db")
util.CheckErr(err)
dbinfo["dbPort"] = appports.GetPort("db")
util.CheckErr(err)
dbinfo["published_port"] = dbPublicPort
dbinfo["mariadb_version"] = app.MariaDBVersion
appDesc["dbinfo"] = dbinfo
appDesc["mailhog_url"] = "http://" + app.GetHostname() + ":" + appports.GetPort("mailhog")
if !util.ArrayContainsString(app.OmitContainers, "dba") {
appDesc["phpmyadmin_url"] = "http://" + app.GetHostname() + ":" + appports.GetPort("dba")
}
}
routerStatus, logOutput := GetRouterStatus()
appDesc["router_status"] = routerStatus
appDesc["router_status_log"] = logOutput
appDesc["ssh_agent_status"] = GetSSHAuthStatus()
appDesc["php_version"] = app.GetPhpVersion()
appDesc["webserver_type"] = app.GetWebserverType()
appDesc["router_http_port"] = app.RouterHTTPPort
appDesc["router_https_port"] = app.RouterHTTPSPort
appDesc["xdebug_enabled"] = app.XdebugEnabled
appDesc["webimg"] = app.WebImage
appDesc["dbimg"] = app.WebImage
appDesc["bgsyncimg"] = app.BgsyncImage
appDesc["dbaimg"] = app.DBAImage
return appDesc, nil
}
// GetPublishedPort returns the host-exposed public port of a container.
func (app *DdevApp) GetPublishedPort(serviceName string) (int, error) {
dbContainer, err := app.FindContainerByType(serviceName)
if err != nil {
return -1, fmt.Errorf("Failed to find container of type %s: %v", serviceName, err)
}
privatePort, _ := strconv.ParseInt(appports.GetPort(serviceName), 10, 16)
publishedPort := dockerutil.GetPublishedPort(privatePort, *dbContainer)
return publishedPort, nil
}
// GetAppRoot return the full path from root to the app directory
func (app *DdevApp) GetAppRoot() string {
return app.AppRoot
}
// AppConfDir returns the full path to the app's .ddev configuration directory
func (app *DdevApp) AppConfDir() string {
return filepath.Join(app.AppRoot, ".ddev")
}
// GetDocroot returns the docroot path for ddev app
func (app DdevApp) GetDocroot() string {
return app.Docroot
}
// GetName returns the app's name
func (app *DdevApp) GetName() string {
return app.Name
}
// GetPhpVersion returns the app's php version
func (app *DdevApp) GetPhpVersion() string {
v := PHPDefault
if app.PHPVersion != "" {
v = app.PHPVersion
}
return v
}
// GetWebserverType returns the app's webserver type (nginx-fpm/apache-fpm/apache-cgi)
func (app *DdevApp) GetWebserverType() string {
v := WebserverDefault
if app.WebserverType != "" {
v = app.WebserverType
}
return v
}
// ImportDB takes a source sql dump and imports it to an active site's database container.
func (app *DdevApp) ImportDB(imPath string, extPath string, progress bool) error {
app.DockerEnv()
var extPathPrompt bool
dbPath, err := ioutil.TempDir(filepath.Dir(app.ConfigPath), "importdb")
//nolint: errcheck
defer os.RemoveAll(dbPath)
if err != nil {
return err
}
err = app.ProcessHooks("pre-import-db")
if err != nil {
return err
}
if imPath == "" {
// ensure we prompt for extraction path if an archive is provided, while still allowing
// non-interactive use of --src flag without providing a --extract-path flag.
if extPath == "" {
extPathPrompt = true
}
output.UserOut.Println("Provide the path to the database you wish to import.")
fmt.Print("Pull path: ")
imPath = util.GetInput("")
}
importPath, isArchive, err := appimport.ValidateAsset(imPath, "db")
if err != nil {
if isArchive && extPathPrompt {
output.UserOut.Println("You provided an archive. Do you want to extract from a specific path in your archive? You may leave this blank if you wish to use the full archive contents")
fmt.Print("Archive extraction path:")
extPath = util.GetInput("")
}
if err != nil {
return err
}
}
switch {
case strings.HasSuffix(importPath, "sql.gz") || strings.HasSuffix(importPath, "mysql.gz"):
err = archive.Ungzip(importPath, dbPath)
if err != nil {
return fmt.Errorf("failed to extract provided archive: %v", err)
}
case strings.HasSuffix(importPath, "zip"):
err = archive.Unzip(importPath, dbPath, extPath)
if err != nil {
return fmt.Errorf("failed to extract provided archive: %v", err)
}
case strings.HasSuffix(importPath, "tar"):
fallthrough
case strings.HasSuffix(importPath, "tar.gz"):
fallthrough
case strings.HasSuffix(importPath, "tgz"):
err := archive.Untar(importPath, dbPath, extPath)
if err != nil {
return fmt.Errorf("failed to extract provided archive: %v", err)
}
default:
err = fileutil.CopyFile(importPath, filepath.Join(dbPath, "db.sql"))
if err != nil {
return err
}
}
matches, err := filepath.Glob(filepath.Join(dbPath, "*.*sql"))
if err != nil {
return err
}
if len(matches) < 1 {
return fmt.Errorf("no .sql or .mysql files found to import")
}
// Inside the container, the dir for imports will be at /mnt/ddev_config/<tmpdir_name>
insideContainerImportPath := path.Join("/mnt/ddev_config", filepath.Base(dbPath))
_, _, err = app.Exec(&ExecOpts{
Service: "db",
Cmd: []string{"bash", "-c", "mysql --database=mysql -e 'DROP DATABASE IF EXISTS db; CREATE DATABASE db;' && pv " + insideContainerImportPath + "/*.*sql | mysql db"},
Tty: progress && isatty.IsTerminal(os.Stderr.Fd()),
})
if err != nil {
return err
}
_, err = app.CreateSettingsFile()
if err != nil {
util.Warning("A custom settings file exists for your application, so ddev did not generate one.")
util.Warning("Run 'ddev describe' to find the database credentials for this application.")
}
err = app.PostImportDBAction()
if err != nil {
return fmt.Errorf("failed to execute PostImportDBAction: %v", err)
}
err = fileutil.PurgeDirectory(dbPath)
if err != nil {
return fmt.Errorf("failed to clean up %s after import: %v", dbPath, err)
}
err = app.ProcessHooks("post-import-db")
if err != nil {
return err
}
return nil
}
// ExportDB exports the db, with optional output to a file, default gzip
func (app *DdevApp) ExportDB(outFile string, gzip bool) error {
app.DockerEnv()
opts := &ExecOpts{
Service: "db",
Cmd: []string{"bash", "-c", "mysqldump db"},
NoCapture: true,
}
if gzip {
opts.Cmd = []string{"bash", "-c", "mysqldump db | gzip"}
}
if outFile != "" {
f, err := os.OpenFile(outFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return fmt.Errorf("failed to open %s: %v", outFile, err)
}
opts.Stdout = f
// nolint: errcheck
defer f.Close()
}
_, _, err := app.Exec(opts)
if err != nil {
return err
}
return nil
}
// SiteStatus returns the current status of an application determined from web and db service health.
func (app *DdevApp) SiteStatus() string {
var siteStatus string
statuses := map[string]string{"web": "", "db": ""}
if app.WebcacheEnabled {
statuses["bgsync"] = ""
}
if !fileutil.FileExists(app.GetAppRoot()) {
siteStatus = fmt.Sprintf("%s: %v", SiteDirMissing, app.GetAppRoot())
return siteStatus
}
_, err := CheckForConf(app.GetAppRoot())
if err != nil {
siteStatus = fmt.Sprintf("%s", SiteConfigMissing)
return siteStatus
}
for service := range statuses {
container, err := app.FindContainerByType(service)
if err != nil {
util.Error("app.FindContainerByType(%v) failed", service)
return ""
}
if container == nil {
statuses[service] = SiteNotFound
} else {
status, _ := dockerutil.GetContainerHealth(container)
switch status {
case "exited":
statuses[service] = SiteStopped
case "healthy":
statuses[service] = SiteRunning
case "starting":
statuses[service] = SiteStarting
default:
statuses[service] = status
}
}
}
// Base the siteStatus on web container. Then override it if others are not the same.
siteStatus = statuses["web"]
for serviceName, status := range statuses {
if status != siteStatus {
siteStatus = siteStatus + "\n" + serviceName + ": " + status
}
}
return siteStatus
}
func (app *DdevApp) SyncStatus() (string, error) {
container, err := app.FindContainerByType("bgsync")
if err != nil || container == nil {
return "", err
}
_, syncStatus := dockerutil.GetContainerHealth(container)
return syncStatus, nil
}
// PullOptions allows for customization of the pull process.
type PullOptions struct {
SkipDb bool
SkipFiles bool
SkipImport bool
Environment string
}
// Pull performs an import from the a configured provider plugin, if one exists.
func (app *DdevApp) Pull(provider Provider, opts *PullOptions) error {
var err error
err = provider.Validate()
if err != nil {
return err
}
if app.SiteStatus() != SiteRunning {
util.Warning("Project is not currently running. Starting project before performing pull.")
err = app.Start()
if err != nil {
return err
}
}
if opts.SkipDb {
output.UserOut.Println("Skipping database pull.")
} else {
output.UserOut.Println("Downloading database...")
fileLocation, importPath, err := provider.GetBackup("database", opts.Environment)
if err != nil {
return err
}
output.UserOut.Printf("Database downloaded to: %s", fileLocation)
if opts.SkipImport {
output.UserOut.Println("Skipping database import.")
} else {
output.UserOut.Println("Importing database...")
err = app.ImportDB(fileLocation, importPath, true)
if err != nil {
return err
}
}
}
if opts.SkipFiles {
output.UserOut.Println("Skipping files pull.")
} else {
output.UserOut.Println("Downloading file archive...")
fileLocation, importPath, err := provider.GetBackup("files", opts.Environment)
if err != nil {
return err
}
output.UserOut.Printf("File archive downloaded to: %s", fileLocation)
if opts.SkipImport {
output.UserOut.Println("Skipping files import.")
} else {
output.UserOut.Println("Importing files...")
err = app.ImportFiles(fileLocation, importPath)
if err != nil {
return err
}
}
}
return nil
}
// ImportFiles takes a source directory or archive and copies to the uploaded files directory of a given app.
func (app *DdevApp) ImportFiles(importPath string, extPath string) error {
app.DockerEnv()
if err := app.ProcessHooks("pre-import-files"); err != nil {
return err
}
if err := app.ImportFilesAction(importPath, extPath); err != nil {
return err
}
if err := app.ProcessHooks("post-import-files"); err != nil {
return err
}
return nil
}
// ComposeFiles returns a list of compose files for a project.
// It has to put the docker-compose.y*l first
// It has to put the docker-compose.override.y*l last
func (app *DdevApp) ComposeFiles() ([]string, error) {
files, err := filepath.Glob(filepath.Join(app.AppConfDir(), "docker-compose*.y*l"))
if err != nil || len(files) == 0 {
return []string{}, fmt.Errorf("failed to load any docker-compose.*y*l files: %v", err)
}
mainfiles, err := filepath.Glob(filepath.Join(app.AppConfDir(), "docker-compose.y*l"))
// Glob doesn't return many errors, so just CheckErr()
util.CheckErr(err)
if len(mainfiles) == 0 {
return []string{}, fmt.Errorf("failed to find a docker-compose.yml or docker-compose.yaml")
}
if len(mainfiles) > 1 {
return []string{}, fmt.Errorf("there are more than one docker-compose.y*l, unable to continue")
}
overrides, err := filepath.Glob(filepath.Join(app.AppConfDir(), "docker-compose.override.y*l"))
util.CheckErr(err)
if len(overrides) > 1 {
return []string{}, fmt.Errorf("there are more than one docker-compose.override.y*l, unable to continue")
}
orderedFiles := make([]string, 1)
// Make sure the docker-compose.yaml goes first
orderedFiles[0] = mainfiles[0]
for _, file := range files {
// We already have the main docker-compose.yaml, so skip when we hit it.
// We'll add the override later, so skip it.
if file == mainfiles[0] || (len(overrides) == 1 && file == overrides[0]) {
continue
}
orderedFiles = append(orderedFiles, file)
}
if len(overrides) == 1 {
orderedFiles = append(orderedFiles, overrides[0])
}
return orderedFiles, nil
}
// ProcessHooks executes commands defined in a Command
func (app *DdevApp) ProcessHooks(hookName string) error {
if cmds := app.Commands[hookName]; len(cmds) > 0 {
output.UserOut.Printf("Executing %s commands...", hookName)
}
for _, c := range app.Commands[hookName] {
if c.Exec != "" {
output.UserOut.Printf("--- Running exec command: %s ---", c.Exec)
args, err := shellwords.Parse(c.Exec)
if err != nil {
return fmt.Errorf("%s exec failed: %v", hookName, err)
}
stdout, stderr, err := app.Exec(&ExecOpts{
Service: "web",
Cmd: args,
})
if err != nil {
return fmt.Errorf("%s exec failed: %v, stderr='%s'", hookName, err, stderr)
}
util.Success("--- %s exec command succeeded, output below ---", hookName)
output.UserOut.Println(stdout + "\n" + stderr)
}
if c.ExecHost != "" {
output.UserOut.Printf("--- Running host command: %s ---", c.ExecHost)
args := strings.Split(c.ExecHost, " ")
cmd := args[0]
args = append(args[:0], args[1:]...)
// ensure exec-host runs from consistent location
cwd, err := os.Getwd()
util.CheckErr(err)
err = os.Chdir(app.GetAppRoot())
util.CheckErr(err)
out, err := exec.RunCommandPipe(cmd, args)
dirErr := os.Chdir(cwd)
util.CheckErr(dirErr)
output.UserOut.Println(out)
if err != nil {
return fmt.Errorf("%s host command failed: %v %s", hookName, err, out)
}
util.Success("--- %s host command succeeded ---\n", hookName)
}
}
return nil
}
// Start initiates docker-compose up
func (app *DdevApp) Start() error {
var err error
app.DockerEnv()
if app.APIVersion != version.DdevVersion {
util.Warning("Your %s version is %s, but ddev is version %s. \nPlease run 'ddev config' to update your config.yaml. \nddev may not operate correctly until you do.", app.ConfigPath, app.APIVersion, version.DdevVersion)
}
// IF we need to do a DB migration to docker-volume, do it here.
// It actually does the app.Start() at the end of the migration, so we can return successfully here.
migrationDone, err := app.migrateDbIfRequired()
if err != nil {
return fmt.Errorf("Failed to migrate db from bind-mounted db: %v", err)
}
if migrationDone {
return nil
}
err = app.ProcessHooks("pre-start")
if err != nil {
return err
}
if !util.ArrayContainsString(app.OmitContainers, "ddev-ssh-agent") {
err = app.EnsureSSHAgentContainer()
if err != nil {
return err
}
}
// Warn the user if there is any custom configuration in use.
app.CheckCustomConfig()
// WriteConfig docker-compose.yaml
err = app.WriteDockerComposeConfig()
if err != nil {
return err
}
err = app.AddHostsEntries()
if err != nil {
return err
}
files, err := app.ComposeFiles()
if err != nil {
return err
}
// Delete the webcachevol and NFS volumes before we bring up docker-compose.
// We don't care if the volume wasn't there
_ = dockerutil.RemoveVolume(app.GetWebcacheVolName())
_ = dockerutil.RemoveVolume(app.GetNFSMountVolName())
_, _, err = dockerutil.ComposeCmd(files, "up", "-d")
if err != nil {
return err
}
err = StartDdevRouter()
if err != nil {
return err
}
requiredContainers := []string{"db", "web"}
if app.WebcacheEnabled {
requiredContainers = append(requiredContainers, "bgsync")
err = app.precacheWebdir()
if err != nil {
return err
}
}
err = app.Wait(requiredContainers)
if err != nil {
return err
}
err = app.PostStartAction()
if err != nil {
return err
}
// Only check for start if there are post-start commands for performance reasons
if postStartCmds := app.Commands["post-start"]; len(postStartCmds) > 0 {
stdout, _, _ := app.Exec(&ExecOpts{
Service: "web",
Cmd: []string{"bash", "-c", "if [ -f /var/tmp/ddev_started.txt ]; then echo -n 'already started'; else touch /var/tmp/ddev_started.txt && echo -n 'starting'; fi"},
})
if stdout != "already started" {
err = app.ProcessHooks("post-start")
if err != nil {
return err
}
}
}
return nil
}
// ExecOpts contains options for running a command inside a container
type ExecOpts struct {
// Service is the service, as in 'web', 'db', 'dba'
Service string
// Dir is the working directory inside the container
Dir string
// Cmd is the array of string to execute
Cmd []string
// Nocapture if true causes use of ComposeNoCapture, so the stdout and stderr go right to stdout/stderr
NoCapture bool
// Tty if true causes a tty to be allocated
Tty bool
// Stdout can be overridden with a File
Stdout *os.File
// Stderr can be overridden with a File
Stderr *os.File
}
// Exec executes a given command in the container of given type without allocating a pty
// Returns ComposeCmd results of stdout, stderr, err
// If Nocapture arg is true, stdout/stderr will be empty and output directly to stdout/stderr
func (app *DdevApp) Exec(opts *ExecOpts) (string, string, error) {
app.DockerEnv()
if opts.Service == "" {
return "", "", fmt.Errorf("no service provided")
}
exec := []string{"exec", "-e", "DDEV_EXEC=true"}
if workingDir := app.getWorkingDir(opts.Service, opts.Dir); workingDir != "" {
exec = append(exec, "-w", workingDir)
}
if !opts.Tty {
exec = append(exec, "-T")
}
exec = append(exec, opts.Service)
if opts.Cmd == nil {
return "", "", fmt.Errorf("no command provided")
}
exec = append(exec, opts.Cmd...)
files, err := app.ComposeFiles()
if err != nil {
return "", "", err
}
stdout := os.Stdout
stderr := os.Stderr
if opts.Stdout != nil {
stdout = opts.Stdout
}
if opts.Stderr != nil {
stderr = opts.Stderr
}
var stdoutResult, stderrResult string
if opts.NoCapture || opts.Tty {
err = dockerutil.ComposeWithStreams(files, os.Stdin, stdout, stderr, exec...)
} else {
stdoutResult, stderrResult, err = dockerutil.ComposeCmd(files, exec...)
}
return stdoutResult, stderrResult, err
}
// ExecWithTty executes a given command in the container of given type.
// It allocates a pty for interactive work.
func (app *DdevApp) ExecWithTty(opts *ExecOpts) error {
app.DockerEnv()
if opts.Service == "" {
return fmt.Errorf("no service provided")
}
exec := []string{"exec"}
if workingDir := app.getWorkingDir(opts.Service, opts.Dir); workingDir != "" {
exec = append(exec, "-w", workingDir)
}
exec = append(exec, opts.Service)
if opts.Cmd == nil {
return fmt.Errorf("no command provided")
}
exec = append(exec, opts.Cmd...)
files, err := app.ComposeFiles()
if err != nil {
return err
}
return dockerutil.ComposeWithStreams(files, os.Stdin, os.Stdout, os.Stderr, exec...)
}
// Logs returns logs for a site's given container.
// See docker.LogsOptions for more information about valid tailLines values.
func (app *DdevApp) Logs(service string, follow bool, timestamps bool, tailLines string) error {
client := dockerutil.GetDockerClient()
var container *docker.APIContainers
var err error
// Let people access ddev-router and ddev-ssh-agent logs as well.
if service == "ddev-router" || service == "ddev-ssh-agent" {
container, err = dockerutil.FindContainerByLabels(map[string]string{"com.docker.compose.service": service})
} else {
container, err = app.FindContainerByType(service)
}
if err != nil {
return err
}
if container == nil {
util.Warning("No running service container %s was found", service)
return nil
}
logOpts := docker.LogsOptions{
Container: container.ID,
Stdout: true,
Stderr: true,
OutputStream: output.UserOut.Out,
ErrorStream: output.UserOut.Out,
Follow: follow,
Timestamps: timestamps,
}
if tailLines != "" {
logOpts.Tail = tailLines
}
err = client.Logs(logOpts)
if err != nil {
return err
}
return nil
}
// CaptureLogs returns logs for a site's given container.
// See docker.LogsOptions for more information about valid tailLines values.
func (app *DdevApp) CaptureLogs(service string, timestamps bool, tailLines string) (string, error) {
stdout := util.CaptureUserOut()
err := app.Logs(service, false, timestamps, tailLines)
out := stdout()
return out, err
}
// DockerEnv sets environment variables for a docker-compose run.
func (app *DdevApp) DockerEnv() {
uidInt, gidInt, uidStr, gidStr := util.GetContainerUIDGid()
// Warn about running as root if we're not on windows.
if uidInt == 0 || gidInt == 0 {
util.Warning("Warning: containers will run as root. This could be a security risk on Linux.")
}
envVars := map[string]string{
"COMPOSE_PROJECT_NAME": "ddev-" + app.Name,
"COMPOSE_CONVERT_WINDOWS_PATHS": "true",
"DDEV_SITENAME": app.Name,
"DDEV_DBIMAGE": app.DBImage,
"DDEV_DBAIMAGE": app.DBAImage,
"DDEV_WEBIMAGE": app.WebImage,
"DDEV_BGSYNCIMAGE": app.BgsyncImage,
"DDEV_APPROOT": app.AppRoot,
"DDEV_DOCROOT": app.Docroot,
"DDEV_URL": app.GetHTTPURL(),
"DDEV_HOSTNAME": app.HostName(),
"DDEV_UID": uidStr,
"DDEV_GID": gidStr,
"DDEV_PHP_VERSION": app.PHPVersion,
"DDEV_WEBSERVER_TYPE": app.WebserverType,
"DDEV_PROJECT_TYPE": app.Type,
"DDEV_ROUTER_HTTP_PORT": app.RouterHTTPPort,
"DDEV_ROUTER_HTTPS_PORT": app.RouterHTTPSPort,
"DDEV_XDEBUG_ENABLED": strconv.FormatBool(app.XdebugEnabled),
}
// Set the mariadb_local command to empty to prevent docker-compose from complaining normally.
// It's used for special startup on restoring to a snapshot.
if len(os.Getenv("DDEV_MARIADB_LOCAL_COMMAND")) == 0 {
err := os.Setenv("DDEV_MARIADB_LOCAL_COMMAND", "")
util.CheckErr(err)
}
// Find out terminal dimensions
columns, lines, err := terminal.GetSize(0)
if err != nil {
columns = 80
lines = 24
}
envVars["COLUMNS"] = strconv.Itoa(columns)
envVars["LINES"] = strconv.Itoa(lines)
if len(app.AdditionalHostnames) > 0 || len(app.AdditionalFQDNs) > 0 {
envVars["DDEV_HOSTNAME"] = strings.Join(app.GetHostnames(), ",")
}
// Only set values if they don't already exist in env.
for k, v := range envVars {
if err := os.Setenv(k, v); err != nil {
util.Error("Failed to set the environment variable %s=%s: %v", k, v, err)
}
}
}
// Stop initiates docker-compose stop
func (app *DdevApp) Stop() error {
app.DockerEnv()
if app.SiteStatus() == SiteNotFound {
return fmt.Errorf("no project to stop")
}
files, err := app.ComposeFiles()
if err != nil {
return err
}
if _, _, err := dockerutil.ComposeCmd(files, "stop"); err != nil {
return err
}
return StopRouterIfNoContainers()
}
// Wait ensures that the app service containers are healthy.
func (app *DdevApp) Wait(requiredContainers []string) error {
for _, containerType := range requiredContainers {
labels := map[string]string{
"com.ddev.site-name": app.GetName(),
"com.docker.compose.service": containerType,
}
waitTime := containerWaitTimeout