-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
ddevapp.go
1943 lines (1665 loc) · 62.2 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 (
"bytes"
"fmt"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/drud/ddev/pkg/nodeps"
"github.com/gobuffalo/packr/v2"
"github.com/lextoumbourou/goodhosts"
"github.com/mattn/go-isatty"
"golang.org/x/crypto/ssh/terminal"
"io/ioutil"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
osexec "os/exec"
"path"
"time"
"github.com/drud/ddev/pkg/appimport"
"github.com/drud/ddev/pkg/archive"
"github.com/drud/ddev/pkg/ddevhosts"
"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"
)
// containerWaitTimeout is the max time we wait for all containers to become ready.
var containerWaitTimeout = 61
// SiteRunning defines the string used to denote running sites.
const SiteRunning = "running"
// SiteStarting
const SiteStarting = "starting"
// SiteStopped defines the string used to denote a site where the containers were not found/do not exist, but the project is there.
const SiteStopped = "stopped"
// SiteDirMissing defines the string used to denote when a site is missing its application directory.
const SiteDirMissing = "project 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"
// SitePaused defines the string used to denote when a site is in the paused (docker stopped) state.
const SitePaused = "paused"
// 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 {
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"`
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"`
NoProjectMount bool `yaml:"no_project_mount,omitempty"`
AdditionalHostnames []string `yaml:"additional_hostnames"`
AdditionalFQDNs []string `yaml:"additional_fqdns"`
MariaDBVersion string `yaml:"mariadb_version,omitempty"`
MySQLVersion string `yaml:"mysql_version,omitempty"`
NFSMountEnabled bool `yaml:"nfs_mount_enabled,omitempty"`
NFSMountEnabledGlobal bool `yaml:"-"`
ConfigPath string `yaml:"-"`
AppRoot string `yaml:"-"`
Platform string `yaml:"-"`
Provider string `yaml:"provider,omitempty"`
DataDir string `yaml:"-"`
SiteSettingsPath string `yaml:"-"`
SiteDdevSettingsFile string `yaml:"-"`
providerInstance Provider `yaml:"-"`
Hooks map[string][]YAMLTask `yaml:"hooks,omitempty"`
UploadDir string `yaml:"upload_dir,omitempty"`
WorkingDir map[string]string `yaml:"working_dir,omitempty"`
OmitContainers []string `yaml:"omit_containers,omitempty,flow"`
OmitContainerGlobal []string `yaml:"-"`
HostDBPort string `yaml:"host_db_port,omitempty"`
HostWebserverPort string `yaml:"host_webserver_port,omitempty"`
HostHTTPSPort string `yaml:"host_https_port,omitempty"`
MailhogPort string `yaml:"mailhog_port,omitempty"`
MailhogHTTPSPort string `yaml:"mailhog_https_port,omitempty"`
PHPMyAdminPort string `yaml:"phpmyadmin_port,omitempty"`
PHPMyAdminHTTPSPort string `yaml:"phpmyadmin_https_port,omitempty"`
WebImageExtraPackages []string `yaml:"webimage_extra_packages,omitempty,flow"`
DBImageExtraPackages []string `yaml:"dbimage_extra_packages,omitempty,flow"`
ProjectTLD string `yaml:"project_tld,omitempty"`
UseDNSWhenPossible bool `yaml:"use_dns_when_possible"`
MkcertEnabled bool `yaml:"-"`
NgrokArgs string `yaml:"ngrok_args,omitempty"`
Timezone string `yaml:"timezone,omitempty"`
DisableSettingsManagement bool `yaml:"disable_settings_management,omitempty"`
ComposeYaml map[string]interface{} `yaml:"-"`
}
//var ComposeYaml map[string]interface{}
// 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 {
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("app.Init(%s)", basePath))
defer runTime()
newApp, err := NewApp(basePath, true, "")
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) {
_, _, err := app.ProcessHooks("pre-describe")
if err != nil {
return nil, fmt.Errorf("Failed to process pre-describe hooks: %v", err)
}
shortRoot := RenderHomeRootedDir(app.GetAppRoot())
appDesc := make(map[string]interface{})
appDesc["name"] = app.GetName()
appDesc["hostname"] = app.GetHostname()
appDesc["hostnames"] = app.GetHostnames()
appDesc["status"] = app.SiteStatus()
appDesc["type"] = app.GetType()
appDesc["approot"] = app.GetAppRoot()
appDesc["nfs_mount_enabled"] = (app.NFSMountEnabled || app.NFSMountEnabledGlobal)
appDesc["shortroot"] = shortRoot
appDesc["primary_url"] = app.GetPrimaryURL()
appDesc["httpurl"] = app.GetHTTPURL()
appDesc["httpsurl"] = app.GetHTTPSURL()
httpURLs, httpsURLs, allURLs := app.GetAllURLs()
appDesc["httpURLs"] = httpURLs
appDesc["httpsURLs"] = httpsURLs
appDesc["urls"] = allURLs
if app.MySQLVersion != "" {
appDesc["database_type"] = "mysql"
appDesc["mysql_version"] = app.MySQLVersion
} else {
appDesc["database_type"] = "mariadb" // default
appDesc["mariadb_version"] = app.MariaDBVersion
if app.MariaDBVersion == "" {
appDesc["mariadb_version"] = version.MariaDBDefaultVersion
}
}
// Only show extended status for running sites.
if app.SiteStatus() == SiteRunning {
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
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"] = GetPort("db")
util.CheckErr(err)
dbinfo["published_port"] = dbPublicPort
dbinfo["database_type"] = "mariadb" // default
if app.MySQLVersion != "" {
dbinfo["database_type"] = "mysql"
dbinfo["mysql_version"] = app.MySQLVersion
} else {
if app.MariaDBVersion != "" {
dbinfo["mariadb_version"] = app.MariaDBVersion
} else {
dbinfo["mariadb_version"] = version.MariaDBDefaultVersion
}
}
appDesc["dbinfo"] = dbinfo
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "dba") {
appDesc["phpmyadmin_https_url"] = "https://" + app.GetHostname() + ":" + app.PHPMyAdminHTTPSPort
appDesc["phpmyadmin_url"] = "http://" + app.GetHostname() + ":" + app.PHPMyAdminPort
}
}
appDesc["mailhog_https_url"] = "https://" + app.GetHostname() + ":" + app.MailhogHTTPSPort
appDesc["mailhog_url"] = "http://" + app.GetHostname() + ":" + app.MailhogPort
}
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.GetDBImage()
appDesc["dbaimg"] = app.DBAImage
appDesc["extra_services"] = map[string]map[string]string{}
if app.ComposeYaml != nil && len(app.ComposeYaml) > 0 {
if services, ok := app.ComposeYaml["services"].(map[interface{}]interface{}); ok {
extraServices := appDesc["extra_services"].(map[string]map[string]string)
for k, v := range services {
serviceName := k.(string)
// Standard services are handled in other ways; we want custom services only
if nodeps.ArrayContainsString([]string{"web", "db", "dba"}, serviceName) {
continue
}
var svc map[interface{}]interface{}
if svc, ok = v.(map[interface{}]interface{}); !ok {
continue
}
extraServices[serviceName] = map[string]string{}
if env, ok := svc["environment"].(map[interface{}]interface{}); ok {
// Extract HTTP_EXPOSE and HTTPS_EXPOSE for additional info
for envName, envVal := range env {
if envName == "HTTP_EXPOSE" || envName == "HTTPS_EXPOSE" {
envValStr := fmt.Sprintf("%s", envVal)
portSpecs := strings.Split(envValStr, ",")
// There might be more than one exposed UI port, but this only handles the first listed,
// most often there's only one.
if len(portSpecs) > 0 {
// HTTPS portSpecs typically look like <exposed>:<containerPort>, for example - HTTPS_EXPOSE=1359:1358
ports := strings.Split(portSpecs[0], ":")
extraServices[serviceName][envName.(string)] = ports[0]
switch envName {
case "HTTP_EXPOSE":
extraServices[serviceName]["http_url"] = "http://" + appDesc["hostname"].(string) + ":" + ports[0]
case "HTTPS_EXPOSE":
extraServices[serviceName]["https_url"] = "https://" + appDesc["hostname"].(string) + ":" + ports[0]
}
}
}
}
}
// TODO: Handle volume names so they can be deleted on ddev destroy
// TODO: Show host port access, preferably exposed port. Might require docker inspect?
}
}
}
_, _, err = app.ProcessHooks("post-describe")
if err != nil {
return nil, fmt.Errorf("Failed to process post-describe hooks: %v", err)
}
return appDesc, nil
}
// GetPublishedPort returns the host-exposed public port of a container.
func (app *DdevApp) GetPublishedPort(serviceName string) (int, error) {
container, err := app.FindContainerByType(serviceName)
if err != nil || container == nil {
return -1, fmt.Errorf("Failed to find container of type %s: %v", serviceName, err)
}
privatePort, _ := strconv.ParseInt(GetPort(serviceName), 10, 16)
publishedPort := dockerutil.GetPublishedPort(privatePort, *container)
return publishedPort, nil
}
// GetOmittedContainers returns full list of global and local omitted containers
func (app *DdevApp) GetOmittedContainers() []string {
omitted := app.OmitContainerGlobal
omitted = append(omitted, app.OmitContainers...)
return omitted
}
// 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 := nodeps.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 := nodeps.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, noDrop bool, targetDB string) error {
app.DockerEnv()
if targetDB == "" {
targetDB = "db"
}
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 they don't provide an import path and we're not on a tty (piped in stuff)
// then prompt for path to db
if imPath == "" && isatty.IsTerminal(os.Stdin.Fd()) {
// 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("")
}
if imPath != "" {
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("")
}
}
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 db container, the dir for imports will be at /mnt/ddev_config/<tmpdir_name>
insideContainerImportPath := path.Join("/mnt/ddev_config", filepath.Base(dbPath))
preImportSQL := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s; GRANT ALL ON %s.* TO 'db'@'%%';", targetDB, targetDB)
if !noDrop {
preImportSQL = fmt.Sprintf("DROP DATABASE IF EXISTS %s; ", targetDB) + preImportSQL
}
// The perl manipulation removes statements like CREATE DATABASE and USE, which
// throw off imports.
inContainerCommand := fmt.Sprintf(`mysql -uroot -proot -e "%s" && pv %s/*.*sql | perl -p -e 's/^(CREATE DATABASE|USE|.*DROP DATABASE).*$//' | mysql %s`, preImportSQL, insideContainerImportPath, targetDB)
// Handle the case where we are reading from stdin
if imPath == "" && extPath == "" {
inContainerCommand = fmt.Sprintf(`mysql -uroot -proot -e "%s" && perl -p -e 's/^(CREATE DATABASE|USE|.*DROP DATABASE).*$//' | mysql %s`, preImportSQL, targetDB)
}
_, _, err = app.Exec(&ExecOpts{
Service: "db",
Cmd: inContainerCommand,
Tty: progress && isatty.IsTerminal(os.Stdin.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
// targetDB is the db name if not default "db"
func (app *DdevApp) ExportDB(outFile string, gzip bool, targetDB string) error {
app.DockerEnv()
if targetDB == "" {
targetDB = "db"
}
opts := &ExecOpts{
Service: "db",
Cmd: "mysqldump " + targetDB,
NoCapture: true,
}
if gzip {
opts.Cmd = fmt.Sprintf("mysqldump %s | gzip", targetDB)
}
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
}
confMsg := "Wrote database dump from " + app.Name + " database '" + targetDB + "'"
if outFile != "" {
confMsg = confMsg + " to file " + outFile
} else {
confMsg = confMsg + " to stdout"
}
if gzip {
confMsg = confMsg + " in gzip format"
} else {
confMsg = confMsg + " in plain text format"
}
_, err = fmt.Fprintf(os.Stderr, confMsg+".\n")
return err
}
// 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": ""}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
statuses["db"] = ""
}
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] = SiteStopped
} else {
status, _ := dockerutil.GetContainerHealth(container)
switch status {
case "exited":
statuses[service] = SitePaused
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
}
// 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 = app.ProcessHooks("pre-pull")
if err != nil {
return fmt.Errorf("Failed to process pre-pull hooks: %v", 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
}
}
err = provider.Validate()
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, false, "db")
if err != nil {
return err
}
}
}
if opts.SkipFiles {
output.UserOut.Println("Skipping files pull.")
} else {
output.UserOut.Println("Downloading files...")
fileLocation, importPath, err := provider.GetBackup("files", opts.Environment)
if err != nil {
return err
}
output.UserOut.Printf("Files 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
}
}
}
_, _, err = app.ProcessHooks("post-pull")
if err != nil {
return fmt.Errorf("Failed to process post-pull hooks: %v", 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 .ddev/docker-compose.*.y*ml first
// It has to put the docker-compose.override.y*l last
func (app *DdevApp) ComposeFiles() ([]string, error) {
dir, _ := os.Getwd()
// nolint:errcheck
defer os.Chdir(dir)
err := os.Chdir(app.AppConfDir())
if err != nil {
return nil, err
}
files, err := filepath.Glob("docker-compose.*.y*ml")
if err != nil {
return []string{}, fmt.Errorf("unable to glob docker-compose.*.y*ml in %s: err=%v", app.AppConfDir(), err)
}
mainfile := app.DockerComposeYAMLPath()
if !fileutil.FileExists(mainfile) {
return nil, fmt.Errorf("failed to find %s", mainfile)
}
overrides, err := filepath.Glob("docker-compose.override.y*ml")
util.CheckErr(err)
orderedFiles := make([]string, 1)
// Make sure the main file goes first
orderedFiles[0] = mainfile
for _, file := range files {
// We already have the main file, and it's not in the list anyway, so skip when we hit it.
// We'll add the override later, so skip it.
if len(overrides) == 1 && file == overrides[0] {
continue
}
orderedFiles = append(orderedFiles, app.GetConfigPath(file))
}
if len(overrides) == 1 {
orderedFiles = append(orderedFiles, app.GetConfigPath(overrides[0]))
}
return orderedFiles, nil
}
// ProcessHooks executes Tasks defined in Hooks
func (app *DdevApp) ProcessHooks(hookName string) (string, string, error) {
var stdout, stderr string
if cmds := app.Hooks[hookName]; len(cmds) > 0 {
output.UserOut.Printf("Executing %s hook...", hookName)
}
for _, c := range app.Hooks[hookName] {
a := NewTask(app, c)
if a == nil {
return "", "", fmt.Errorf("unable to create task from %v", c)
}
output.UserOut.Printf("=== Running task: %s, output below", a.GetDescription())
taskout, taskerr, err := a.Execute()
if taskout != "" {
output.UserOut.Println(taskout)
}
if taskerr != "" {
output.UserOut.Errorln(taskerr)
}
if err != nil {
output.UserOut.Errorf("task failed: %v: %v", a.GetDescription(), err)
output.UserOut.Warn("A task failure does not mean that ddev failed, but your hook configuration has a command that failed.")
}
stdout = stdout + taskout
stderr = stderr + taskerr
}
return stdout, stderr, nil
}
// GetDBImage uses the available mariadb or mysql version or provides the default
func (app *DdevApp) GetDBImage() string {
// If an explicit dbimage is set, just use it.
if app.DBImage != "" {
return app.DBImage
}
dbImage := ""
// If the dbimage has not been overridden (because dbimage takes precedence)
// and the mariadb_version/mysql_version *has* been changed by config,
// use the dbimage derived from dbversion.
// IF dbimage has not been specified (it equals mariadb default)
// AND mariadb version is NOT the default version
// Then override the dbimage with related mariadb or mysql version
// If no (dbimage set or it's the default image) and MariaDB or MySQL version set
if (app.DBImage == "" || app.DBImage == version.GetDBImage(nodeps.MariaDB)) && (app.MariaDBVersion != "" || app.MySQLVersion != "") {
switch {
// mariadb_version is explicitly set
case app.MariaDBVersion != "":
dbImage = version.GetDBImage(nodeps.MariaDB, app.MariaDBVersion)
// mysql_version is explicitly set
case app.MySQLVersion != "":
dbImage = version.GetDBImage(nodeps.MySQL, app.MySQLVersion)
}
}
// Default behavior is just to use the MariaDB image.
if dbImage == "" {
dbImage = version.GetDBImage(nodeps.MariaDB)
}
return dbImage
}
// Start initiates docker-compose up
func (app *DdevApp) Start() error {
var err error
app.DockerEnv()
app.DBImage = app.GetDBImage()
// Make sure that any ports allocated are available.
// and of course add to global project list as well
err = app.UpdateGlobalProjectList()
if err != nil {
return err
}
_, _, err = app.ProcessHooks("pre-start")
if err != nil {
return err
}
// We used to support nginx overrides in .ddev/nginx-site.conf
// Warn in that case
oldNginxConfig := app.GetConfigPath("nginx-site.conf")
if fileutil.FileExists(oldNginxConfig) {
util.Warning("An old nginx-site.conf exists at %s. Please move it to ~/.ddev/nginx_full", oldNginxConfig)
}
err = app.GenerateWebserverConfig()
if err != nil {
return err
}
// Pull the main images with full output, since docker-compose up won't
// show enough output.
for _, imageName := range []string{app.WebImage, app.DBImage, app.DBAImage, version.GetSSHAuthImage(), version.GetRouterImage()} {
err = dockerutil.Pull(imageName)
if err != nil {
return err
}
}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "ddev-ssh-agent") {
err = app.EnsureSSHAgentContainer()
if err != nil {
return err
}
}
// Warn the user if there is any custom configuration in use.
app.CheckCustomConfig()
// Warn user if there are deprecated items used in the config
app.CheckDeprecations()
// Copy any global homeadditions content into its mount location
globalHomeadditionsPath := filepath.Join(globalconfig.GetGlobalDdevDir(), "homeadditions")
if fileutil.IsDirectory(globalHomeadditionsPath) {
projectGlobalHomeadditionsPath := app.GetConfigPath(".homeadditions")
if fileutil.IsDirectory(projectGlobalHomeadditionsPath) {
err = os.RemoveAll(projectGlobalHomeadditionsPath)
if err != nil {
return err
}
}
err = fileutil.CopyDir(globalHomeadditionsPath, projectGlobalHomeadditionsPath)
if err != nil {
return err
}
}
caRoot := globalconfig.GetCAROOT()
if caRoot == "" {
util.Warning("mkcert may not be properly installed, we suggest installing it for trusted https support, `brew install mkcert nss`, `choco install -y mkcert`, etc. and then `mkcert -install`")
}
router, _ := FindDdevRouter()
// If the router doesn't exist, go ahead and push mkcert root ca certs into the ddev-global-cache/mkcert
// This will often be redundant
if router == nil {
// Copy ca certs into ddev-global-cache/mkcert
if caRoot != "" {
output.UserOut.Info("Pushing mkcert rootca certs to ddev-global-cache")
_, out, err := dockerutil.RunSimpleContainer("busybox:latest", "", []string{"sh", "-c", "mkdir -p /mnt/ddev-global-cache/composer && mkdir -p /mnt/ddev-global-cache/mkcert && chmod 777 /mnt/ddev-global-cache/* && cp -R /mnt/mkcert /mnt/ddev-global-cache"}, []string{}, []string{}, []string{"ddev-global-cache" + ":/mnt/ddev-global-cache", caRoot + ":/mnt/mkcert"}, "", true)
if err != nil {
util.Warning("failed to copy root CA into docker volume: %v, output='%s'", err, out)
}
util.Success("Pushed mkcert rootca certs to ddev-global-cache")
}
}
// WriteConfig .ddev-docker-compose-*.yaml
err = app.WriteDockerComposeYAML()
if err != nil {
return err
}
err = app.AddHostsEntriesIfNeeded()
if err != nil {
return err
}
// Delete the NFS volumes before we bring up docker-compose.
// We don't care if the volume wasn't there
_ = dockerutil.RemoveVolume(app.GetNFSMountVolName())
_, _, err = dockerutil.ComposeCmd([]string{app.DockerComposeFullRenderedYAMLPath()}, "up", "--build", "-d")
if err != nil {
return err
}
err = StartDdevRouter()
if err != nil {
return err
}
requiredContainers := []string{"web"}
if !nodeps.ArrayContainsString(app.GetOmittedContainers(), "db") {
requiredContainers = append(requiredContainers, "db")
}
err = app.Wait(requiredContainers)
if err != nil {
return err
}
err = app.PostStartAction()
if err != nil {
return err
}
_, _, err = app.ProcessHooks("post-start")
if err != nil {
return err
}
return nil
}
// GenerateWebserverConfig generates the default nginx and apache config files
func (app *DdevApp) GenerateWebserverConfig() error {
var items = map[string]string{
"nginx": app.GetConfigPath(filepath.Join("nginx_full", "nginx-site.conf")),
"apache": app.GetConfigPath(filepath.Join("apache", "apache-site.conf")),
"nginx_second_docroot_example": app.GetConfigPath(filepath.Join("nginx_full", "seconddocroot.conf.example")),
"README.nginx_full.txt": app.GetConfigPath(filepath.Join("nginx_full", "README.nginx_full.txt")),
"README.apache.txt": app.GetConfigPath(filepath.Join("apache", "README.apache.txt")),
"apache_second_docroot_example": app.GetConfigPath(filepath.Join("apache", "seconddocroot.conf.example")),
}
for t, configPath := range items {
err := os.MkdirAll(filepath.Dir(configPath), 0755)
if err != nil {
return err
}
if fileutil.FileExists(configPath) {
sigExists, err := fileutil.FgrepStringInFile(configPath, DdevFileSignature)
if err != nil {
return err
}
// If the signature doesn't exist, they have taken over the file, so return
if !sigExists {
return nil
}
}
box := packr.New("webserver_config_packr_assets", "./webserver_config_packr_assets")
c, err := box.Find(fmt.Sprintf("%s-site-%s.conf", t, app.Type))
if err != nil {
c, err = box.Find(fmt.Sprintf("%s-site-php.conf", t))
if err != nil {
return err
}
}
content := string(c)
docroot := path.Join("/var/www/html", app.Docroot)
err = fileutil.TemplateStringToFile(content, map[string]interface{}{"Docroot": docroot}, configPath)
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'