-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
config.go
1485 lines (1286 loc) · 52.3 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"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/Masterminds/semver/v3"
"github.com/ddev/ddev/pkg/config/types"
"github.com/ddev/ddev/pkg/docker"
"github.com/ddev/ddev/pkg/dockerutil"
"github.com/ddev/ddev/pkg/fileutil"
"github.com/ddev/ddev/pkg/globalconfig"
"github.com/ddev/ddev/pkg/nodeps"
"github.com/ddev/ddev/pkg/output"
"github.com/ddev/ddev/pkg/util"
"github.com/ddev/ddev/pkg/versionconstants"
copy2 "github.com/otiai10/copy"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
// 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])$`)
// RunValidateConfig controls whether to run ValidateConfig() function.
// In some cases we don't actually need to check the config, e.g. when deleting the project.
// It is enabled by default.
var RunValidateConfig = true
// init() is for testing situations only, allowing us to override the default webserver type
// or caching behavior
func init() {
var err error
// 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 == "true" {
nodeps.PerformanceModeDefault = types.PerformanceModeNFS
}
if testMutagen := os.Getenv("DDEV_TEST_USE_MUTAGEN"); testMutagen == "true" {
nodeps.PerformanceModeDefault = types.PerformanceModeMutagen
}
if os.Getenv("DDEV_TEST_NO_BIND_MOUNTS") == "true" {
nodeps.NoBindMountsDefault = true
}
if os.Getenv("DDEV_TEST_USE_NGINX_PROXY_ROUTER") == "true" {
nodeps.UseNginxProxyRouter = true
}
if g := os.Getenv("DDEV_TEST_GOROUTINE_LIMIT"); g != "" {
nodeps.GoroutineLimit, err = strconv.Atoi(g)
if err != nil {
util.Failed("DDEV_TEST_GOROUTINE_LIMIT must be empty or numeric value, not '%v'", g)
}
}
}
// NewApp creates a new DdevApp struct with defaults set and overridden by any existing config.yml.
func NewApp(appRoot string, includeOverrides bool) (*DdevApp, error) {
defer util.TimeTrackC(fmt.Sprintf("ddevapp.NewApp(%s)", appRoot))()
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 _, err := os.Stat(app.AppRoot); err != nil {
return app, err
}
app.ConfigPath = app.GetConfigPath("config.yaml")
app.Type = nodeps.AppTypeNone
app.PHPVersion = nodeps.PHPDefault
app.ComposerVersion = nodeps.ComposerDefault
app.NodeJSVersion = nodeps.NodeJSDefault
app.WebserverType = nodeps.WebserverDefault
app.SetPerformanceMode(nodeps.PerformanceModeDefault)
// Turn off Mutagen on Python projects until initial setup can be done
if app.WebserverType == nodeps.WebserverNginxGunicorn {
app.SetPerformanceMode(types.PerformanceModeNone)
}
app.FailOnHookFail = nodeps.FailOnHookFailDefault
app.FailOnHookFailGlobal = globalconfig.DdevGlobalConfig.FailOnHookFailGlobal
// Provide a default app name based on directory name
app.Name = filepath.Base(app.AppRoot)
// Gather containers to omit, adding ddev-router for gitpod/codespaces
app.OmitContainersGlobal = globalconfig.DdevGlobalConfig.OmitContainersGlobal
if nodeps.IsGitpod() || nodeps.IsCodespaces() {
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 = docker.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
// On Windows the default timeout may be too short for mutagen to succeed.
if runtime.GOOS == "windows" {
app.DefaultContainerTimeout = "240"
}
}
// Migrate UploadDir to UploadDirs
if app.UploadDirDeprecated != "" {
uploadDirDeprecated := app.UploadDirDeprecated
app.UploadDirDeprecated = ""
app.addUploadDir(uploadDirDeprecated)
}
// Remove dba
if nodeps.ArrayContainsString(app.OmitContainers, "dba") || nodeps.ArrayContainsString(app.OmitContainersGlobal, "dba") {
app.OmitContainers = nodeps.RemoveItemFromSlice(app.OmitContainers, "dba")
app.OmitContainersGlobal = nodeps.RemoveItemFromSlice(app.OmitContainersGlobal, "dba")
}
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
}
}
// If non-php type, use non-php webserver type
if app.WebserverType == nodeps.WebserverDefault && app.Type == nodeps.AppTypeDjango4 {
app.WebserverType = nodeps.WebserverNginxGunicorn
}
// TODO: Enable once the bootstrap is clean and every project is loaded once only
//app.TrackProject()
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 == docker.GetWebImage() {
appcopy.WebImage = ""
}
if appcopy.MailpitHTTPPort == nodeps.DdevDefaultMailpitHTTPPort {
appcopy.MailpitHTTPPort = ""
}
if appcopy.MailpitHTTPSPort == nodeps.DdevDefaultMailpitHTTPSPort {
appcopy.MailpitHTTPSPort = ""
}
if appcopy.ProjectTLD == globalconfig.DdevGlobalConfig.ProjectTldGlobal {
appcopy.ProjectTLD = ""
}
if appcopy.DefaultContainerTimeout == nodeps.DefaultDefaultContainerTimeout {
appcopy.DefaultContainerTimeout = ""
}
if appcopy.NodeJSVersion == nodeps.NodeJSDefault {
appcopy.NodeJSVersion = ""
}
// Ensure valid type
if appcopy.Type == nodeps.AppTypeNone {
appcopy.Type = nodeps.AppTypePHP
}
// 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(&appcopy)
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.
// returns the list of config files read
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
}
// Handle UploadDirs value which can take multiple types.
err = app.validateUploadDirs()
if err != nil {
return err
}
return nil
}
// WarnIfConfigReplace 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(false)
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#Syntax for valid hostname requirements", name)
}
return nil
}
// ValidateConfig ensures the configuration meets ddev's requirements.
func (app *DdevApp) ValidateConfig() error {
// Skip project validation on request.
if !RunValidateConfig {
return nil
}
// Validate ddev version constraint, if any
if app.DdevVersionConstraint != "" {
constraint := app.DdevVersionConstraint
if !strings.Contains(constraint, "-") {
// Allow pre-releases to be included in the constraint validation
// @see https://github.com/Masterminds/semver#working-with-prerelease-versions
constraint += "-0"
}
c, err := semver.NewConstraint(constraint)
if err != nil {
return fmt.Errorf("the %s project has '%s' constraint that is not valid. See https://github.com/Masterminds/semver#checking-version-constraints for valid constraints format", app.Name, app.DdevVersionConstraint).(invalidConstraint)
}
// Make sure we do this check with valid released versions
v, err := semver.NewVersion(versionconstants.DdevVersion)
if err == nil {
if !c.Check(v) {
return fmt.Errorf("the %s project has a DDEV version constraint of '%s' and the version of DDEV you are using ('%s') does not meet the constraint. Please update the `ddev_version_constraint` in your .ddev/config.yaml or use a version of DDEV that meets the constraint",
app.Name, app.DdevVersionConstraint, versionconstants.DdevVersion)
}
}
}
// Validate project name
if err := ValidateProjectName(app.Name); err != nil {
return err
}
// Skip any validation below this check if there is nothing to validate
if err := CheckForMissingProjectFiles(app); err != nil {
// Do not return an error here because not all DDEV commands should be stopped by this check
// It matters when you start a project, but not when you stop or delete it
// This check is reused elsewhere where appropriate
return nil
}
// Validate hostnames
for _, hn := range app.GetHostnames() {
// If they have provided "*.<hostname>" then ignore the *. part.
hn = strings.TrimPrefix(hn, "*.")
if hn == nodeps.DdevDefaultTLD {
return fmt.Errorf("wildcarding the full hostname\nor using 'ddev.site' as FQDN for the project %s is not allowed\nbecause other projects would not work in that case", app.Name)
}
if !hostRegex.MatchString(hn) {
return fmt.Errorf("the %s project has an invalid hostname: '%s', see https://en.wikipedia.org/wiki/Hostname#Syntax for valid hostname requirements", app.Name, hn).(invalidHostname)
}
}
// Validate apptype
if !IsValidAppType(app.Type) {
return fmt.Errorf("the %s project has an invalid app type: %s", app.Name, app.Type).(invalidAppType)
}
// Validate PHP version
if !nodeps.IsValidPHPVersion(app.PHPVersion) {
return fmt.Errorf("the %s project has an unsupported PHP version: %s, DDEV only supports the following versions: %v", app.Name, app.PHPVersion, nodeps.GetValidPHPVersions()).(invalidPHPVersion)
}
// Validate webserver type
if !nodeps.IsValidWebserverType(app.WebserverType) {
return fmt.Errorf("the %s project has an unsupported webserver type: %s, DDEV (%s) only supports the following webserver types: %s", app.Name, app.WebserverType, runtime.GOARCH, nodeps.GetValidWebserverTypes()).(invalidWebserverType)
}
if !nodeps.IsValidOmitContainers(app.OmitContainers) {
return fmt.Errorf("the %s project has an unsupported omit_containers: %s, DDEV (%s) only supports the following for omit_containers: %s", app.Name, app.OmitContainers, runtime.GOARCH, nodeps.GetValidOmitContainers()).(InvalidOmitContainers)
}
if !nodeps.IsValidDatabaseVersion(app.Database.Type, app.Database.Version) {
return fmt.Errorf("the %s project has an unsupported database type/version: '%s:%s', DDEV %s only supports the following database types and versions: mariadb: %v, mysql: %v, postgres: %v", app.Name, 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/stable/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("the %s project has an invalid timezone %s: %v", app.Name, app.Timezone, err)
}
}
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 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 {
printableFiles, _ := util.ArrayToReadableOutput(nginxFiles)
util.Warning("Using nginx snippets: %v", printableFiles)
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 {
printableFiles, _ := util.ArrayToReadableOutput(mysqlFiles)
util.Warning("Using custom MySQL configuration: %v", printableFiles)
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 {
printableFiles, _ := util.ArrayToReadableOutput(phpFiles)
util.Warning("Using custom PHP configuration: %v", printableFiles)
customConfig = true
}
}
webEntrypointPath := filepath.Join(ddevDir, "web-entrypoint.d")
if _, err := os.Stat(webEntrypointPath); err == nil {
entrypointFiles, err := filepath.Glob(webEntrypointPath + "/*.sh")
util.CheckErr(err)
if len(entrypointFiles) > 0 {
printableFiles, _ := util.ArrayToReadableOutput(entrypointFiles)
util.Warning("Using custom web-entrypoint.d configuration: %v", printableFiles)
customConfig = true
}
}
if customConfig {
util.Warning("Custom configuration is updated on restart.\nIf you don't see your custom configuration taking effect, run 'ddev restart'.")
}
}
// 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{"acquia.yaml.example", "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)
}
}
}
// Remove old router router-build Dockerfile, etc.
for _, f := range []string{"Dockerfile", "traefik_healthcheck.sh"} {
routerBuildPath := filepath.Join(globalconfig.GetGlobalDdevDir(), "router-build")
item := filepath.Join(routerBuildPath, f)
signatureFound, err := fileutil.FgrepStringInFile(item, nodeps.DdevFileSignature)
if err == nil && signatureFound {
err = os.Remove(item)
if err != nil {
util.Warning("attempted to remove %s but failed, you may want to remove it manually: %v", item, err)
}
}
}
// Remove old .global_commands directory
legacyCommandDir := app.GetConfigPath(".global_commands")
if fileutil.IsDirectory(legacyCommandDir) {
err := os.RemoveAll(legacyCommandDir)
if err != nil {
util.Warning("attempted to remove %s but failed, you may want to remove it manually: %v", legacyCommandDir, err)
}
}
}
type composeYAMLVars struct {
Name string
Plugin string
AppType string
MailpitPort string
HostMailpitPort string
DBType string
DBVersion string
DBMountDir string
DBAPort string
DBPort 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
FailOnHookFail bool
WebWorkingDir string
DBWorkingDir string
DBAWorkingDir string
WebEnvironment []string
NoBindMounts bool
Docroot string
UploadDirsMap []string
GitDirMount bool
IsGitpod bool
IsCodespaces 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,
MailpitPort: GetExposedPort(app, "mailpit"),
HostMailpitPort: app.HostMailpitPort,
DBType: app.Database.Type,
DBVersion: app.Database.Version,
DBMountDir: "/var/lib/mysql",
DBPort: GetExposedPort(app, "db"),
DdevGenerated: nodeps.DdevFileSignature,
HostDockerInternalIP: hostDockerInternalIP,
NFSServerAddr: nfsServerAddr,
DisableSettingsManagement: app.DisableSettingsManagement,
OmitDB: nodeps.ArrayContainsString(app.GetOmittedContainers(), nodeps.DBContainer),
OmitRouter: nodeps.ArrayContainsString(app.GetOmittedContainers(), globalconfig.DdevRouterContainer),
OmitSSHAgent: nodeps.ArrayContainsString(app.GetOmittedContainers(), "ddev-ssh-agent"),
BindAllInterfaces: app.BindAllInterfaces,
MutagenEnabled: app.IsMutagenEnabled(),
NFSMountEnabled: app.IsNFSMountEnabled(),
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",
FailOnHookFail: app.FailOnHookFail || app.FailOnHookFailGlobal,
WebWorkingDir: app.GetWorkingDir("web", ""),
DBWorkingDir: app.GetWorkingDir("db", ""),
WebEnvironment: webEnvironment,
MariaDBVolumeName: app.GetMariaDBVolumeName(),
PostgresVolumeName: app.GetPostgresVolumeName(),
NFSMountVolumeName: app.GetNFSMountVolumeName(),
NoBindMounts: globalconfig.DdevGlobalConfig.NoBindMounts,
Docroot: app.GetDocroot(),
UploadDirsMap: app.getUploadDirsHostContainerMapping(),
GitDirMount: false,
IsGitpod: nodeps.IsGitpod(),
IsCodespaces: nodeps.IsCodespaces(),
// 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 and not Colima
// If WSL2 we have to figure out other things, see GetHostDockerInternalIP()
UseHostDockerInternalExtraHosts: (runtime.GOOS == "linux" && !nodeps.IsWSL2() && !dockerutil.IsColima()) || (nodeps.IsWSL2() && globalconfig.DdevGlobalConfig.XdebugIDELocation == globalconfig.XdebugIDELocationWSL2),
}
// We don't want to bind-mount Git directory 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
}
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.IsNFSMountEnabled() {
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"
extraWebContent = extraWebContent + "\nENV NVM_DIR=/home/$username/.nvm"
if app.NodeJSVersion != nodeps.NodeJSDefault {
extraWebContent = extraWebContent + "\nRUN npm install -g n"
extraWebContent = extraWebContent + fmt.Sprintf("\nRUN n install %s && ln -sf /usr/local/bin/node /usr/local/bin/nodejs", app.NodeJSVersion)
}
if app.CorepackEnable {
extraWebContent = extraWebContent + "\nRUN corepack enable"
}
if app.Type == nodeps.AppTypeDrupal {
// TODO: When ddev-webserver has required drupal 11+ sqlite version we can remove this.
// These packages must be retrieved from snapshot.debian.org. We hope they'll be there
// when we need them.
drupalVersion, err := GetDrupalVersion(app)
if err == nil && drupalVersion == "11" {
extraWebContent = extraWebContent + "\n" + fmt.Sprintf(`
### Drupal 11+ requires a minimum sqlite3 version (3.45 currently)
ARG TARGETPLATFORM
ENV SQLITE_VERSION=%s
RUN mkdir -p /tmp/sqlite3 && \
wget -O /tmp/sqlite3/sqlite3.deb https://snapshot.debian.org/archive/debian/20240203T152533Z/pool/main/s/sqlite3/sqlite3_${SQLITE_VERSION}-1_${TARGETPLATFORM##linux/}.deb && \
wget -O /tmp/sqlite3/libsqlite3.deb https://snapshot.debian.org/archive/debian/20240203T152533Z/pool/main/s/sqlite3/libsqlite3-0_${SQLITE_VERSION}-1_${TARGETPLATFORM##linux/}.deb && \
apt-get install -y /tmp/sqlite3/*.deb && \
rm -rf /tmp/sqlite3
`, versionconstants.Drupal11RequiredSqlite3Version)
}
}
// 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; exit_code=$?; if [ $exit_code -ne 0 ]; then sleep 2; fi; exit $exit_code"
directory=%s
autostart=false
autorestart=true
startsecs=3 # Must stay up 3 sec, because "sleep 2" in case of fail
startretries=15
stdout_logfile=/var/tmp/logpipe