File: create.go

package info (click to toggle)
docker-compose 2.32.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,300 kB
  • sloc: makefile: 113; sh: 2
file content (1548 lines) | stat: -rw-r--r-- 47,013 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
/*
   Copyright 2020 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package compose

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"

	"github.com/compose-spec/compose-go/v2/types"
	"github.com/docker/compose/v2/internal/desktop"
	pathutil "github.com/docker/compose/v2/internal/paths"
	"github.com/docker/compose/v2/pkg/api"
	"github.com/docker/compose/v2/pkg/progress"
	"github.com/docker/compose/v2/pkg/prompt"
	"github.com/docker/compose/v2/pkg/utils"
	moby "github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/blkiodev"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/mount"
	"github.com/docker/docker/api/types/network"
	"github.com/docker/docker/api/types/strslice"
	"github.com/docker/docker/api/types/versions"
	volumetypes "github.com/docker/docker/api/types/volume"
	"github.com/docker/docker/errdefs"
	"github.com/docker/go-connections/nat"
	"github.com/sirupsen/logrus"
	cdi "tags.cncf.io/container-device-interface/pkg/parser"
)

type createOptions struct {
	AutoRemove        bool
	AttachStdin       bool
	UseNetworkAliases bool
	Labels            types.Labels
}

type createConfigs struct {
	Container *container.Config
	Host      *container.HostConfig
	Network   *network.NetworkingConfig
	Links     []string
}

func (s *composeService) Create(ctx context.Context, project *types.Project, createOpts api.CreateOptions) error {
	return progress.RunWithTitle(ctx, func(ctx context.Context) error {
		return s.create(ctx, project, createOpts)
	}, s.stdinfo(), "Creating")
}

func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
	if len(options.Services) == 0 {
		options.Services = project.ServiceNames()
	}

	err := project.CheckContainerNameUnicity()
	if err != nil {
		return err
	}

	err = s.ensureImagesExists(ctx, project, options.Build, options.QuietPull)
	if err != nil {
		return err
	}

	prepareNetworks(project)

	networks, err := s.ensureNetworks(ctx, project)
	if err != nil {
		return err
	}

	volumes, err := s.ensureProjectVolumes(ctx, project, options.AssumeYes)
	if err != nil {
		return err
	}

	var observedState Containers
	observedState, err = s.getContainers(ctx, project.Name, oneOffInclude, true)
	if err != nil {
		return err
	}
	orphans := observedState.filter(isOrphaned(project))
	if len(orphans) > 0 && !options.IgnoreOrphans {
		if options.RemoveOrphans {
			err := s.removeContainers(ctx, orphans, nil, nil, false)
			if err != nil {
				return err
			}
		} else {
			logrus.Warnf("Found orphan containers (%s) for this project. If "+
				"you removed or renamed this service in your compose "+
				"file, you can run this command with the "+
				"--remove-orphans flag to clean it up.", orphans.names())
		}
	}
	return newConvergence(options.Services, observedState, networks, volumes, s).apply(ctx, project, options)
}

func prepareNetworks(project *types.Project) {
	for k, nw := range project.Networks {
		nw.CustomLabels = nw.CustomLabels.
			Add(api.NetworkLabel, k).
			Add(api.ProjectLabel, project.Name).
			Add(api.VersionLabel, api.ComposeVersion)
		project.Networks[k] = nw
	}
}

func (s *composeService) ensureNetworks(ctx context.Context, project *types.Project) (map[string]string, error) {
	networks := map[string]string{}
	for name, nw := range project.Networks {
		id, err := s.ensureNetwork(ctx, project, name, &nw)
		if err != nil {
			return nil, err
		}
		networks[name] = id
		project.Networks[name] = nw
	}
	return networks, nil
}

func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project, assumeYes bool) (map[string]string, error) {
	ids := map[string]string{}
	for k, volume := range project.Volumes {
		volume.CustomLabels = volume.CustomLabels.Add(api.VolumeLabel, k)
		volume.CustomLabels = volume.CustomLabels.Add(api.ProjectLabel, project.Name)
		volume.CustomLabels = volume.CustomLabels.Add(api.VersionLabel, api.ComposeVersion)
		id, err := s.ensureVolume(ctx, k, volume, project, assumeYes)
		if err != nil {
			return nil, err
		}
		ids[k] = id
	}

	err := func() error {
		if s.manageDesktopFileSharesEnabled(ctx) {
			// collect all the bind mount paths and try to set up file shares in
			// Docker Desktop for them
			var paths []string
			for _, svcName := range project.ServiceNames() {
				svc := project.Services[svcName]
				for _, vol := range svc.Volumes {
					if vol.Type != string(mount.TypeBind) {
						continue
					}
					p := filepath.Clean(vol.Source)
					if !filepath.IsAbs(p) {
						return fmt.Errorf("file share path is not absolute: %s", p)
					}
					if fi, err := os.Stat(p); errors.Is(err, fs.ErrNotExist) {
						// actual directory will be implicitly created when the
						// file share is initialized if it doesn't exist, so
						// need to filter out any that should not be auto-created
						if vol.Bind != nil && !vol.Bind.CreateHostPath {
							logrus.Debugf("Skipping creating file share for %q: does not exist and `create_host_path` is false", p)
							continue
						}
					} else if err != nil {
						// if we can't read the path, we won't be able to make
						// a file share for it
						logrus.Debugf("Skipping creating file share for %q: %v", p, err)
						continue
					} else if !fi.IsDir() {
						// ignore files & special types (e.g. Unix sockets)
						logrus.Debugf("Skipping creating file share for %q: not a directory", p)
						continue
					}

					paths = append(paths, p)
				}
			}

			// remove duplicate/unnecessary child paths and sort them for predictability
			paths = pathutil.EncompassingPaths(paths)
			sort.Strings(paths)

			fileShareManager := desktop.NewFileShareManager(s.desktopCli, project.Name, paths)
			if err := fileShareManager.EnsureExists(ctx); err != nil {
				return fmt.Errorf("initializing file shares: %w", err)
			}
		}
		return nil
	}()
	if err != nil {
		progress.ContextWriter(ctx).TailMsgf("Failed to prepare Synchronized file shares: %v", err)
	}
	return ids, nil
}

func (s *composeService) getCreateConfigs(ctx context.Context,
	p *types.Project,
	service types.ServiceConfig,
	number int,
	inherit *moby.Container,
	opts createOptions,
) (createConfigs, error) {
	labels, err := s.prepareLabels(opts.Labels, service, number)
	if err != nil {
		return createConfigs{}, err
	}

	var (
		runCmd     strslice.StrSlice
		entrypoint strslice.StrSlice
	)
	if service.Command != nil {
		runCmd = strslice.StrSlice(service.Command)
	}
	if service.Entrypoint != nil {
		entrypoint = strslice.StrSlice(service.Entrypoint)
	}

	var (
		tty       = service.Tty
		stdinOpen = service.StdinOpen
	)

	proxyConfig := types.MappingWithEquals(s.configFile().ParseProxyConfig(s.apiClient().DaemonHost(), nil))
	env := proxyConfig.OverrideBy(service.Environment)

	var mainNwName string
	var mainNw *types.ServiceNetworkConfig
	if len(service.Networks) > 0 {
		mainNwName = service.NetworksByPriority()[0]
		mainNw = service.Networks[mainNwName]
	}

	macAddress, err := s.prepareContainerMACAddress(ctx, service, mainNw, mainNwName)
	if err != nil {
		return createConfigs{}, err
	}

	healthcheck, err := s.ToMobyHealthCheck(ctx, service.HealthCheck)
	if err != nil {
		return createConfigs{}, err
	}
	containerConfig := container.Config{
		Hostname:        service.Hostname,
		Domainname:      service.DomainName,
		User:            service.User,
		ExposedPorts:    buildContainerPorts(service),
		Tty:             tty,
		OpenStdin:       stdinOpen,
		StdinOnce:       opts.AttachStdin && stdinOpen,
		AttachStdin:     opts.AttachStdin,
		AttachStderr:    true,
		AttachStdout:    true,
		Cmd:             runCmd,
		Image:           api.GetImageNameOrDefault(service, p.Name),
		WorkingDir:      service.WorkingDir,
		Entrypoint:      entrypoint,
		NetworkDisabled: service.NetworkMode == "disabled",
		MacAddress:      macAddress,
		Labels:          labels,
		StopSignal:      service.StopSignal,
		Env:             ToMobyEnv(env),
		Healthcheck:     healthcheck,
		StopTimeout:     ToSeconds(service.StopGracePeriod),
	} // VOLUMES/MOUNTS/FILESYSTEMS
	tmpfs := map[string]string{}
	for _, t := range service.Tmpfs {
		if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
			tmpfs[arr[0]] = arr[1]
		} else {
			tmpfs[arr[0]] = ""
		}
	}
	binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit)
	if err != nil {
		return createConfigs{}, err
	}

	// NETWORKING
	links, err := s.getLinks(ctx, p.Name, service, number)
	if err != nil {
		return createConfigs{}, err
	}
	apiVersion, err := s.RuntimeVersion(ctx)
	if err != nil {
		return createConfigs{}, err
	}
	networkMode, networkingConfig := defaultNetworkSettings(p, service, number, links, opts.UseNetworkAliases, apiVersion)
	portBindings := buildContainerPortBindingOptions(service)

	// MISC
	resources := getDeployResources(service)
	var logConfig container.LogConfig
	if service.Logging != nil {
		logConfig = container.LogConfig{
			Type:   service.Logging.Driver,
			Config: service.Logging.Options,
		}
	}
	securityOpts, unconfined, err := parseSecurityOpts(p, service.SecurityOpt)
	if err != nil {
		return createConfigs{}, err
	}

	hostConfig := container.HostConfig{
		AutoRemove:     opts.AutoRemove,
		Annotations:    service.Annotations,
		Binds:          binds,
		Mounts:         mounts,
		CapAdd:         strslice.StrSlice(service.CapAdd),
		CapDrop:        strslice.StrSlice(service.CapDrop),
		NetworkMode:    networkMode,
		Init:           service.Init,
		IpcMode:        container.IpcMode(service.Ipc),
		CgroupnsMode:   container.CgroupnsMode(service.Cgroup),
		ReadonlyRootfs: service.ReadOnly,
		RestartPolicy:  getRestartPolicy(service),
		ShmSize:        int64(service.ShmSize),
		Sysctls:        service.Sysctls,
		PortBindings:   portBindings,
		Resources:      resources,
		VolumeDriver:   service.VolumeDriver,
		VolumesFrom:    service.VolumesFrom,
		DNS:            service.DNS,
		DNSSearch:      service.DNSSearch,
		DNSOptions:     service.DNSOpts,
		ExtraHosts:     service.ExtraHosts.AsList(":"),
		SecurityOpt:    securityOpts,
		StorageOpt:     service.StorageOpt,
		UsernsMode:     container.UsernsMode(service.UserNSMode),
		UTSMode:        container.UTSMode(service.Uts),
		Privileged:     service.Privileged,
		PidMode:        container.PidMode(service.Pid),
		Tmpfs:          tmpfs,
		Isolation:      container.Isolation(service.Isolation),
		Runtime:        service.Runtime,
		LogConfig:      logConfig,
		GroupAdd:       service.GroupAdd,
		Links:          links,
		OomScoreAdj:    int(service.OomScoreAdj),
	}

	if unconfined {
		hostConfig.MaskedPaths = []string{}
		hostConfig.ReadonlyPaths = []string{}
	}

	cfgs := createConfigs{
		Container: &containerConfig,
		Host:      &hostConfig,
		Network:   networkingConfig,
		Links:     links,
	}
	return cfgs, nil
}

// prepareContainerMACAddress handles the service-level mac_address field and the newer mac_address field added to service
// network config. This newer field is only compatible with the Engine API v1.44 (and onwards), and this API version
// also deprecates the container-wide mac_address field. Thus, this method will validate service config and mutate the
// passed mainNw to provide backward-compatibility whenever possible.
//
// It returns the container-wide MAC address, but this value will be kept empty for newer API versions.
func (s *composeService) prepareContainerMACAddress(ctx context.Context, service types.ServiceConfig, mainNw *types.ServiceNetworkConfig, nwName string) (string, error) {
	version, err := s.RuntimeVersion(ctx)
	if err != nil {
		return "", err
	}

	// Engine API 1.44 added support for endpoint-specific MAC address and now returns a warning when a MAC address is
	// set in container.Config. Thus, we have to jump through a number of hoops:
	//
	// 1. Top-level mac_address and main endpoint's MAC address should be the same ;
	// 2. If supported by the API, top-level mac_address should be migrated to the main endpoint and container.Config
	//    should be kept empty ;
	// 3. Otherwise, the endpoint mac_address should be set in container.Config and no other endpoint-specific
	//    mac_address can be specified. If that's the case, use top-level mac_address ;
	//
	// After that, if an endpoint mac_address is set, it's either user-defined or migrated by the code below, so
	// there's no need to check for API version in defaultNetworkSettings.
	macAddress := service.MacAddress
	if macAddress != "" && mainNw != nil && mainNw.MacAddress != "" && mainNw.MacAddress != macAddress {
		return "", fmt.Errorf("the service-level mac_address should have the same value as network %s", nwName)
	}
	if versions.GreaterThanOrEqualTo(version, "1.44") {
		if mainNw != nil && mainNw.MacAddress == "" {
			mainNw.MacAddress = macAddress
		}
		macAddress = ""
	} else if len(service.Networks) > 0 {
		var withMacAddress []string
		for nwName, nw := range service.Networks {
			if nw != nil && nw.MacAddress != "" {
				withMacAddress = append(withMacAddress, nwName)
			}
		}

		if len(withMacAddress) > 1 {
			return "", fmt.Errorf("a MAC address is specified for multiple networks (%s), but this feature requires Docker Engine 1.44 or later (currently: %s)", strings.Join(withMacAddress, ", "), version)
		}

		if mainNw != nil && mainNw.MacAddress != "" {
			macAddress = mainNw.MacAddress
		}
	}

	return macAddress, nil
}

func getAliases(project *types.Project, service types.ServiceConfig, serviceIndex int, cfg *types.ServiceNetworkConfig, useNetworkAliases bool) []string {
	aliases := []string{getContainerName(project.Name, service, serviceIndex)}
	if useNetworkAliases {
		aliases = append(aliases, service.Name)
		if cfg != nil {
			aliases = append(aliases, cfg.Aliases...)
		}
	}
	return aliases
}

func createEndpointSettings(p *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, links []string, useNetworkAliases bool) *network.EndpointSettings {
	config := service.Networks[networkKey]
	var ipam *network.EndpointIPAMConfig
	var (
		ipv4Address string
		ipv6Address string
		macAddress  string
		driverOpts  types.Options
	)
	if config != nil {
		ipv4Address = config.Ipv4Address
		ipv6Address = config.Ipv6Address
		ipam = &network.EndpointIPAMConfig{
			IPv4Address:  ipv4Address,
			IPv6Address:  ipv6Address,
			LinkLocalIPs: config.LinkLocalIPs,
		}
		macAddress = config.MacAddress
		driverOpts = config.DriverOpts
	}
	return &network.EndpointSettings{
		Aliases:     getAliases(p, service, serviceIndex, config, useNetworkAliases),
		Links:       links,
		IPAddress:   ipv4Address,
		IPv6Gateway: ipv6Address,
		IPAMConfig:  ipam,
		MacAddress:  macAddress,
		DriverOpts:  driverOpts,
	}
}

// copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
// TODO find so way to share this code with docker/cli
func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) {
	var (
		unconfined bool
		parsed     []string
	)
	for _, opt := range securityOpts {
		if opt == "systempaths=unconfined" {
			unconfined = true
			continue
		}
		con := strings.SplitN(opt, "=", 2)
		if len(con) == 1 && con[0] != "no-new-privileges" {
			if strings.Contains(opt, ":") {
				con = strings.SplitN(opt, ":", 2)
			} else {
				return securityOpts, false, fmt.Errorf("Invalid security-opt: %q", opt)
			}
		}
		if con[0] == "seccomp" && con[1] != "unconfined" {
			f, err := os.ReadFile(p.RelativePath(con[1]))
			if err != nil {
				return securityOpts, false, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err)
			}
			b := bytes.NewBuffer(nil)
			if err := json.Compact(b, f); err != nil {
				return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", con[1], err)
			}
			parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes()))
		} else {
			parsed = append(parsed, opt)
		}
	}

	return parsed, unconfined, nil
}

func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) {
	hash, err := ServiceHash(service)
	if err != nil {
		return nil, err
	}
	labels[api.ConfigHashLabel] = hash

	if number > 0 {
		// One-off containers are not indexed
		labels[api.ContainerNumberLabel] = strconv.Itoa(number)
	}

	var dependencies []string
	for s, d := range service.DependsOn {
		dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart))
	}
	labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
	return labels, nil
}

// defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable).
func defaultNetworkSettings(
	project *types.Project,
	service types.ServiceConfig,
	serviceIndex int,
	links []string,
	useNetworkAliases bool,
	version string,
) (container.NetworkMode, *network.NetworkingConfig) {
	if service.NetworkMode != "" {
		return container.NetworkMode(service.NetworkMode), nil
	}

	if len(project.Networks) == 0 {
		return "none", nil
	}

	var primaryNetworkKey string
	if len(service.Networks) > 0 {
		primaryNetworkKey = service.NetworksByPriority()[0]
	} else {
		primaryNetworkKey = "default"
	}
	primaryNetworkMobyNetworkName := project.Networks[primaryNetworkKey].Name
	primaryNetworkEndpoint := createEndpointSettings(project, service, serviceIndex, primaryNetworkKey, links, useNetworkAliases)
	endpointsConfig := map[string]*network.EndpointSettings{}

	// Starting from API version 1.44, the Engine will take several EndpointsConfigs
	// so we can pass all the extra networks we want the container to be connected to
	// in the network configuration instead of connecting the container to each extra
	// network individually after creation.
	if versions.GreaterThanOrEqualTo(version, "1.44") {
		if len(service.Networks) > 1 {
			serviceNetworks := service.NetworksByPriority()
			for _, networkKey := range serviceNetworks[1:] {
				mobyNetworkName := project.Networks[networkKey].Name
				epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases)
				endpointsConfig[mobyNetworkName] = epSettings
			}
		}
		if primaryNetworkEndpoint.MacAddress == "" {
			primaryNetworkEndpoint.MacAddress = service.MacAddress
		}
	}

	endpointsConfig[primaryNetworkMobyNetworkName] = primaryNetworkEndpoint
	networkConfig := &network.NetworkingConfig{
		EndpointsConfig: endpointsConfig,
	}

	// From the Engine API docs:
	// > Supported standard values are: bridge, host, none, and container:<name|id>.
	// > Any other value is taken as a custom network's name to which this container should connect to.
	return container.NetworkMode(primaryNetworkMobyNetworkName), networkConfig
}

func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
	var restart container.RestartPolicy
	if service.Restart != "" {
		split := strings.Split(service.Restart, ":")
		var attempts int
		if len(split) > 1 {
			attempts, _ = strconv.Atoi(split[1])
		}
		restart = container.RestartPolicy{
			Name:              mapRestartPolicyCondition(split[0]),
			MaximumRetryCount: attempts,
		}
	}
	if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
		policy := *service.Deploy.RestartPolicy
		var attempts int
		if policy.MaxAttempts != nil {
			attempts = int(*policy.MaxAttempts)
		}
		restart = container.RestartPolicy{
			Name:              mapRestartPolicyCondition(policy.Condition),
			MaximumRetryCount: attempts,
		}
	}
	return restart
}

func mapRestartPolicyCondition(condition string) container.RestartPolicyMode {
	// map definitions of deploy.restart_policy to engine definitions
	switch condition {
	case "none", "no":
		return container.RestartPolicyDisabled
	case "on-failure":
		return container.RestartPolicyOnFailure
	case "unless-stopped":
		return container.RestartPolicyUnlessStopped
	case "any", "always":
		return container.RestartPolicyAlways
	default:
		return container.RestartPolicyMode(condition)
	}
}

func getDeployResources(s types.ServiceConfig) container.Resources {
	var swappiness *int64
	if s.MemSwappiness != 0 {
		val := int64(s.MemSwappiness)
		swappiness = &val
	}
	resources := container.Resources{
		CgroupParent:       s.CgroupParent,
		Memory:             int64(s.MemLimit),
		MemorySwap:         int64(s.MemSwapLimit),
		MemorySwappiness:   swappiness,
		MemoryReservation:  int64(s.MemReservation),
		OomKillDisable:     &s.OomKillDisable,
		CPUCount:           s.CPUCount,
		CPUPeriod:          s.CPUPeriod,
		CPUQuota:           s.CPUQuota,
		CPURealtimePeriod:  s.CPURTPeriod,
		CPURealtimeRuntime: s.CPURTRuntime,
		CPUShares:          s.CPUShares,
		NanoCPUs:           int64(s.CPUS * 1e9),
		CPUPercent:         int64(s.CPUPercent * 100),
		CpusetCpus:         s.CPUSet,
		DeviceCgroupRules:  s.DeviceCgroupRules,
	}

	if s.PidsLimit != 0 {
		resources.PidsLimit = &s.PidsLimit
	}

	setBlkio(s.BlkioConfig, &resources)

	if s.Deploy != nil {
		setLimits(s.Deploy.Resources.Limits, &resources)
		setReservations(s.Deploy.Resources.Reservations, &resources)
	}

	var cdiDeviceNames []string
	for _, device := range s.Devices {

		if device.Source == device.Target && cdi.IsQualifiedName(device.Source) {
			cdiDeviceNames = append(cdiDeviceNames, device.Source)
			continue
		}

		resources.Devices = append(resources.Devices, container.DeviceMapping{
			PathOnHost:        device.Source,
			PathInContainer:   device.Target,
			CgroupPermissions: device.Permissions,
		})
	}

	if len(cdiDeviceNames) > 0 {
		resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
			Driver:    "cdi",
			DeviceIDs: cdiDeviceNames,
		})
	}

	for _, gpus := range s.Gpus {
		resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
			Driver:       gpus.Driver,
			Count:        int(gpus.Count),
			DeviceIDs:    gpus.IDs,
			Capabilities: [][]string{append(gpus.Capabilities, "gpu")},
			Options:      gpus.Options,
		})
	}

	ulimits := toUlimits(s.Ulimits)
	resources.Ulimits = ulimits
	return resources
}

func toUlimits(m map[string]*types.UlimitsConfig) []*container.Ulimit {
	var ulimits []*container.Ulimit
	for name, u := range m {
		soft := u.Single
		if u.Soft != 0 {
			soft = u.Soft
		}
		hard := u.Single
		if u.Hard != 0 {
			hard = u.Hard
		}
		ulimits = append(ulimits, &container.Ulimit{
			Name: name,
			Hard: int64(hard),
			Soft: int64(soft),
		})
	}
	return ulimits
}

func setReservations(reservations *types.Resource, resources *container.Resources) {
	if reservations == nil {
		return
	}
	// Cpu reservation is a swarm option and PIDs is only a limit
	// So we only need to map memory reservation and devices
	if reservations.MemoryBytes != 0 {
		resources.MemoryReservation = int64(reservations.MemoryBytes)
	}

	for _, device := range reservations.Devices {
		resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
			Capabilities: [][]string{device.Capabilities},
			Count:        int(device.Count),
			DeviceIDs:    device.IDs,
			Driver:       device.Driver,
			Options:      device.Options,
		})
	}
}

func setLimits(limits *types.Resource, resources *container.Resources) {
	if limits == nil {
		return
	}
	if limits.MemoryBytes != 0 {
		resources.Memory = int64(limits.MemoryBytes)
	}
	if limits.NanoCPUs != 0 {
		resources.NanoCPUs = int64(limits.NanoCPUs * 1e9)
	}
	if limits.Pids > 0 {
		resources.PidsLimit = &limits.Pids
	}
}

func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
	if blkio == nil {
		return
	}
	resources.BlkioWeight = blkio.Weight
	for _, b := range blkio.WeightDevice {
		resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
			Path:   b.Path,
			Weight: b.Weight,
		})
	}
	for _, b := range blkio.DeviceReadBps {
		resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
			Path: b.Path,
			Rate: uint64(b.Rate),
		})
	}
	for _, b := range blkio.DeviceReadIOps {
		resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
			Path: b.Path,
			Rate: uint64(b.Rate),
		})
	}
	for _, b := range blkio.DeviceWriteBps {
		resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
			Path: b.Path,
			Rate: uint64(b.Rate),
		})
	}
	for _, b := range blkio.DeviceWriteIOps {
		resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
			Path: b.Path,
			Rate: uint64(b.Rate),
		})
	}
}

func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
	ports := nat.PortSet{}
	for _, s := range s.Expose {
		p := nat.Port(s)
		ports[p] = struct{}{}
	}
	for _, p := range s.Ports {
		p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
		ports[p] = struct{}{}
	}
	return ports
}

func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
	bindings := nat.PortMap{}
	for _, port := range s.Ports {
		p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
		binding := nat.PortBinding{
			HostIP:   port.HostIP,
			HostPort: port.Published,
		}
		bindings[p] = append(bindings[p], binding)
	}
	return bindings
}

func getDependentServiceFromMode(mode string) string {
	if strings.HasPrefix(
		mode,
		types.NetworkModeServicePrefix,
	) {
		return mode[len(types.NetworkModeServicePrefix):]
	}
	return ""
}

func (s *composeService) buildContainerVolumes(
	ctx context.Context,
	p types.Project,
	service types.ServiceConfig,
	inherit *moby.Container,
) ([]string, []mount.Mount, error) {
	var mounts []mount.Mount
	var binds []string

	image := api.GetImageNameOrDefault(service, p.Name)
	imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
	if err != nil {
		return nil, nil, err
	}

	mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
	if err != nil {
		return nil, nil, err
	}

MOUNTS:
	for _, m := range mountOptions {
		if m.Type == mount.TypeNamedPipe {
			mounts = append(mounts, m)
			continue
		}
		if m.Type == mount.TypeBind {
			// `Mount` is preferred but does not offer option to created host path if missing
			// so `Bind` API is used here with raw volume string
			// see https://github.com/moby/moby/issues/43483
			for _, v := range service.Volumes {
				if v.Target == m.Target {
					switch {
					case string(m.Type) != v.Type:
						v.Source = m.Source
						fallthrough
					case !requireMountAPI(v.Bind):
						binds = append(binds, v.String())
						continue MOUNTS
					}
				}
			}
		}
		mounts = append(mounts, m)
	}
	return binds, mounts, nil
}

// requireMountAPI check if Bind declaration can be implemented by the plain old Bind API or uses any of the advanced
// options which require use of Mount API
func requireMountAPI(bind *types.ServiceVolumeBind) bool {
	switch {
	case bind == nil:
		return false
	case !bind.CreateHostPath:
		return true
	case bind.Propagation != "":
		return true
	case bind.Recursive != "":
		return true
	default:
		return false
	}
}

func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
	mounts := map[string]mount.Mount{}
	if inherit != nil {
		for _, m := range inherit.Mounts {
			if m.Type == "tmpfs" {
				continue
			}
			src := m.Source
			if m.Type == "volume" {
				src = m.Name
			}

			if img.Config != nil {
				if _, ok := img.Config.Volumes[m.Destination]; ok {
					// inherit previous container's anonymous volume
					mounts[m.Destination] = mount.Mount{
						Type:     m.Type,
						Source:   src,
						Target:   m.Destination,
						ReadOnly: !m.RW,
					}
				}
			}
			volumes := []types.ServiceVolumeConfig{}
			for _, v := range s.Volumes {
				if v.Target != m.Destination || v.Source != "" {
					volumes = append(volumes, v)
					continue
				}
				// inherit previous container's anonymous volume
				mounts[m.Destination] = mount.Mount{
					Type:     m.Type,
					Source:   src,
					Target:   m.Destination,
					ReadOnly: !m.RW,
				}
			}
			s.Volumes = volumes
		}
	}

	mounts, err := fillBindMounts(p, s, mounts)
	if err != nil {
		return nil, err
	}

	values := make([]mount.Mount, 0, len(mounts))
	for _, v := range mounts {
		values = append(values, v)
	}
	return values, nil
}

func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
	for _, v := range s.Volumes {
		bindMount, err := buildMount(p, v)
		if err != nil {
			return nil, err
		}
		m[bindMount.Target] = bindMount
	}

	secrets, err := buildContainerSecretMounts(p, s)
	if err != nil {
		return nil, err
	}
	for _, s := range secrets {
		if _, found := m[s.Target]; found {
			continue
		}
		m[s.Target] = s
	}

	configs, err := buildContainerConfigMounts(p, s)
	if err != nil {
		return nil, err
	}
	for _, c := range configs {
		if _, found := m[c.Target]; found {
			continue
		}
		m[c.Target] = c
	}
	return m, nil
}

func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
	mounts := map[string]mount.Mount{}

	configsBaseDir := "/"
	for _, config := range s.Configs {
		target := config.Target
		if config.Target == "" {
			target = configsBaseDir + config.Source
		} else if !isAbsTarget(config.Target) {
			target = configsBaseDir + config.Target
		}

		definedConfig := p.Configs[config.Source]
		if definedConfig.External {
			return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
		}

		if definedConfig.Driver != "" {
			return nil, errors.New("Docker Compose does not support configs.*.driver")
		}
		if definedConfig.TemplateDriver != "" {
			return nil, errors.New("Docker Compose does not support configs.*.template_driver")
		}

		if definedConfig.Environment != "" || definedConfig.Content != "" {
			continue
		}

		if config.UID != "" || config.GID != "" || config.Mode != nil {
			logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
		}

		bindMount, err := buildMount(p, types.ServiceVolumeConfig{
			Type:     types.VolumeTypeBind,
			Source:   definedConfig.File,
			Target:   target,
			ReadOnly: true,
		})
		if err != nil {
			return nil, err
		}
		mounts[target] = bindMount
	}
	values := make([]mount.Mount, 0, len(mounts))
	for _, v := range mounts {
		values = append(values, v)
	}
	return values, nil
}

func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
	mounts := map[string]mount.Mount{}

	secretsDir := "/run/secrets/"
	for _, secret := range s.Secrets {
		target := secret.Target
		if secret.Target == "" {
			target = secretsDir + secret.Source
		} else if !isAbsTarget(secret.Target) {
			target = secretsDir + secret.Target
		}

		definedSecret := p.Secrets[secret.Source]
		if definedSecret.External {
			return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
		}

		if definedSecret.Driver != "" {
			return nil, errors.New("Docker Compose does not support secrets.*.driver")
		}
		if definedSecret.TemplateDriver != "" {
			return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
		}

		if definedSecret.Environment != "" {
			continue
		}

		if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
			logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
		}

		if _, err := os.Stat(definedSecret.File); os.IsNotExist(err) {
			logrus.Warnf("secret file %s does not exist", definedSecret.Name)
		}

		mnt, err := buildMount(p, types.ServiceVolumeConfig{
			Type:     types.VolumeTypeBind,
			Source:   definedSecret.File,
			Target:   target,
			ReadOnly: true,
			Bind: &types.ServiceVolumeBind{
				CreateHostPath: false,
			},
		})
		if err != nil {
			return nil, err
		}
		mounts[target] = mnt
	}
	values := make([]mount.Mount, 0, len(mounts))
	for _, v := range mounts {
		values = append(values, v)
	}
	return values, nil
}

func isAbsTarget(p string) bool {
	return isUnixAbs(p) || isWindowsAbs(p)
}

func isUnixAbs(p string) bool {
	return strings.HasPrefix(p, "/")
}

func isWindowsAbs(p string) bool {
	if strings.HasPrefix(p, "\\\\") {
		return true
	}
	if len(p) > 2 && p[1] == ':' {
		return p[2] == '\\'
	}
	return false
}

func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
	source := volume.Source
	// on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
	// do not replace these with  filepath.Abs(source) that will include a default drive.
	if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
		// volume source has already been prefixed with workdir if required, by compose-go project loader
		var err error
		source, err = filepath.Abs(source)
		if err != nil {
			return mount.Mount{}, err
		}
	}
	if volume.Type == types.VolumeTypeVolume {
		if volume.Source != "" {
			pVolume, ok := project.Volumes[volume.Source]
			if ok {
				source = pVolume.Name
			}
		}
	}

	bind, vol, tmpfs := buildMountOptions(volume)

	if bind != nil {
		volume.Type = types.VolumeTypeBind
	}

	return mount.Mount{
		Type:          mount.Type(volume.Type),
		Source:        source,
		Target:        volume.Target,
		ReadOnly:      volume.ReadOnly,
		Consistency:   mount.Consistency(volume.Consistency),
		BindOptions:   bind,
		VolumeOptions: vol,
		TmpfsOptions:  tmpfs,
	}, nil
}

func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
	switch volume.Type {
	case "bind":
		if volume.Volume != nil {
			logrus.Warnf("mount of type `bind` should not define `volume` option")
		}
		if volume.Tmpfs != nil {
			logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
		}
		return buildBindOption(volume.Bind), nil, nil
	case "volume":
		if volume.Bind != nil {
			logrus.Warnf("mount of type `volume` should not define `bind` option")
		}
		if volume.Tmpfs != nil {
			logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
		}
		return nil, buildVolumeOptions(volume.Volume), nil
	case "tmpfs":
		if volume.Bind != nil {
			logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
		}
		if volume.Volume != nil {
			logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
		}
		return nil, nil, buildTmpfsOptions(volume.Tmpfs)
	}
	return nil, nil, nil
}

func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
	if bind == nil {
		return nil
	}
	opts := &mount.BindOptions{
		Propagation:      mount.Propagation(bind.Propagation),
		CreateMountpoint: bind.CreateHostPath,
	}
	switch bind.Recursive {
	case "disabled":
		opts.NonRecursive = true
	case "writable":
		opts.ReadOnlyNonRecursive = true
	case "readonly":
		opts.ReadOnlyForceRecursive = true
	}
	return opts
}

func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
	if vol == nil {
		return nil
	}
	return &mount.VolumeOptions{
		NoCopy:  vol.NoCopy,
		Subpath: vol.Subpath,
		// Labels:       , // FIXME missing from model ?
		// DriverConfig: , // FIXME missing from model ?
	}
}

func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
	if tmpfs == nil {
		return nil
	}
	return &mount.TmpfsOptions{
		SizeBytes: int64(tmpfs.Size),
		Mode:      os.FileMode(tmpfs.Mode),
	}
}

func (s *composeService) ensureNetwork(ctx context.Context, project *types.Project, name string, n *types.NetworkConfig) (string, error) {
	if n.External {
		return s.resolveExternalNetwork(ctx, n)
	}

	id, err := s.resolveOrCreateNetwork(ctx, project, name, n)
	if errdefs.IsConflict(err) {
		// Maybe another execution of `docker compose up|run` created same network
		// let's retry once
		return s.resolveOrCreateNetwork(ctx, project, name, n)
	}
	return id, err
}

func (s *composeService) resolveOrCreateNetwork(ctx context.Context, project *types.Project, name string, n *types.NetworkConfig) (string, error) { //nolint:gocyclo
	// First, try to find a unique network matching by name or ID
	inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, network.InspectOptions{})
	if err == nil {
		// NetworkInspect will match on ID prefix, so double check we get the expected one
		// as looking for network named `db` we could erroneously match network ID `db9086999caf`
		if inspect.Name == n.Name || inspect.ID == n.Name {
			p, ok := inspect.Labels[api.ProjectLabel]
			if !ok {
				logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
					"Set `external: true` to use an existing network", n.Name)
			} else if p != project.Name {
				logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
					"Set `external: true` to use an existing network", n.Name, project.Name)
			}
			if inspect.Labels[api.NetworkLabel] != name {
				return "", fmt.Errorf(
					"network %s was found but has incorrect label %s set to %q (expected: %q)",
					n.Name,
					api.NetworkLabel,
					inspect.Labels[api.NetworkLabel],
					name,
				)
			}

			hash := inspect.Labels[api.ConfigHashLabel]
			expected, err := NetworkHash(n)
			if err != nil {
				return "", err
			}
			if hash == "" || hash == expected {
				return inspect.ID, nil
			}

			err = s.removeDivergedNetwork(ctx, project, name, n)
			if err != nil {
				return "", err
			}
		}
	}
	// ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error

	// Either not found, or name is ambiguous - use NetworkList to list by name
	networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{
		Filters: filters.NewArgs(filters.Arg("name", n.Name)),
	})
	if err != nil {
		return "", err
	}

	// NetworkList Matches all or part of a network name, so we have to filter for a strict match
	networks = utils.Filter(networks, func(net network.Summary) bool {
		return net.Name == n.Name
	})

	for _, net := range networks {
		if net.Labels[api.ProjectLabel] == project.Name &&
			net.Labels[api.NetworkLabel] == name {
			return net.ID, nil
		}
	}

	// we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
	// scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
	// prevents to create another one.
	if len(networks) > 0 {
		logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
			"Set `external: true` to use an existing network", n.Name)
		return networks[0].ID, nil
	}

	var ipam *network.IPAM
	if n.Ipam.Config != nil {
		var config []network.IPAMConfig
		for _, pool := range n.Ipam.Config {
			config = append(config, network.IPAMConfig{
				Subnet:     pool.Subnet,
				IPRange:    pool.IPRange,
				Gateway:    pool.Gateway,
				AuxAddress: pool.AuxiliaryAddresses,
			})
		}
		ipam = &network.IPAM{
			Driver: n.Ipam.Driver,
			Config: config,
		}
	}
	hash, err := NetworkHash(n)
	if err != nil {
		return "", err
	}
	n.CustomLabels = n.CustomLabels.Add(api.ConfigHashLabel, hash)
	createOpts := network.CreateOptions{
		Labels:     mergeLabels(n.Labels, n.CustomLabels),
		Driver:     n.Driver,
		Options:    n.DriverOpts,
		Internal:   n.Internal,
		Attachable: n.Attachable,
		IPAM:       ipam,
		EnableIPv6: n.EnableIPv6,
	}

	if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
		createOpts.IPAM = &network.IPAM{}
	}

	if n.Ipam.Driver != "" {
		createOpts.IPAM.Driver = n.Ipam.Driver
	}

	for _, ipamConfig := range n.Ipam.Config {
		config := network.IPAMConfig{
			Subnet:     ipamConfig.Subnet,
			IPRange:    ipamConfig.IPRange,
			Gateway:    ipamConfig.Gateway,
			AuxAddress: ipamConfig.AuxiliaryAddresses,
		}
		createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
	}
	networkEventName := fmt.Sprintf("Network %s", n.Name)
	w := progress.ContextWriter(ctx)
	w.Event(progress.CreatingEvent(networkEventName))

	resp, err := s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
	if err != nil {
		w.Event(progress.ErrorEvent(networkEventName))
		return "", fmt.Errorf("failed to create network %s: %w", n.Name, err)
	}
	w.Event(progress.CreatedEvent(networkEventName))
	return resp.ID, nil
}

func (s *composeService) removeDivergedNetwork(ctx context.Context, project *types.Project, name string, n *types.NetworkConfig) error {
	// Remove services attached to this network to force recreation
	var services []string
	for _, service := range project.Services.Filter(func(config types.ServiceConfig) bool {
		_, ok := config.Networks[name]
		return ok
	}) {
		services = append(services, service.Name)
	}

	// Stop containers so we can remove network
	// They will be restarted (actually: recreated) with the updated network
	err := s.stop(ctx, project.Name, api.StopOptions{
		Services: services,
		Project:  project,
	})
	if err != nil {
		return err
	}

	err = s.apiClient().NetworkRemove(ctx, n.Name)
	eventName := fmt.Sprintf("Network %s", n.Name)
	progress.ContextWriter(ctx).Event(progress.RemovedEvent(eventName))
	return err
}

func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) (string, error) {
	// NetworkInspect will match on ID prefix, so NetworkList with a name
	// filter is used to look for an exact match to prevent e.g. a network
	// named `db` from getting erroneously matched to a network with an ID
	// like `db9086999caf`
	networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{
		Filters: filters.NewArgs(filters.Arg("name", n.Name)),
	})
	if err != nil {
		return "", err
	}

	if len(networks) == 0 {
		// in this instance, n.Name is really an ID
		sn, err := s.apiClient().NetworkInspect(ctx, n.Name, network.InspectOptions{})
		if err != nil && !errdefs.IsNotFound(err) {
			return "", err
		}
		networks = append(networks, sn)
	}

	// NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
	networks = utils.Filter(networks, func(net network.Inspect) bool {
		// later in this function, the name is changed the to ID.
		// this function is called during the rebuild stage of `compose watch`.
		// we still require just one network back, but we need to run the search on the ID
		return net.Name == n.Name || net.ID == n.Name
	})

	switch len(networks) {
	case 1:
		return networks[0].ID, nil
	case 0:
		enabled, err := s.isSWarmEnabled(ctx)
		if err != nil {
			return "", err
		}
		if enabled {
			// Swarm nodes do not register overlay networks that were
			// created on a different node unless they're in use.
			// So we can't preemptively check network exists, but
			// networkAttach will later fail anyway if network actually doesn't exist
			return "swarm", nil
		}
		return "", fmt.Errorf("network %s declared as external, but could not be found", n.Name)
	default:
		return "", fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
	}
}

func (s *composeService) ensureVolume(ctx context.Context, name string, volume types.VolumeConfig, project *types.Project, assumeYes bool) (string, error) {
	inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
	if err != nil {
		if !errdefs.IsNotFound(err) {
			return "", err
		}
		if volume.External {
			return "", fmt.Errorf("external volume %q not found", volume.Name)
		}
		err = s.createVolume(ctx, volume)
		return volume.Name, err
	}

	if volume.External {
		return volume.Name, nil
	}

	// Volume exists with name, but let's double-check this is the expected one
	p, ok := inspected.Labels[api.ProjectLabel]
	if !ok {
		logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
	}
	if ok && p != project.Name {
		logrus.Warnf("volume %q already exists but was created for project %q (expected %q). Use `external: true` to use an existing volume", volume.Name, p, project.Name)
	}

	expected, err := VolumeHash(volume)
	if err != nil {
		return "", err
	}
	actual, ok := inspected.Labels[api.ConfigHashLabel]
	if ok && actual != expected {
		confirm := assumeYes
		if !assumeYes {
			msg := fmt.Sprintf("Volume %q exists but doesn't match configuration in compose file. Recreate (data will be lost)?", volume.Name)
			confirm, err = prompt.NewPrompt(s.stdin(), s.stdout()).Confirm(msg, false)
			if err != nil {
				return "", err
			}
		}
		if confirm {
			err = s.removeDivergedVolume(ctx, name, volume, project)
			if err != nil {
				return "", err
			}
			return volume.Name, s.createVolume(ctx, volume)
		}
	}
	return inspected.Name, nil
}

func (s *composeService) removeDivergedVolume(ctx context.Context, name string, volume types.VolumeConfig, project *types.Project) error {
	// Remove services mounting divergent volume
	var services []string
	for _, service := range project.Services.Filter(func(config types.ServiceConfig) bool {
		for _, cfg := range config.Volumes {
			if cfg.Source == name {
				return true
			}
		}
		return false
	}) {
		services = append(services, service.Name)
	}

	err := s.stop(ctx, project.Name, api.StopOptions{
		Services: services,
		Project:  project,
	})
	if err != nil {
		return err
	}

	containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, services...)
	if err != nil {
		return err
	}

	// FIXME (ndeloof) we have to remove container so we can recreate volume
	// but doing so we can't inherit anonymous volumes from previous instance
	err = s.remove(ctx, containers, api.RemoveOptions{
		Services: services,
		Project:  project,
	})
	if err != nil {
		return err
	}

	return s.apiClient().VolumeRemove(ctx, volume.Name, true)
}

func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
	eventName := fmt.Sprintf("Volume %q", volume.Name)
	w := progress.ContextWriter(ctx)
	w.Event(progress.CreatingEvent(eventName))
	hash, err := VolumeHash(volume)
	if err != nil {
		return err
	}
	volume.CustomLabels.Add(api.ConfigHashLabel, hash)
	_, err = s.apiClient().VolumeCreate(ctx, volumetypes.CreateOptions{
		Labels:     mergeLabels(volume.Labels, volume.CustomLabels),
		Name:       volume.Name,
		Driver:     volume.Driver,
		DriverOpts: volume.DriverOpts,
	})
	if err != nil {
		w.Event(progress.ErrorEvent(eventName))
		return err
	}
	w.Event(progress.CreatedEvent(eventName))
	return nil
}