/
config.go
1336 lines (1156 loc) · 47.1 KB
/
config.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 (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"time"
"github.com/Masterminds/sprig/v3"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/drud/ddev/pkg/nodeps"
"github.com/drud/ddev/pkg/versionconstants"
copy2 "github.com/otiai10/copy"
"regexp"
"runtime"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/util"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
// Regexp pattern to determine if a hostname is valid per RFC 1123.
var hostRegex = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
// init() is for testing situations only, allowing us to override the default webserver type
// or caching behavior
func init() {
// This is for automated testing only. It allows us to override the webserver type.
if testWebServerType := os.Getenv("DDEV_TEST_WEBSERVER_TYPE"); testWebServerType != "" {
nodeps.WebserverDefault = testWebServerType
}
if testNFSMount := os.Getenv("DDEV_TEST_USE_NFSMOUNT"); testNFSMount != "" {
nodeps.NFSMountEnabledDefault = true
}
if testMutagen := os.Getenv("DDEV_TEST_USE_MUTAGEN"); testMutagen == "true" {
nodeps.MutagenEnabledDefault = true
}
if os.Getenv("DDEV_TEST_NO_BIND_MOUNTS") == "true" {
nodeps.NoBindMountsDefault = true
}
if os.Getenv("DDEV_TEST_USE_TRAEFIK") == "true" {
nodeps.UseTraefikDefault = true
}
}
// NewApp creates a new DdevApp struct with defaults set and overridden by any existing config.yml.
func NewApp(appRoot string, includeOverrides bool) (*DdevApp, error) {
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("ddevapp.NewApp(%s)", appRoot))
defer runTime()
app := &DdevApp{}
if appRoot == "" {
app.AppRoot, _ = os.Getwd()
} else {
app.AppRoot = appRoot
}
homeDir, _ := os.UserHomeDir()
if appRoot == filepath.Dir(globalconfig.GetGlobalDdevDir()) || app.AppRoot == homeDir {
return nil, fmt.Errorf("ddev config is not useful in your home directory (%s)", homeDir)
}
if !fileutil.FileExists(app.AppRoot) {
return app, fmt.Errorf("project root %s does not exist", app.AppRoot)
}
app.ConfigPath = app.GetConfigPath("config.yaml")
app.Type = nodeps.AppTypePHP
app.PHPVersion = nodeps.PHPDefault
app.ComposerVersion = nodeps.ComposerDefault
app.NodeJSVersion = nodeps.NodeJSDefault
app.WebserverType = nodeps.WebserverDefault
app.NFSMountEnabled = nodeps.NFSMountEnabledDefault
app.NFSMountEnabledGlobal = globalconfig.DdevGlobalConfig.NFSMountEnabledGlobal
app.MutagenEnabled = nodeps.MutagenEnabledDefault
app.MutagenEnabledGlobal = globalconfig.DdevGlobalConfig.MutagenEnabledGlobal
app.FailOnHookFail = nodeps.FailOnHookFailDefault
app.FailOnHookFailGlobal = globalconfig.DdevGlobalConfig.FailOnHookFailGlobal
app.RouterHTTPPort = nodeps.DdevDefaultRouterHTTPPort
app.RouterHTTPSPort = nodeps.DdevDefaultRouterHTTPSPort
app.PHPMyAdminPort = nodeps.DdevDefaultPHPMyAdminPort
app.PHPMyAdminHTTPSPort = nodeps.DdevDefaultPHPMyAdminHTTPSPort
app.MailhogPort = nodeps.DdevDefaultMailhogPort
app.MailhogHTTPSPort = nodeps.DdevDefaultMailhogHTTPSPort
// Provide a default app name based on directory name
app.Name = filepath.Base(app.AppRoot)
// Gather containers to omit, adding ddev-router for gitpod
app.OmitContainersGlobal = globalconfig.DdevGlobalConfig.OmitContainersGlobal
if nodeps.IsGitpod() {
app.OmitContainersGlobal = append(app.OmitContainersGlobal, "ddev-router")
}
app.ProjectTLD = globalconfig.DdevGlobalConfig.ProjectTldGlobal
if globalconfig.DdevGlobalConfig.ProjectTldGlobal == "" {
app.ProjectTLD = nodeps.DdevDefaultTLD
}
app.UseDNSWhenPossible = true
app.WebImage = versionconstants.GetWebImage()
// Load from file if available. This will return an error if the file doesn't exist,
// and it is up to the caller to determine if that's an issue.
if _, err := os.Stat(app.ConfigPath); !os.IsNotExist(err) {
_, err = app.ReadConfig(includeOverrides)
if err != nil {
return app, fmt.Errorf("%v exists but cannot be read. It may be invalid due to a syntax error.: %v", app.ConfigPath, err)
}
}
// Upgrade any pre-v1.19.0 config that has mariadb_version or mysql_version
if app.MariaDBVersion != "" {
app.Database = DatabaseDesc{Type: nodeps.MariaDB, Version: app.MariaDBVersion}
app.MariaDBVersion = ""
}
if app.MySQLVersion != "" {
app.Database = DatabaseDesc{Type: nodeps.MySQL, Version: app.MySQLVersion}
app.MySQLVersion = ""
}
if app.Database.Type == "" {
app.Database = DatabaseDefault
}
if app.DefaultContainerTimeout == "" {
app.DefaultContainerTimeout = nodeps.DefaultDefaultContainerTimeout
}
app.SetApptypeSettingsPaths()
// Rendered yaml is not there until after ddev config or ddev start
if fileutil.FileExists(app.ConfigPath) && fileutil.FileExists(app.DockerComposeFullRenderedYAMLPath()) {
content, err := fileutil.ReadFileIntoString(app.DockerComposeFullRenderedYAMLPath())
if err != nil {
return app, err
}
err = app.UpdateComposeYaml(content)
if err != nil {
return app, err
}
}
return app, nil
}
// GetConfigPath returns the path to an application config file specified by filename.
func (app *DdevApp) GetConfigPath(filename string) string {
return filepath.Join(app.AppRoot, ".ddev", filename)
}
// WriteConfig writes the app configuration into the .ddev folder.
func (app *DdevApp) WriteConfig() error {
// Work against a copy of the DdevApp, since we don't want to actually change it.
appcopy := *app
// Only set the images on write if non-default values have been specified.
if appcopy.WebImage == versionconstants.GetWebImage() {
appcopy.WebImage = ""
}
if appcopy.MailhogPort == nodeps.DdevDefaultMailhogPort {
appcopy.MailhogPort = ""
}
if appcopy.MailhogHTTPSPort == nodeps.DdevDefaultMailhogHTTPSPort {
appcopy.MailhogHTTPSPort = ""
}
if appcopy.PHPMyAdminPort == nodeps.DdevDefaultPHPMyAdminPort {
appcopy.PHPMyAdminPort = ""
}
if appcopy.PHPMyAdminHTTPSPort == nodeps.DdevDefaultPHPMyAdminHTTPSPort {
appcopy.PHPMyAdminHTTPSPort = ""
}
if appcopy.ProjectTLD == nodeps.DdevDefaultTLD || appcopy.ProjectTLD == globalconfig.DdevGlobalConfig.ProjectTldGlobal {
appcopy.ProjectTLD = ""
}
if appcopy.DefaultContainerTimeout == nodeps.DefaultDefaultContainerTimeout {
appcopy.DefaultContainerTimeout = ""
}
// We now want to reserve the port we're writing for HostDBPort and HostWebserverPort and so they don't
// accidentally get used for other projects.
err := app.UpdateGlobalProjectList()
if err != nil {
return err
}
// Don't write default working dir values to config
defaults := appcopy.DefaultWorkingDirMap()
for service, defaultWorkingDir := range defaults {
if app.WorkingDir[service] == defaultWorkingDir {
delete(appcopy.WorkingDir, service)
}
}
err = PrepDdevDirectory(filepath.Dir(appcopy.ConfigPath))
if err != nil {
return err
}
cfgbytes, err := yaml.Marshal(appcopy)
if err != nil {
return err
}
// Append hook information and sample hook suggestions.
cfgbytes = append(cfgbytes, []byte(ConfigInstructions)...)
cfgbytes = append(cfgbytes, appcopy.GetHookDefaultComments()...)
err = os.WriteFile(appcopy.ConfigPath, cfgbytes, 0644)
if err != nil {
return err
}
// Allow project-specific post-config action
err = appcopy.PostConfigAction()
if err != nil {
return err
}
// Write example Dockerfiles into build directories
contents := []byte(`
#ddev-generated
# You can copy this Dockerfile.example to Dockerfile to add configuration
# or packages or anything else to your webimage
# These additions will be appended last to ddev's own Dockerfile
RUN npm install --global forever
RUN echo "Built on $(date)" > /build-date.txt
`)
err = WriteImageDockerfile(app.GetConfigPath("web-build")+"/Dockerfile.example", contents)
if err != nil {
return err
}
contents = []byte(`
#ddev-generated
# You can copy this Dockerfile.example to Dockerfile to add configuration
# or packages or anything else to your dbimage
RUN echo "Built on $(date)" > /build-date.txt
`)
err = WriteImageDockerfile(app.GetConfigPath("db-build")+"/Dockerfile.example", contents)
if err != nil {
return err
}
return nil
}
// UpdateGlobalProjectList updates any information about project that
// is tracked in global project list:
// - approot
// - configured host ports
// checks that configured host ports are not already
// reserved by another project
func (app *DdevApp) UpdateGlobalProjectList() error {
portsToReserve := []string{}
if app.HostDBPort != "" {
portsToReserve = append(portsToReserve, app.HostDBPort)
}
if app.HostWebserverPort != "" {
portsToReserve = append(portsToReserve, app.HostWebserverPort)
}
if app.HostHTTPSPort != "" {
portsToReserve = append(portsToReserve, app.HostHTTPSPort)
}
if len(portsToReserve) > 0 {
err := globalconfig.CheckHostPortsAvailable(app.Name, portsToReserve)
if err != nil {
return err
}
}
err := globalconfig.ReservePorts(app.Name, portsToReserve)
if err != nil {
return err
}
err = globalconfig.SetProjectAppRoot(app.Name, app.AppRoot)
if err != nil {
return err
}
return nil
}
// ReadConfig reads project configuration from the config.yaml file
// It does not attempt to set default values; that's NewApp's job.
func (app *DdevApp) ReadConfig(includeOverrides bool) ([]string, error) {
// Load base .ddev/config.yaml - original config
err := app.LoadConfigYamlFile(app.ConfigPath)
if err != nil {
return []string{}, fmt.Errorf("unable to load config file %s: %v", app.ConfigPath, err)
}
configOverrides := []string{}
// Load config.*.y*ml after in glob order
if includeOverrides {
glob := filepath.Join(filepath.Dir(app.ConfigPath), "config.*.y*ml")
configOverrides, err = filepath.Glob(glob)
if err != nil {
return []string{}, err
}
for _, item := range configOverrides {
err = app.mergeAdditionalConfigIntoApp(item)
if err != nil {
return []string{}, fmt.Errorf("unable to load config file %s: %v", item, err)
}
}
}
return append([]string{app.ConfigPath}, configOverrides...), nil
}
// LoadConfigYamlFile loads one config.yaml into app, overriding what might be there.
func (app *DdevApp) LoadConfigYamlFile(filePath string) error {
source, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("could not find an active ddev configuration at %s have you run 'ddev config'? %v", app.ConfigPath, err)
}
// validate extend command keys
err = validateHookYAML(source)
if err != nil {
return fmt.Errorf("invalid configuration in %s: %v", app.ConfigPath, err)
}
// ReadConfig config values from file.
err = yaml.Unmarshal(source, app)
if err != nil {
return err
}
return nil
}
// WarnIfConfigReplace just messages user about whether config is being replaced or created
func (app *DdevApp) WarnIfConfigReplace() {
if app.ConfigExists() {
util.Warning("You are reconfiguring the project at %s.\nThe existing configuration will be updated and replaced.", app.AppRoot)
} else {
util.Success("Creating a new ddev project config in the current directory (%s)", app.AppRoot)
util.Success("Once completed, your configuration will be written to %s\n", app.ConfigPath)
}
}
// PromptForConfig goes through a set of prompts to receive user input and generate an Config struct.
func (app *DdevApp) PromptForConfig() error {
app.WarnIfConfigReplace()
for {
err := app.promptForName()
if err == nil {
break
}
output.UserOut.Printf("%v", err)
}
if err := app.docrootPrompt(); err != nil {
return err
}
err := app.AppTypePrompt()
if err != nil {
return err
}
err = app.ConfigFileOverrideAction()
if err != nil {
return err
}
err = app.ValidateConfig()
if err != nil {
return err
}
return nil
}
// ValidateProjectName checks to see if the project name works for a proper hostname
func ValidateProjectName(name string) error {
match := hostRegex.MatchString(name)
if !match {
return fmt.Errorf("%s is not a valid project name. Please enter a project name in your configuration that will allow for a valid hostname. See https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames for valid hostname requirements", name)
}
return nil
}
// ValidateConfig ensures the configuration meets ddev's requirements.
func (app *DdevApp) ValidateConfig() error {
// validate project name
if err := ValidateProjectName(app.Name); err != nil {
return err
}
// validate hostnames
for _, hn := range app.GetHostnames() {
// If they have provided "*.<hostname>" then ignore the *. part.
hn = strings.TrimPrefix(hn, "*.")
if hn == "ddev.site" {
return fmt.Errorf("wildcarding the full hostname or using 'ddev.site' as fqdn is not allowed because other projects would not work in that case")
}
if !hostRegex.MatchString(hn) {
return fmt.Errorf("invalid hostname: %s. See https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames for valid hostname requirements", hn).(invalidHostname)
}
}
// validate apptype
if !IsValidAppType(app.Type) {
return fmt.Errorf("invalid app type: %s", app.Type).(invalidAppType)
}
// validate PHP version
if !nodeps.IsValidPHPVersion(app.PHPVersion) {
return fmt.Errorf("unsupported PHP version: %s, ddev only supports the following versions: %v", app.PHPVersion, nodeps.GetValidPHPVersions()).(invalidPHPVersion)
}
// validate webserver type
if !nodeps.IsValidWebserverType(app.WebserverType) {
return fmt.Errorf("unsupported webserver type: %s, ddev (%s) only supports the following webserver types: %s", app.WebserverType, runtime.GOARCH, nodeps.GetValidWebserverTypes()).(invalidWebserverType)
}
if !nodeps.IsValidNodeVersion(app.NodeJSVersion) {
return fmt.Errorf("unsupported system Node.js version: '%s'; for the system Node.js version ddev only supports %s. However, you can use 'ddev nvm install' at runtime to use any supported version", app.NodeJSVersion, nodeps.GetValidNodeVersions())
}
if !nodeps.IsValidOmitContainers(app.OmitContainers) {
return fmt.Errorf("unsupported omit_containers: %s, ddev (%s) only supports the following for omit_containers: %s", app.OmitContainers, runtime.GOARCH, nodeps.GetValidOmitContainers()).(InvalidOmitContainers)
}
if !nodeps.IsValidDatabaseVersion(app.Database.Type, app.Database.Version) {
return fmt.Errorf("unsupported database type/version: '%s:%s', ddev %s only supports the following database types and versions: mariadb: %v, mysql: %v, postgres: %v", app.Database.Type, app.Database.Version, runtime.GOARCH, nodeps.GetValidMariaDBVersions(), nodeps.GetValidMySQLVersions(), nodeps.GetValidPostgresVersions())
}
// This check is too intensive for app.Init() and ddevapp.GetActiveApp(), slows things down dramatically
// If the database already exists in volume and is not of this type, then throw an error
//if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
// if dbType, err := app.GetExistingDBType(); err != nil || (dbType != "" && dbType != app.Database.Type+":"+app.Database.Version) {
// return fmt.Errorf("Unable to configure project %s with database type %s because that database type does not match the current actual database. Please change your database type back to %s and start again, export, delete, and then change configuration and start. To get back to existing type use 'ddev config --database=%s', see docs at %s", app.Name, dbType, dbType, dbType, "https://ddev.readthedocs.io/en/latest/users/extend/database-types/")
// }
//}
// golang on windows is not able to time.LoadLocation unless
// go is installed... so skip validation on Windows
if runtime.GOOS != "windows" {
_, err := time.LoadLocation(app.Timezone)
if err != nil {
// golang on Windows is often not able to time.LoadLocation.
// It often works if go is installed and $GOROOT is set, but
// that's not the norm for our users.
return fmt.Errorf("invalid timezone %s: %v", app.Timezone, err)
}
}
//if app.Database.Type == nodeps.Postgres && (nodeps.ArrayContainsString([]string{"wordpress", "magento", "magento2"}, app.Type)) {
// return fmt.Errorf("project type %s does not support postgres database", app.Type)
//}
return nil
}
// DockerComposeYAMLPath returns the absolute path to where the
// base generated yaml file should exist for this project.
func (app *DdevApp) DockerComposeYAMLPath() string {
return app.GetConfigPath(".ddev-docker-compose-base.yaml")
}
// DockerComposeFullRenderedYAMLPath returns the absolute path to where the
// the complete generated yaml file should exist for this project.
func (app *DdevApp) DockerComposeFullRenderedYAMLPath() string {
return app.GetConfigPath(".ddev-docker-compose-full.yaml")
}
// GetHostname returns the primary hostname of the app.
func (app *DdevApp) GetHostname() string {
return strings.ToLower(app.Name) + "." + app.ProjectTLD
}
// GetHostnames returns a slice of all the configured hostnames.
func (app *DdevApp) GetHostnames() []string {
// Use a map to make sure that we have unique hostnames
// The value is useless, so just use the int 1 for assignment.
nameListMap := make(map[string]int)
nameListArray := []string{}
if !IsRouterDisabled(app) {
for _, name := range app.AdditionalHostnames {
name = strings.ToLower(name)
nameListMap[name+"."+app.ProjectTLD] = 1
}
for _, name := range app.AdditionalFQDNs {
name = strings.ToLower(name)
nameListMap[name] = 1
}
// Make sure the primary hostname didn't accidentally get added, it will be prepended
delete(nameListMap, app.GetHostname())
// Now walk the map and extract the keys into an array.
for k := range nameListMap {
nameListArray = append(nameListArray, k)
}
sort.Strings(nameListArray)
// We want the primary hostname to be first in the list.
nameListArray = append([]string{app.GetHostname()}, nameListArray...)
}
return nameListArray
}
// CheckCustomConfig warns the user if any custom configuration files are in use.
func (app *DdevApp) CheckCustomConfig() {
// Get the path to .ddev for the current app.
ddevDir := filepath.Dir(app.ConfigPath)
customConfig := false
if _, err := os.Stat(filepath.Join(ddevDir, "nginx-site.conf")); err == nil && app.WebserverType == nodeps.WebserverNginxFPM {
util.Warning("Using custom nginx configuration in nginx-site.conf")
customConfig = true
}
nginxFullConfigPath := app.GetConfigPath("nginx_full/nginx-site.conf")
sigFound, _ := fileutil.FgrepStringInFile(nginxFullConfigPath, nodeps.DdevFileSignature)
if !sigFound && app.WebserverType == nodeps.WebserverNginxFPM {
util.Warning("Using custom nginx configuration in %s", nginxFullConfigPath)
customConfig = true
}
apacheFullConfigPath := app.GetConfigPath("apache/apache-site.conf")
sigFound, _ = fileutil.FgrepStringInFile(apacheFullConfigPath, nodeps.DdevFileSignature)
if !sigFound && app.WebserverType != nodeps.WebserverNginxFPM {
util.Warning("Using custom apache configuration in %s", apacheFullConfigPath)
customConfig = true
}
nginxPath := filepath.Join(ddevDir, "nginx")
if _, err := os.Stat(nginxPath); err == nil {
nginxFiles, err := filepath.Glob(nginxPath + "/*.conf")
util.CheckErr(err)
if len(nginxFiles) > 0 {
util.Warning("Using nginx snippets: %v", nginxFiles)
customConfig = true
}
}
mysqlPath := filepath.Join(ddevDir, "mysql")
if _, err := os.Stat(mysqlPath); err == nil {
mysqlFiles, err := filepath.Glob(mysqlPath + "/*.cnf")
util.CheckErr(err)
if len(mysqlFiles) > 0 {
util.Warning("Using custom mysql configuration: %v", mysqlFiles)
customConfig = true
}
}
phpPath := filepath.Join(ddevDir, "php")
if _, err := os.Stat(phpPath); err == nil {
phpFiles, err := filepath.Glob(phpPath + "/*.ini")
util.CheckErr(err)
if len(phpFiles) > 0 {
util.Warning("Using custom PHP configuration: %v", phpFiles)
customConfig = true
}
}
if customConfig {
util.Warning("Custom configuration takes effect when the container is created.\nUse 'ddev restart' for force it to take effect.")
}
}
// CheckDeprecations warns the user if anything in use is deprecated.
func (app *DdevApp) CheckDeprecations() {
}
// FixObsolete removes files that may be obsolete, etc.
func (app *DdevApp) FixObsolete() {
// Remove old in-project commands (which have been moved to global)
for _, command := range []string{"db/mysql", "host/launch", "web/xdebug"} {
cmdPath := app.GetConfigPath(filepath.Join("commands", command))
signatureFound, err := fileutil.FgrepStringInFile(cmdPath, nodeps.DdevFileSignature)
if err == nil && signatureFound {
err = os.Remove(cmdPath)
if err != nil {
util.Warning("attempted to remove %s but failed, you may want to remove it manually: %v", cmdPath, err)
}
}
}
// Remove old provider/*.example as we migrate to not needing them.
for _, providerFile := range []string{"platform.yaml.example"} {
providerFilePath := app.GetConfigPath(filepath.Join("providers", providerFile))
err := os.Remove(providerFilePath)
if err == nil {
util.Success("Removed obsolete file %s", providerFilePath)
}
}
// Remove old global commands
for _, command := range []string{"host/yarn"} {
cmdPath := filepath.Join(globalconfig.GetGlobalDdevDir(), "commands/", command)
if _, err := os.Stat(cmdPath); err == nil {
err1 := os.Remove(cmdPath)
if err1 != nil {
util.Warning("attempted to remove %s but failed, you may want to remove it manually: %v", cmdPath, err)
}
}
}
}
type composeYAMLVars struct {
Name string
Plugin string
AppType string
MailhogPort string
HostMailhogPort string
DBType string
DBVersion string
DBMountDir string
DBAPort string
DBPort string
HostPHPMyAdminPort string
DdevGenerated string
HostDockerInternalIP string
NFSServerAddr string
DisableSettingsManagement bool
MountType string
WebMount string
WebBuildContext string
DBBuildContext string
WebBuildDockerfile string
DBBuildDockerfile string
SSHAgentBuildContext string
OmitDB bool
OmitDBA bool
OmitRouter bool
OmitSSHAgent bool
BindAllInterfaces bool
MariaDBVolumeName string
PostgresVolumeName string
MutagenEnabled bool
MutagenVolumeName string
NFSMountEnabled bool
NFSSource string
NFSMountVolumeName string
DockerIP string
IsWindowsFS bool
NoProjectMount bool
Hostnames []string
Timezone string
ComposerVersion string
Username string
UID string
GID string
AutoRestartContainers bool
FailOnHookFail bool
WebWorkingDir string
DBWorkingDir string
DBAWorkingDir string
WebEnvironment []string
NoBindMounts bool
Docroot string
ContainerUploadDir string
HostUploadDir string
GitDirMount bool
IsGitpod bool
DefaultContainerTimeout string
UseHostDockerInternalExtraHosts bool
WebExtraHTTPPorts string
WebExtraHTTPSPorts string
WebExtraExposedPorts string
EnvFile string
}
// RenderComposeYAML renders the contents of .ddev/.ddev-docker-compose*.
func (app *DdevApp) RenderComposeYAML() (string, error) {
var doc bytes.Buffer
var err error
hostDockerInternalIP, err := dockerutil.GetHostDockerInternalIP()
if err != nil {
util.Warning("Could not determine host.docker.internal IP address: %v", err)
}
nfsServerAddr, err := dockerutil.GetNFSServerAddr()
if err != nil {
util.Warning("Could not determine NFS server IP address: %v", err)
}
// The fallthrough default for hostDockerInternalIdentifier is the
// hostDockerInternalHostname == host.docker.internal
webEnvironment := globalconfig.DdevGlobalConfig.WebEnvironment
localWebEnvironment := app.WebEnvironment
for _, v := range localWebEnvironment {
// docker-compose won't accept a duplicate environment value
if !nodeps.ArrayContainsString(webEnvironment, v) {
webEnvironment = append(webEnvironment, v)
}
}
uid, gid, username := util.GetContainerUIDGid()
_, err = app.GetProvider("")
if err != nil {
return "", err
}
templateVars := composeYAMLVars{
Name: app.Name,
Plugin: "ddev",
AppType: app.Type,
MailhogPort: GetExposedPort(app, "mailhog"),
HostMailhogPort: app.HostMailhogPort,
DBType: app.Database.Type,
DBVersion: app.Database.Version,
DBMountDir: "/var/lib/mysql",
DBAPort: GetExposedPort(app, "dba"),
DBPort: GetExposedPort(app, "db"),
HostPHPMyAdminPort: app.HostPHPMyAdminPort,
DdevGenerated: nodeps.DdevFileSignature,
HostDockerInternalIP: hostDockerInternalIP,
NFSServerAddr: nfsServerAddr,
DisableSettingsManagement: app.DisableSettingsManagement,
OmitDB: nodeps.ArrayContainsString(app.GetOmittedContainers(), nodeps.DBContainer),
OmitDBA: nodeps.ArrayContainsString(app.GetOmittedContainers(), nodeps.DBAContainer) || nodeps.ArrayContainsString(app.OmitContainers, nodeps.DBContainer),
OmitRouter: nodeps.ArrayContainsString(app.GetOmittedContainers(), globalconfig.DdevRouterContainer),
OmitSSHAgent: nodeps.ArrayContainsString(app.GetOmittedContainers(), "ddev-ssh-agent"),
BindAllInterfaces: app.BindAllInterfaces,
MutagenEnabled: app.IsMutagenEnabled() || globalconfig.DdevGlobalConfig.NoBindMounts,
NFSMountEnabled: (app.NFSMountEnabled || app.NFSMountEnabledGlobal) && !app.IsMutagenEnabled(),
NFSSource: "",
IsWindowsFS: runtime.GOOS == "windows",
NoProjectMount: app.NoProjectMount,
MountType: "bind",
WebMount: "../",
Hostnames: app.GetHostnames(),
Timezone: app.Timezone,
ComposerVersion: app.ComposerVersion,
Username: username,
UID: uid,
GID: gid,
WebBuildContext: "./.webimageBuild",
DBBuildContext: "./.dbimageBuild",
AutoRestartContainers: globalconfig.DdevGlobalConfig.AutoRestartContainers,
FailOnHookFail: app.FailOnHookFail || app.FailOnHookFailGlobal,
WebWorkingDir: app.GetWorkingDir("web", ""),
DBWorkingDir: app.GetWorkingDir("db", ""),
DBAWorkingDir: app.GetWorkingDir("dba", ""),
WebEnvironment: webEnvironment,
MariaDBVolumeName: app.GetMariaDBVolumeName(),
PostgresVolumeName: app.GetPostgresVolumeName(),
NFSMountVolumeName: app.GetNFSMountVolumeName(),
NoBindMounts: globalconfig.DdevGlobalConfig.NoBindMounts,
Docroot: app.GetDocroot(),
HostUploadDir: app.GetHostUploadDirFullPath(),
ContainerUploadDir: app.GetContainerUploadDirFullPath(),
GitDirMount: false,
IsGitpod: nodeps.IsGitpod(),
// Default max time we wait for containers to be healthy
DefaultContainerTimeout: app.DefaultContainerTimeout,
// Only use the extra_hosts technique for linux and only if not WSL2
// If WSL2 we have to figure out other things, see GetHostDockerInternalIP()
UseHostDockerInternalExtraHosts: runtime.GOOS == "linux" || (dockerutil.IsWSL2() && globalconfig.DdevGlobalConfig.XdebugIDELocation == globalconfig.XdebugIDELocationWSL2),
}
// We don't want to bind-mount git dir if it doesn't exist
if fileutil.IsDirectory(filepath.Join(app.AppRoot, ".git")) {
templateVars.GitDirMount = true
}
envFile := app.GetConfigPath(".env")
if fileutil.FileExists(envFile) {
templateVars.EnvFile = envFile
}
// And we don't want to bind-mount upload dir if it doesn't exist.
// templateVars.UploadDir is relative path rooted in approot.
if app.GetHostUploadDirFullPath() == "" || !fileutil.FileExists(app.GetHostUploadDirFullPath()) {
templateVars.HostUploadDir = ""
templateVars.ContainerUploadDir = ""
}
webimageExtraHTTPPorts := []string{}
webimageExtraHTTPSPorts := []string{}
exposedPorts := []int{}
for _, a := range app.WebExtraExposedPorts {
webimageExtraHTTPPorts = append(webimageExtraHTTPPorts, fmt.Sprintf("%d:%d", a.HTTPPort, a.WebContainerPort))
webimageExtraHTTPSPorts = append(webimageExtraHTTPSPorts, fmt.Sprintf("%d:%d", a.HTTPSPort, a.WebContainerPort))
exposedPorts = append(exposedPorts, a.WebContainerPort)
}
if len(exposedPorts) != 0 {
templateVars.WebExtraHTTPPorts = "," + strings.Join(webimageExtraHTTPPorts, ",")
templateVars.WebExtraHTTPSPorts = "," + strings.Join(webimageExtraHTTPSPorts, ",")
templateVars.WebExtraExposedPorts = "expose:\n - "
// Odd way to join ints into a string from https://stackoverflow.com/a/37533144/215713
templateVars.WebExtraExposedPorts = templateVars.WebExtraExposedPorts + strings.Trim(strings.Join(strings.Fields(fmt.Sprint(exposedPorts)), "\n - "), "[]")
}
if app.Database.Type == nodeps.Postgres {
templateVars.DBMountDir = "/var/lib/postgresql/data"
}
if app.NFSMountEnabled || app.NFSMountEnabledGlobal {
templateVars.MountType = "volume"
templateVars.WebMount = "nfsmount"
templateVars.NFSSource = app.AppRoot
// Workaround for Catalina sharing nfs as /System/Volumes/Data
if runtime.GOOS == "darwin" && fileutil.IsDirectory(filepath.Join("/System/Volumes/Data", app.AppRoot)) {
templateVars.NFSSource = filepath.Join("/System/Volumes/Data", app.AppRoot)
}
if runtime.GOOS == "windows" {
// WinNFSD can only handle a mountpoint like /C/Users/rfay/workspace/d8git
// and completely chokes in C:\Users\rfay...
templateVars.NFSSource = dockerutil.MassageWindowsNFSMount(app.AppRoot)
}
}
if app.IsMutagenEnabled() {
templateVars.MutagenVolumeName = GetMutagenVolumeName(app)
}
// Add web and db extra dockerfile info
// If there is a user-provided Dockerfile, use that as the base and then add
// our extra stuff like usernames, etc.
// The db-build and web-build directories are used for context
// so must exist. They usually do.
for _, d := range []string{".webimageBuild", ".dbimageBuild"} {
err = os.MkdirAll(app.GetConfigPath(d), 0755)
if err != nil {
return "", err
}
// We must start with a clean base directory
err := fileutil.PurgeDirectory(app.GetConfigPath(d))
if err != nil {
util.Warning("unable to clean up directory %s, you may want to delete it manually: %v", d, err)
}
}
err = os.MkdirAll(app.GetConfigPath("db-build"), 0755)
if err != nil {
return "", err
}
err = os.MkdirAll(app.GetConfigPath("web-build"), 0755)
if err != nil {
return "", err
}
extraWebContent := "\nRUN mkdir -p /home/$username && chown $username /home/$username && chmod 600 /home/$username/.pgpass"
if app.NodeJSVersion != nodeps.NodeJSDefault {
extraWebContent = extraWebContent + "\nRUN (apt-get remove -y nodejs || true) && (apt purge nodejs || true)"
// Download of setup_*.sh seems to fail a LOT, probably a problem on their end. So try it twice
extraWebContent = extraWebContent + fmt.Sprintf("\nRUN curl -sSL --fail https://deb.nodesource.com/setup_%s.x >/tmp/setup_node.sh || curl -sSL --fail https://deb.nodesource.com/setup_%s.sh >/tmp/setup_node.sh", app.NodeJSVersion, app.NodeJSVersion)
extraWebContent = extraWebContent + "\nRUN bash /tmp/setup_node.sh && apt-get install nodejs && npm config set unsafe-perm true && npm install --global gulp-cli yarn"
}
// Add supervisord config for WebExtraDaemons
var supervisorGroup []string
for _, appStart := range app.WebExtraDaemons {
supervisorGroup = append(supervisorGroup, appStart.Name)
supervisorConf := fmt.Sprintf(`
[program:%s]
group=webextradaemons
command=bash -c "%s || sleep 2"
directory=%s
autostart=false
autorestart=true
startretries=15
stdout_logfile=/proc/self/fd/2
stdout_logfile_maxbytes=0
redirect_stderr=true
`, appStart.Name, appStart.Command, appStart.Directory)
err = os.WriteFile(app.GetConfigPath(fmt.Sprintf(".webimageBuild/%s.conf", appStart.Name)), []byte(supervisorConf), 0755)
if err != nil {
return "", fmt.Errorf("failed to write .webimageBuild/%s.conf: %v", appStart.Name, err)
}
extraWebContent = extraWebContent + fmt.Sprintf("\nADD %s.conf /etc/supervisor/conf.d\n", appStart.Name)
}
if len(supervisorGroup) > 0 {
err = os.WriteFile(app.GetConfigPath(".webimageBuild/webextradaemons.conf"), []byte("[group:webextradaemons]\nprograms="+strings.Join(supervisorGroup, ",")), 0755)
if err != nil {
return "", fmt.Errorf("failed to write .webimageBuild/webextradaemons.conf: %v", err)
}
extraWebContent = extraWebContent + "\nADD webextradaemons.conf /etc/supervisor/conf.d\n"
}
err = WriteBuildDockerfile(app.GetConfigPath(".webimageBuild/Dockerfile"), app.GetConfigPath("web-build"), app.WebImageExtraPackages, app.ComposerVersion, extraWebContent)
if err != nil {
return "", err
}
// Add .pgpass to homedir on postgres
extraDBContent := ""
if app.Database.Type == nodeps.Postgres {
// Postgres 9/10/11 upstream images are stretch-based, out of support from Debian.
// Postgres 9/10 are out of support by Postgres and no new images being pushed, see
// https://github.com/docker-library/postgres/issues/1012
// However, they do have a postgres:11-bullseye, but we won't start using it yet
// because of awkward changes to $DBIMAGE. Postgres 11 will be EOL Nov 2023
if nodeps.ArrayContainsString([]string{nodeps.Postgres9, nodeps.Postgres10, nodeps.Postgres11}, app.Database.Version) {
extraDBContent = extraDBContent + `
RUN rm -f /etc/apt/sources.list.d/pgdg.list
RUN apt-get update
RUN apt-get -y install apt-transport-https
RUN printf "deb http://apt-archive.postgresql.org/pub/repos/apt/ stretch-pgdg main" > /etc/apt/sources.list.d/pgdg.list
`
}
extraDBContent = extraDBContent + `
ENV PATH $PATH:/usr/lib/postgresql/$PG_MAJOR/bin
ADD postgres_healthcheck.sh /
RUN chmod ugo+rx /postgres_healthcheck.sh
RUN mkdir -p /etc/postgresql/conf.d && chmod 777 /etc/postgresql/conf.d
RUN echo "*:*:db:db:db" > ~postgres/.pgpass && chown postgres:postgres ~postgres/.pgpass && chmod 600 ~postgres/.pgpass && chmod 777 /var/tmp && ln -sf /mnt/ddev_config/postgres/postgresql.conf /etc/postgresql && echo "restore_command = 'true'" >> /var/lib/postgresql/recovery.conf
RUN printf "# TYPE DATABASE USER CIDR-ADDRESS METHOD \nhost all all 0.0.0.0/0 md5\nlocal all all trust\nhost replication db 0.0.0.0/0 trust\nhost replication all 0.0.0.0/0 trust\nlocal replication all trust\nlocal replication all peer\n" >/etc/postgresql/pg_hba.conf
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confold" --no-install-recommends --no-install-suggests bzip2 less procps pv vim
`
}
err = WriteBuildDockerfile(app.GetConfigPath(".dbimageBuild/Dockerfile"), app.GetConfigPath("db-build"), app.DBImageExtraPackages, "", extraDBContent)
// CopyEmbedAssets of postgres healthcheck has to be done after we WriteBuildDockerfile
// because that deletes the .dbimageBuild directory
if app.Database.Type == nodeps.Postgres {
err = fileutil.CopyEmbedAssets(bundledAssets, "healthcheck", app.GetConfigPath(".dbimageBuild"))
if err != nil {
return "", err
}
}
if err != nil {
return "", err
}
// SSH agent just needs extra to add the official related user, nothing else
err = WriteBuildDockerfile(filepath.Join(globalconfig.GetGlobalDdevDir(), ".sshimageBuild/Dockerfile"), "", nil, "", "")
if err != nil {
return "", err
}
templateVars.DockerIP, err = dockerutil.GetDockerIP()
if err != nil {
return "", err
}
if app.BindAllInterfaces {
templateVars.DockerIP = "0.0.0.0"
}
t, err := template.New("app_compose_template.yaml").Funcs(sprig.TxtFuncMap()).ParseFS(bundledAssets, "app_compose_template.yaml")
if err != nil {
return "", err
}
err = t.Execute(&doc, templateVars)
return doc.String(), err
}
// WriteBuildDockerfile writes a Dockerfile to be used in the
// docker-compose 'build'
// It may include the contents of .ddev/<container>-build
func WriteBuildDockerfile(fullpath string, userDockerfilePath string, extraPackages []string, composerVersion string, extraContent string) error {
// Start with user-built dockerfile if there is one.
err := os.MkdirAll(filepath.Dir(fullpath), 0755)
if err != nil {
return err
}
// Normal starting content is just the arg and base image
contents := `
#ddev-generated - Do not modify this file; your modifications will be overwritten.
### DDEV-injected base Dockerfile contents
ARG BASE_IMAGE
FROM $BASE_IMAGE
`
contents = contents + `
ARG username
ARG uid
ARG gid
RUN (groupadd --gid $gid "$username" || groupadd "$username" || true) && (useradd -l -m -s "/bin/bash" --gid "$username" --comment '' --uid $uid "$username" || useradd -l -m -s "/bin/bash" --gid "$username" --comment '' "$username" || useradd -l -m -s "/bin/bash" --gid "$gid" --comment '' "$username" || useradd -l -m -s "/bin/bash" --comment '' $username )
`
// If there are user pre.Dockerfile* files, insert their contents
if userDockerfilePath != "" {
files, err := filepath.Glob(userDockerfilePath + "/pre.Dockerfile*")
if err != nil {