File: driver_common.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (1667 lines) | stat: -rw-r--r-- 50,830 bytes parent folder | download | duplicates (3)
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
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
package network

import (
	"context"
	"errors"
	"fmt"
	"maps"
	"net"
	"os"
	"slices"
	"strconv"
	"strings"
	"unicode"

	incus "github.com/lxc/incus/v6/client"
	internalInstance "github.com/lxc/incus/v6/internal/instance"
	"github.com/lxc/incus/v6/internal/iprange"
	"github.com/lxc/incus/v6/internal/server/bgp"
	"github.com/lxc/incus/v6/internal/server/cluster"
	"github.com/lxc/incus/v6/internal/server/cluster/request"
	"github.com/lxc/incus/v6/internal/server/db"
	dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
	"github.com/lxc/incus/v6/internal/server/network/acl"
	"github.com/lxc/incus/v6/internal/server/state"
	internalUtil "github.com/lxc/incus/v6/internal/util"
	"github.com/lxc/incus/v6/internal/version"
	"github.com/lxc/incus/v6/shared/api"
	"github.com/lxc/incus/v6/shared/logger"
	"github.com/lxc/incus/v6/shared/resources"
	"github.com/lxc/incus/v6/shared/util"
	"github.com/lxc/incus/v6/shared/validate"
)

// Info represents information about a network driver.
type Info struct {
	Projects           bool // Indicates if driver can be used in network enabled projects.
	NodeSpecificConfig bool // Whether driver has cluster node specific config as a prerequisite for creation.
	AddressForwards    bool // Indicates if driver supports address forwards.
	LoadBalancers      bool // Indicates if driver supports load balancers.
	Peering            bool // Indicates if the driver supports network peering.
}

// forwardTarget represents a single port forward target.
type forwardTarget struct {
	address net.IP
	ports   []uint64
}

// forwardPortMap represents a mapping of listen port(s) to target port(s) for a protocol/target address pair.
type forwardPortMap struct {
	listenPorts []uint64
	protocol    string
	target      forwardTarget
	snat        bool
}

type loadBalancerPortMap struct {
	listenPorts []uint64
	protocol    string
	targets     []forwardTarget
}

// subnetUsageType indicates the type of use for a subnet.
type subnetUsageType uint

const (
	subnetUsageNetwork subnetUsageType = iota
	subnetUsageNetworkSNAT
	subnetUsageNetworkForward
	subnetUsageNetworkLoadBalancer
	subnetUsageInstance
	subnetUsageProxy
)

// externalSubnetUsage represents usage of a subnet by a network or NIC.
type externalSubnetUsage struct {
	subnet          net.IPNet
	usageType       subnetUsageType
	networkProject  string
	networkName     string
	instanceProject string
	instanceName    string
	instanceDevice  string
}

// common represents a generic network.
type common struct {
	logger      logger.Logger
	state       *state.State
	id          int64
	project     string
	name        string
	netType     string
	description string
	config      map[string]string
	status      string
	managed     bool
	nodes       map[int64]db.NetworkNode
}

// init initialize internal variables.
func (n *common) init(s *state.State, id int64, projectName string, netInfo *api.Network, netNodes map[int64]db.NetworkNode) error {
	n.logger = logger.AddContext(logger.Ctx{"project": projectName, "driver": netInfo.Type, "network": netInfo.Name})
	n.id = id
	n.project = projectName
	n.name = netInfo.Name
	n.netType = netInfo.Type
	n.config = netInfo.Config
	n.state = s
	n.description = netInfo.Description
	n.status = netInfo.Status
	n.managed = netInfo.Managed
	n.nodes = netNodes

	return nil
}

// FillConfig fills requested config with any default values, by default this is a no-op.
func (n *common) FillConfig(config map[string]string) error {
	return nil
}

// validationRules returns a map of config rules common to all drivers.
func (n *common) validationRules() map[string]func(string) error {
	return map[string]func(string) error{}
}

// validate a network config against common rules and optional driver specific rules.
func (n *common) validate(config map[string]string, driverRules map[string]func(value string) error) error {
	checkedFields := map[string]struct{}{}

	// Get rules common for all drivers.
	rules := n.validationRules()

	// Merge driver specific rules into common rules.
	maps.Copy(rules, driverRules)

	// Run the validator against each field.
	for k, validator := range rules {
		checkedFields[k] = struct{}{} // Mark field as checked.
		err := validator(config[k])
		if err != nil {
			return fmt.Errorf("Invalid value for network %q option %q: %w", n.name, k, err)
		}
	}

	// Look for any unchecked fields, as these are unknown fields and validation should fail.
	for k := range config {
		_, checked := checkedFields[k]
		if checked {
			continue
		}

		// User keys are not validated.
		if internalInstance.IsUserConfig(k) {
			continue
		}

		return fmt.Errorf("Invalid option for network %q option %q", n.name, k)
	}

	return nil
}

// validateZoneNames checks the DNS zone names are valid in config.
func (n *common) validateZoneNames(config map[string]string) error {
	// Check if DNS zones in use.
	if config["dns.zone.forward"] == "" && config["dns.zone.reverse.ipv4"] == "" && config["dns.zone.reverse.ipv6"] == "" {
		return nil
	}

	var err error
	var zones []dbCluster.NetworkZone
	zoneProjects := make(map[string]string)

	err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		zones, err = dbCluster.GetNetworkZones(ctx, tx.Tx())
		if err != nil {
			return fmt.Errorf("Failed to load all network zones: %w", err)
		}

		for _, zone := range zones {
			zoneProjects[zone.Name] = zone.Project
		}

		return nil
	})
	if err != nil {
		return err
	}

	for _, keyName := range []string{"dns.zone.forward", "dns.zone.reverse.ipv4", "dns.zone.reverse.ipv6"} {
		keyZoneNames := util.SplitNTrimSpace(config[keyName], ",", -1, true)
		keyZoneNamesLen := len(keyZoneNames)
		if keyZoneNamesLen < 1 {
			continue
		} else if keyZoneNamesLen > 1 && (keyName == "dns.zone.reverse.ipv4" || keyName == "dns.zone.reverse.ipv6") {
			return fmt.Errorf("Invalid %q must contain only single DNS zone name", keyName)
		}

		zoneProjectsUsed := make(map[string]struct{})
		for _, keyZoneName := range keyZoneNames {
			zoneProjectName, found := zoneProjects[keyZoneName]
			if !found {
				return fmt.Errorf("Invalid %q, network zone %q not found", keyName, keyZoneName)
			}

			_, zoneProjectUsed := zoneProjectsUsed[zoneProjectName]
			if zoneProjectUsed {
				return fmt.Errorf("Invalid %q, contains multiple zones from the same project", keyName)
			}

			zoneProjectsUsed[zoneProjectName] = struct{}{}
		}
	}

	return nil
}

// ValidateName validates network name.
func (n *common) ValidateName(name string) error {
	if strings.Contains(name, ":") {
		return fmt.Errorf("Cannot contain %q", ":")
	}

	return nil
}

// ID returns the network ID.
func (n *common) ID() int64 {
	return n.id
}

// Name returns the network name.
func (n *common) Name() string {
	return n.name
}

// Type returns the network type.
func (n *common) Type() string {
	return n.netType
}

// Project returns the network project.
func (n *common) Project() string {
	return n.project
}

// Description returns the network description.
func (n *common) Description() string {
	return n.description
}

// Status returns the network status.
func (n *common) Status() string {
	return n.status
}

// LocalStatus returns network status of the local cluster member.
func (n *common) LocalStatus() string {
	// Check if network is unavailable locally and replace status if so.
	if !IsAvailable(n.Project(), n.Name()) {
		return api.NetworkStatusUnavailable
	}

	node, exists := n.nodes[n.state.DB.Cluster.GetNodeID()]
	if !exists {
		return api.NetworkStatusUnknown
	}

	return db.NetworkStateToAPIStatus(node.State)
}

// Config returns the network config.
func (n *common) Config() map[string]string {
	return n.config
}

func (n *common) IsManaged() bool {
	return n.managed
}

// Config returns the common network driver info.
func (n *common) Info() Info {
	return Info{
		Projects:           false,
		NodeSpecificConfig: true,
		AddressForwards:    false,
		LoadBalancers:      false,
	}
}

// Locations returns the list of cluster members this network is configured on.
func (n *common) Locations() []string {
	locations := make([]string, 0, len(n.nodes))
	for _, netNode := range n.nodes {
		locations = append(locations, netNode.Name)
	}

	return locations
}

// IsUsed returns whether the network is in use by instances or by downstream networks.
func (n *common) IsUsed(instanceOnly bool) (bool, error) {
	if instanceOnly {
		usedBy := 0
		err := UsedByInstanceDevices(n.state, n.project, n.name, n.netType, func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
			usedBy++
			return nil
		})
		if err != nil {
			return false, err
		}

		return usedBy > 0, nil
	}

	usedBy, err := UsedBy(n.state, n.project, n.id, n.name, n.netType, true)
	if err != nil {
		return false, err
	}

	return len(usedBy) > 0, nil
}

// DHCPv4Subnet returns nil always.
func (n *common) DHCPv4Subnet() *net.IPNet {
	return nil
}

// DHCPv6Subnet returns nil always.
func (n *common) DHCPv6Subnet() *net.IPNet {
	return nil
}

// DHCPv4Ranges returns a parsed set of DHCPv4 ranges for this network.
func (n *common) DHCPv4Ranges() []iprange.Range {
	dhcpRanges := make([]iprange.Range, 0)
	if n.config["ipv4.dhcp.ranges"] != "" {
		for _, r := range strings.Split(n.config["ipv4.dhcp.ranges"], ",") {
			parts := strings.SplitN(strings.TrimSpace(r), "-", 2)
			if len(parts) == 2 {
				startIP := net.ParseIP(parts[0])
				endIP := net.ParseIP(parts[1])
				dhcpRanges = append(dhcpRanges, iprange.Range{
					Start: startIP.To4(),
					End:   endIP.To4(),
				})
			}
		}
	}

	return dhcpRanges
}

// DHCPv6Ranges returns a parsed set of DHCPv6 ranges for this network.
func (n *common) DHCPv6Ranges() []iprange.Range {
	dhcpRanges := make([]iprange.Range, 0)
	if n.config["ipv6.dhcp.ranges"] != "" {
		for _, r := range strings.Split(n.config["ipv6.dhcp.ranges"], ",") {
			parts := strings.SplitN(strings.TrimSpace(r), "-", 2)
			if len(parts) == 2 {
				startIP := net.ParseIP(parts[0])
				endIP := net.ParseIP(parts[1])
				dhcpRanges = append(dhcpRanges, iprange.Range{
					Start: startIP.To16(),
					End:   endIP.To16(),
				})
			}
		}
	}

	return dhcpRanges
}

// update the internal config variables, and if not cluster notification, notifies all nodes and updates database.
func (n *common) update(applyNetwork api.NetworkPut, targetNode string, clientType request.ClientType) error {
	// Update internal config before database has been updated (so that if update is a notification we apply
	// the config being supplied and not that in the database).
	n.description = applyNetwork.Description
	n.config = applyNetwork.Config

	// If this update isn't coming via a cluster notification itself, then notify all nodes of change and then
	// update the database.
	if clientType != request.ClientTypeNotifier {
		if targetNode == "" {
			// Notify all other nodes to update the network if no target specified.
			notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
			if err != nil {
				return err
			}

			sendNetwork := applyNetwork
			sendNetwork.Config = make(map[string]string)

			// Don't forward node specific keys (these will be merged in on recipient node).
			sendNetwork.Config = db.StripNodeSpecificNetworkConfig(applyNetwork.Config)

			err = notifier(func(client incus.InstanceServer) error {
				return client.UseProject(n.project).UpdateNetwork(n.name, sendNetwork, "")
			})
			if err != nil {
				return err
			}
		}

		err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
			// Update the database.
			return tx.UpdateNetwork(ctx, n.project, n.name, applyNetwork.Description, applyNetwork.Config)
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// configChanged compares supplied new config with existing config. Returns a boolean indicating if differences in
// the config or description were found (and the database record needs updating), and a list of non-user config
// keys that have changed, and a copy of the current internal network config that can be used to revert if needed.
func (n *common) configChanged(newNetwork api.NetworkPut) (bool, []string, api.NetworkPut, error) {
	// Backup the current state.
	oldNetwork := api.NetworkPut{
		Description: n.description,
		Config:      map[string]string{},
	}

	err := util.DeepCopy(&n.config, &oldNetwork.Config)
	if err != nil {
		return false, nil, oldNetwork, err
	}

	// Diff the configurations.
	changedKeys := []string{}
	dbUpdateNeeded := false

	if newNetwork.Description != n.description {
		dbUpdateNeeded = true
	}

	for k, v := range oldNetwork.Config {
		if v != newNetwork.Config[k] {
			dbUpdateNeeded = true

			// Add non-user changed key to list of changed keys.
			if !strings.HasPrefix(k, "user.") && !slices.Contains(changedKeys, k) {
				changedKeys = append(changedKeys, k)
			}
		}
	}

	for k, v := range newNetwork.Config {
		if v != oldNetwork.Config[k] {
			dbUpdateNeeded = true

			// Add non-user changed key to list of changed keys.
			if !strings.HasPrefix(k, "user.") && !slices.Contains(changedKeys, k) {
				changedKeys = append(changedKeys, k)
			}
		}
	}

	return dbUpdateNeeded, changedKeys, oldNetwork, nil
}

// rename the network directory, update database record and update internal variables.
func (n *common) rename(newName string) error {
	// Clear new directory if exists.
	if util.PathExists(internalUtil.VarPath("networks", newName)) {
		_ = os.RemoveAll(internalUtil.VarPath("networks", newName))
	}

	// Rename directory to new name.
	if util.PathExists(internalUtil.VarPath("networks", n.name)) {
		err := os.Rename(internalUtil.VarPath("networks", n.name), internalUtil.VarPath("networks", newName))
		if err != nil {
			return err
		}
	}

	err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		// Rename the database entry.
		return tx.RenameNetwork(ctx, n.project, n.name, newName)
	})
	if err != nil {
		return err
	}

	// Reinitialize internal name variable and logger context with new name.
	n.name = newName

	return nil
}

// warningsDelete deletes any persistent warnings for the network.
func (n *common) warningsDelete() error {
	err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		return dbCluster.DeleteWarnings(ctx, tx.Tx(), dbCluster.TypeNetwork, int(n.ID()))
	})
	if err != nil {
		return fmt.Errorf("Failed deleting persistent warnings: %w", err)
	}

	return nil
}

// delete the network on local server.
func (n *common) delete(clientType request.ClientType) error {
	// Delete any persistent warnings for network.
	err := n.warningsDelete()
	if err != nil {
		return err
	}

	// Cleanup storage.
	if util.PathExists(internalUtil.VarPath("networks", n.name)) {
		_ = os.RemoveAll(internalUtil.VarPath("networks", n.name))
	}

	pn := ProjectNetwork{
		ProjectName: n.Project(),
		NetworkName: n.Name(),
	}

	unavailableNetworksMu.Lock()
	delete(unavailableNetworks, pn)
	unavailableNetworksMu.Unlock()

	return nil
}

// Create is a no-op.
func (n *common) Create(clientType request.ClientType) error {
	n.logger.Debug("Create", logger.Ctx{"clientType": clientType, "config": n.config})
	return nil
}

// HandleHeartbeat is a no-op.
func (n *common) HandleHeartbeat(heartbeatData *cluster.APIHeartbeat) error {
	return nil
}

// notifyDependentNetworks allows any dependent networks to apply changes to themselves when this network changes.
func (n *common) notifyDependentNetworks(changedKeys []string) {
	if n.Project() != api.ProjectDefaultName {
		return // Only networks in the default project can be used as dependent networks.
	}

	// Get a list of projects.
	var err error
	var projectNames []string

	err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		projectNames, err = dbCluster.GetProjectNames(ctx, tx.Tx())
		return err
	})
	if err != nil {
		n.logger.Error("Failed to load projects", logger.Ctx{"err": err})
		return
	}

	for _, projectName := range projectNames {
		var depNets []string

		err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
			// Get a list of managed networks in project.
			depNets, err = tx.GetCreatedNetworkNamesByProject(ctx, projectName)

			return err
		})
		if err != nil {
			n.logger.Error("Failed to load networks in project", logger.Ctx{"project": projectName, "err": err})
			continue // Continue to next project.
		}

		for _, depName := range depNets {
			depNet, err := LoadByName(n.state, projectName, depName)
			if err != nil {
				n.logger.Error("Failed to load dependent network", logger.Ctx{"project": projectName, "dependentNetwork": depName, "err": err})
				continue // Continue to next network.
			}

			if depNet.Config()["network"] != n.Name() {
				continue // Skip network, as does not depend on our network.
			}

			err = depNet.handleDependencyChange(n.Name(), n.Config(), changedKeys)
			if err != nil {
				n.logger.Error("Failed notifying dependent network", logger.Ctx{"project": projectName, "dependentNetwork": depName, "err": err})
				continue // Continue to next network.
			}
		}
	}
}

// handleDependencyChange is a placeholder for networks that don't need to handle changes from dependent networks.
func (n *common) handleDependencyChange(netName string, netConfig map[string]string, changedKeys []string) error {
	return nil
}

// bgpValidate.
func (n *common) bgpValidationRules(config map[string]string) (map[string]func(value string) error, error) {
	rules := map[string]func(value string) error{}
	for k := range config {
		// BGP keys have the peer name in their name, extract the suffix.
		if !strings.HasPrefix(k, "bgp.peers.") {
			continue
		}

		// Validate remote name in key.
		fields := strings.Split(k, ".")
		if len(fields) != 4 {
			return nil, fmt.Errorf("Invalid network configuration key: %q", k)
		}

		bgpKey := fields[3]

		// Add the correct validation rule for the dynamic field based on last part of key.
		switch bgpKey {
		case "address":
			rules[k] = validate.Optional(validate.IsNetworkAddress)
		case "asn":
			rules[k] = validate.Optional(validate.IsInRange(1, 4294967294))
		case "password":
			rules[k] = validate.Optional(validate.IsAny)
		case "holdtime":
			rules[k] = validate.Optional(validate.IsInRange(9, 65535))
		}
	}

	return rules, nil
}

// bgpSetup initializes BGP peers and prefixes.
func (n *common) bgpSetup(oldConfig map[string]string) error {
	currentPeers := n.bgpGetPeers(n.config)
	oldPeers := n.bgpGetPeers(oldConfig)

	// Don't set up BGP on non-OVN networks when no peers are configured.
	if n.netType != "ovn" && len(currentPeers) == 0 {
		if len(oldPeers) > 0 {
			return n.bgpClear(oldConfig)
		}

		return nil
	}

	// Set up the peers.
	err := n.bgpSetupPeers(oldConfig)
	if err != nil {
		return fmt.Errorf("Failed setting up BGP peers: %w", err)
	}

	// Export the prefixes.
	err = n.bgpSetupPrefixes(oldConfig)
	if err != nil {
		return fmt.Errorf("Failed setting up BGP prefixes: %w", err)
	}

	err = n.forwardBGPSetupPrefixes()
	if err != nil {
		return fmt.Errorf("Failed applying BGP prefixes for address forwards: %w", err)
	}

	return nil
}

// bgpClear clears BGP peers and prefixes.
func (n *common) bgpClear(config map[string]string) error {
	// Clear all peers.
	err := n.bgpClearPeers(config)
	if err != nil {
		return err
	}

	// Clear all prefixes.
	err = n.state.BGP.RemovePrefixByOwner(fmt.Sprintf("network_%d", n.id))
	if err != nil {
		return err
	}

	// Clear existing address forward prefixes for network.
	err = n.state.BGP.RemovePrefixByOwner(fmt.Sprintf("network_%d_forward", n.id))
	if err != nil {
		return err
	}

	return nil
}

// bgpClearPeers removes all BGP peers on the network.
func (n *common) bgpClearPeers(config map[string]string) error {
	peers := n.bgpGetPeers(config)
	for _, peer := range peers {
		// Remove the peer.
		fields := strings.Split(peer, ",")
		err := n.state.BGP.RemovePeer(net.ParseIP(fields[0]))
		if err != nil && !errors.Is(err, bgp.ErrPeerNotFound) {
			return err
		}
	}

	return nil
}

// bgpSetupPeers updates the list of BGP peers.
func (n *common) bgpSetupPeers(oldConfig map[string]string) error {
	// Setup BGP (and handled config changes).
	newPeers := n.bgpGetPeers(n.config)
	oldPeers := n.bgpGetPeers(oldConfig)

	// Remove old peers.
	for _, peer := range oldPeers {
		if slices.Contains(newPeers, peer) {
			continue
		}

		// Remove old peer.
		fields := strings.Split(peer, ",")
		err := n.state.BGP.RemovePeer(net.ParseIP(fields[0]))
		if err != nil {
			return err
		}
	}

	// Add new peers.
	for _, peer := range newPeers {
		if slices.Contains(oldPeers, peer) {
			continue
		}

		// Add new peer.
		fields := strings.Split(peer, ",")
		asn, err := strconv.ParseUint(fields[1], 10, 32)
		if err != nil {
			return err
		}

		var holdTime uint64
		if fields[3] != "" {
			holdTime, err = strconv.ParseUint(fields[3], 10, 32)
			if err != nil {
				return err
			}
		}

		err = n.state.BGP.AddPeer(net.ParseIP(fields[0]), uint32(asn), fields[2], holdTime)
		if err != nil {
			return err
		}
	}

	return nil
}

// bgpNextHopAddress parses nexthop configuration and returns next hop address to use for BGP routes.
// Uses first of bgp.ipv{ipVersion}.nexthop or volatile.network.ipv{ipVersion}.address or wildcard address.
func (n *common) bgpNextHopAddress(ipVersion uint) net.IP {
	nextHopAddr := net.ParseIP(n.config[fmt.Sprintf("bgp.ipv%d.nexthop", ipVersion)])
	if nextHopAddr == nil {
		nextHopAddr = net.ParseIP(n.config[fmt.Sprintf("volatile.network.ipv%d.address", ipVersion)])
		if nextHopAddr == nil {
			if ipVersion == 4 {
				nextHopAddr = net.ParseIP("0.0.0.0")
			} else {
				nextHopAddr = net.ParseIP("::")
			}
		}
	}

	return nextHopAddr
}

// bgpSetupPrefixes refreshes the prefix list for the network.
func (n *common) bgpSetupPrefixes(oldConfig map[string]string) error {
	// Clear existing prefixes.
	bgpOwner := fmt.Sprintf("network_%d", n.id)
	if oldConfig != nil {
		err := n.state.BGP.RemovePrefixByOwner(bgpOwner)
		if err != nil {
			return err
		}
	}

	// Add the new prefixes.
	for _, ipVersion := range []uint{4, 6} {
		nextHopAddr := n.bgpNextHopAddress(ipVersion)

		// If network has NAT enabled, then export network's NAT address if specified.
		if util.IsTrue(n.config[fmt.Sprintf("ipv%d.nat", ipVersion)]) {
			natAddressKey := fmt.Sprintf("ipv%d.nat.address", ipVersion)
			if n.config[natAddressKey] != "" {
				subnetSize := 128
				if ipVersion == 4 {
					subnetSize = 32
				}

				_, subnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", n.config[natAddressKey], subnetSize))
				if err != nil {
					return err
				}

				err = n.state.BGP.AddPrefix(*subnet, nextHopAddr, bgpOwner)
				if err != nil {
					return err
				}
			}
		} else if !slices.Contains([]string{"", "none"}, n.config[fmt.Sprintf("ipv%d.address", ipVersion)]) {
			// If network has NAT disabled, then export the network's subnet if specified.
			netAddress := n.config[fmt.Sprintf("ipv%d.address", ipVersion)]
			_, subnet, err := net.ParseCIDR(netAddress)
			if err != nil {
				return fmt.Errorf("Failed parsing network address %q: %w", netAddress, err)
			}

			err = n.state.BGP.AddPrefix(*subnet, nextHopAddr, bgpOwner)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// bgpGetPeers returns a list of strings representing the BGP peers.
func (n *common) bgpGetPeers(config map[string]string) []string {
	// Get a list of peer names.
	peerNames := []string{}
	for k := range config {
		if !strings.HasPrefix(k, "bgp.peers.") {
			continue
		}

		fields := strings.Split(k, ".")
		if !slices.Contains(peerNames, fields[2]) {
			peerNames = append(peerNames, fields[2])
		}
	}

	// Build up a list of peer strings.
	peers := []string{}
	for _, peerName := range peerNames {
		peerAddress := config[fmt.Sprintf("bgp.peers.%s.address", peerName)]
		peerASN := config[fmt.Sprintf("bgp.peers.%s.asn", peerName)]
		peerPassword := config[fmt.Sprintf("bgp.peers.%s.password", peerName)]
		peerHoldTime := config[fmt.Sprintf("bgp.peers.%s.holdtime", peerName)]

		if peerAddress != "" && peerASN != "" {
			peers = append(peers, fmt.Sprintf("%s,%s,%s,%s", peerAddress, peerASN, peerPassword, peerHoldTime))
		}
	}

	return peers
}

// forwardValidate validates the forward request.
func (n *common) forwardValidate(listenAddress net.IP, forward *api.NetworkForwardPut) ([]*forwardPortMap, error) {
	if listenAddress == nil {
		return nil, errors.New("Invalid listen address")
	}

	if listenAddress.IsUnspecified() {
		return nil, fmt.Errorf("Cannot use unspecified address: %q", listenAddress.String())
	}

	listenIsIP4 := listenAddress.To4() != nil

	// For checking target addresses are within network's subnet.
	netIPKey := "ipv4.address"
	if !listenIsIP4 {
		netIPKey = "ipv6.address"
	}

	netIPAddress := n.config[netIPKey]

	var err error
	var netSubnet *net.IPNet
	if netIPAddress != "" {
		_, netSubnet, err = net.ParseCIDR(n.config[netIPKey])
		if err != nil {
			return nil, err
		}
	}

	// Look for any unknown config fields.
	for k := range forward.Config {
		if k == "target_address" {
			continue
		}

		// User keys are not validated.

		// gendoc:generate(entity=network_forward, group=common, key=user.*)
		//
		// ---
		//  type: string
		//  shortdesc: User defined key/value configuration
		if internalInstance.IsUserConfig(k) {
			continue
		}

		return nil, fmt.Errorf("Invalid option %q", k)
	}

	// Validate default target address.

	// gendoc:generate(entity=network_forward, group=common, key=target_address)
	//
	// ---
	//  type: string
	//  shortdesc: Default target address for anything not covered through a port definition
	defaultTargetAddress := net.ParseIP(forward.Config["target_address"])

	if forward.Config["target_address"] != "" {
		if defaultTargetAddress == nil {
			return nil, errors.New("Invalid default target address")
		}

		defaultTargetIsIP4 := defaultTargetAddress.To4() != nil
		if listenIsIP4 != defaultTargetIsIP4 {
			return nil, errors.New("Cannot mix IP versions in listen address and default target address")
		}

		// Check default target address is within network's subnet.
		if netSubnet != nil && !SubnetContainsIP(netSubnet, defaultTargetAddress) {
			return nil, errors.New("Default target address is not within the network subnet")
		}
	}

	// Validate port rules.
	validPortProcols := []string{"tcp", "udp"}

	// Used to ensure that each listen port is only used once.
	listenPorts := map[string]map[int64]struct{}{
		"tcp": make(map[int64]struct{}),
		"udp": make(map[int64]struct{}),
	}

	// Maps portSpecID to a portMap struct.
	portMaps := make([]*forwardPortMap, 0, len(forward.Ports))
	for portSpecID, portSpec := range forward.Ports {
		if !slices.Contains(validPortProcols, portSpec.Protocol) {
			return nil, fmt.Errorf("Invalid port protocol in port specification %d, protocol must be one of: %s", portSpecID, strings.Join(validPortProcols, ", "))
		}

		targetAddress := net.ParseIP(portSpec.TargetAddress)
		if targetAddress == nil {
			return nil, fmt.Errorf("Invalid target address in port specification %d", portSpecID)
		}

		if targetAddress.Equal(defaultTargetAddress) {
			return nil, fmt.Errorf("Target address is same as default target address in port specification %d", portSpecID)
		}

		targetIsIP4 := targetAddress.To4() != nil
		if listenIsIP4 != targetIsIP4 {
			return nil, fmt.Errorf("Cannot mix IP versions in listen address and port specification %d target address", portSpecID)
		}

		// Check target address is within network's subnet.
		if netSubnet != nil && !SubnetContainsIP(netSubnet, targetAddress) {
			return nil, fmt.Errorf("Target address is not within the network subnet in port specification %d", portSpecID)
		}

		// Check valid listen port(s) supplied.
		listenPortRanges := util.SplitNTrimSpace(portSpec.ListenPort, ",", -1, true)
		if len(listenPortRanges) <= 0 {
			return nil, fmt.Errorf("Missing listen port in port specification %d", portSpecID)
		}

		portMap := forwardPortMap{
			listenPorts: make([]uint64, 0),
			target: forwardTarget{
				address: targetAddress,
			},
			protocol: portSpec.Protocol,
			snat:     portSpec.SNAT,
		}

		for _, pr := range listenPortRanges {
			portFirst, portRange, err := ParsePortRange(pr)
			if err != nil {
				return nil, fmt.Errorf("Invalid listen port in port specification %d: %w", portSpecID, err)
			}

			for i := range portRange {
				port := portFirst + i
				_, found := listenPorts[portSpec.Protocol][port]
				if found {
					return nil, fmt.Errorf("Duplicate listen port %d for protocol %q in port specification %d", port, portSpec.Protocol, portSpecID)
				}

				listenPorts[portSpec.Protocol][port] = struct{}{}
				portMap.listenPorts = append(portMap.listenPorts, uint64(port))
			}
		}

		// Check that SNAT is only used with bridges.
		if portSpec.SNAT && n.netType != "bridge" {
			return nil, errors.New("SNAT can only be used with bridge networks")
		}

		// Check valid target port(s) supplied.
		targetPortRanges := util.SplitNTrimSpace(portSpec.TargetPort, ",", -1, true)

		if len(targetPortRanges) > 0 {
			// Target ports can be at maximum the same length as listen ports.
			portMap.target.ports = make([]uint64, 0, len(portMap.listenPorts))

			for _, pr := range targetPortRanges {
				portFirst, portRange, err := ParsePortRange(pr)
				if err != nil {
					return nil, fmt.Errorf("Invalid target port in port specification %d", portSpecID)
				}

				for i := range portRange {
					port := portFirst + i
					portMap.target.ports = append(portMap.target.ports, uint64(port))
				}
			}

			// Only check if the target port count matches the listen port count if the target ports
			// don't equal 1, because we allow many-to-one type mapping.
			portSpectTargetPortsLen := len(portMap.target.ports)
			if portSpectTargetPortsLen != 1 && len(portMap.listenPorts) != portSpectTargetPortsLen {
				return nil, fmt.Errorf("Mismatch of listen port(s) and target port(s) count in port specification %d", portSpecID)
			}
		}

		portMaps = append(portMaps, &portMap)
	}

	return portMaps, err
}

// ForwardCreate returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) ForwardCreate(forward api.NetworkForwardsPost, clientType request.ClientType) error {
	return ErrNotImplemented
}

// ForwardUpdate returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) ForwardUpdate(listenAddress string, newForward api.NetworkForwardPut, clientType request.ClientType) error {
	return ErrNotImplemented
}

// ForwardDelete returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) ForwardDelete(listenAddress string, clientType request.ClientType) error {
	return ErrNotImplemented
}

// forwardBGPSetupPrefixes exports external forward addresses as prefixes.
func (n *common) forwardBGPSetupPrefixes() error {
	var fwdListenAddresses map[int64]string

	err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		var err error

		// Retrieve network forwards before clearing existing prefixes, and separate them by IP family.
		networkID := int64(n.ID())
		dbRecords, err := dbCluster.GetNetworkForwards(ctx, tx.Tx(), dbCluster.NetworkForwardFilter{
			NetworkID: &networkID,
		})
		if err != nil {
			return err
		}

		fwdListenAddresses = make(map[int64]string)
		for _, dbRecord := range dbRecords {
			// memberSpecific filtering
			if !dbRecord.NodeID.Valid || (dbRecord.NodeID.Int64 == tx.GetNodeID()) {
				// Get listen address
				forwardID := int64(dbRecord.ID)
				fwdListenAddresses[forwardID] = dbRecord.ListenAddress
			}
		}

		return nil
	})
	if err != nil {
		return fmt.Errorf("Failed loading network forwards: %w", err)
	}

	fwdListenAddressesByFamily := map[uint][]string{
		4: make([]string, 0),
		6: make([]string, 0),
	}

	for _, fwdListenAddress := range fwdListenAddresses {
		if strings.Contains(fwdListenAddress, ":") {
			fwdListenAddressesByFamily[6] = append(fwdListenAddressesByFamily[6], fwdListenAddress)
		} else {
			fwdListenAddressesByFamily[4] = append(fwdListenAddressesByFamily[4], fwdListenAddress)
		}
	}

	// Use forward specific owner string (different from the network prefixes) so that these can be reapplied
	// independently of the network's own prefixes.
	bgpOwner := fmt.Sprintf("network_%d_forward", n.id)

	// Clear existing address forward prefixes for network.
	err = n.state.BGP.RemovePrefixByOwner(bgpOwner)
	if err != nil {
		return err
	}

	// Add the new prefixes.
	for _, ipVersion := range []uint{4, 6} {
		nextHopAddr := n.bgpNextHopAddress(ipVersion)
		natEnabled := util.IsTrue(n.config[fmt.Sprintf("ipv%d.nat", ipVersion)])
		_, netSubnet, _ := net.ParseCIDR(n.config[fmt.Sprintf("ipv%d.address", ipVersion)])

		routeSubnetSize := 128
		if ipVersion == 4 {
			routeSubnetSize = 32
		}

		// Export external forward listen addresses.
		for _, fwdListenAddress := range fwdListenAddressesByFamily[ipVersion] {
			fwdListenAddr := net.ParseIP(fwdListenAddress)

			// Don't export internal address forwards (those inside the NAT enabled network's subnet).
			if natEnabled && netSubnet != nil && netSubnet.Contains(fwdListenAddr) {
				continue
			}

			_, ipRouteSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", fwdListenAddr.String(), routeSubnetSize))
			if err != nil {
				return err
			}

			err = n.state.BGP.AddPrefix(*ipRouteSubnet, nextHopAddr, bgpOwner)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// getExternalSubnetInUse returns information about usage of external subnets by networks connected to, or used by,
// the specified uplinkNetworkName.
func (n *common) getExternalSubnetInUse(ctx context.Context, tx *db.ClusterTx, uplinkNetworkName string, memberSpecific bool) ([]externalSubnetUsage, error) {
	// Get a list of related networks.
	relatedNetworks := map[int64]*api.Network{}

	networksByProject, err := tx.GetNetworksAllProjects(ctx)
	if err != nil {
		return nil, fmt.Errorf("Failed loading network load balancer listen addresses: %w", err)
	}

	for projectName, networks := range networksByProject {
		for _, networkName := range networks {
			// Load the network.
			networkID, apiNetwork, _, err := tx.GetNetworkInAnyState(ctx, projectName, networkName)
			if err != nil {
				return nil, fmt.Errorf("Failed to load network: %w", err)
			}

			// Check if we're looking at our uplink.
			if projectName == api.ProjectDefaultName && uplinkNetworkName == networkName {
				relatedNetworks[networkID] = apiNetwork
				continue
			}

			// Check if the network shares the same uplink.
			if apiNetwork.Config["network"] == uplinkNetworkName {
				relatedNetworks[networkID] = apiNetwork
				continue
			}
		}
	}

	// Get all network load balancer and forward listen addresses for all networks (of any type) connected to our uplink.
	projectNetworksLoadBalancersOnUplink := map[string]map[string][]string{}
	projectNetworksForwardsOnUplink := map[string]map[string][]string{}

	for networkID, relatedNetwork := range relatedNetworks {
		// Get all load balancers associated with this network.
		loadBalancers, err := dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
			NetworkID: &networkID,
		})
		if err != nil {
			return nil, fmt.Errorf("Failed getting list of network load balancer: %w", err)
		}

		for _, lb := range loadBalancers {
			if projectNetworksLoadBalancersOnUplink[relatedNetwork.Project] == nil {
				projectNetworksLoadBalancersOnUplink[relatedNetwork.Project] = map[string][]string{}
			}

			projectNetworksLoadBalancersOnUplink[relatedNetwork.Project][relatedNetwork.Name] = append(projectNetworksLoadBalancersOnUplink[relatedNetwork.Project][relatedNetwork.Name], lb.ListenAddress)
		}

		// Get all network forwards associated with this network.
		networkForwards, err := dbCluster.GetNetworkForwards(ctx, tx.Tx(), dbCluster.NetworkForwardFilter{
			NetworkID: &networkID,
		})
		if err != nil {
			return nil, fmt.Errorf("Failed getting list of network forward: %w", err)
		}

		for _, fwd := range networkForwards {
			if !memberSpecific || (!fwd.NodeID.Valid || (fwd.NodeID.Int64 == tx.GetNodeID())) {
				if projectNetworksForwardsOnUplink[relatedNetwork.Project] == nil {
					projectNetworksForwardsOnUplink[relatedNetwork.Project] = map[string][]string{}
				}

				projectNetworksForwardsOnUplink[relatedNetwork.Project][relatedNetwork.Name] = append(projectNetworksForwardsOnUplink[relatedNetwork.Project][relatedNetwork.Name], fwd.ListenAddress)
			}
		}
	}

	externalSubnets := make([]externalSubnetUsage, 0, len(projectNetworksForwardsOnUplink)+len(projectNetworksLoadBalancersOnUplink))

	// Add forward listen addresses to this list.
	for projectName, networks := range projectNetworksForwardsOnUplink {
		for networkName, listenAddresses := range networks {
			for _, listenAddress := range listenAddresses {
				// Convert listen address to subnet.
				listenAddressNet, err := ParseIPToNet(listenAddress)
				if err != nil {
					return nil, fmt.Errorf("Invalid existing forward listen address %q", listenAddress)
				}

				// Create an externalSubnetUsage for the listen address by using the network ID
				// of the listen address to retrieve the already loaded network name from the
				// projectNetworks map.
				externalSubnets = append(externalSubnets, externalSubnetUsage{
					subnet:         *listenAddressNet,
					networkProject: projectName,
					networkName:    networkName,
					usageType:      subnetUsageNetworkForward,
				})
			}
		}
	}

	// Add load balancer listen addresses to this list.
	for projectName, networks := range projectNetworksLoadBalancersOnUplink {
		for networkName, listenAddresses := range networks {
			for _, listenAddress := range listenAddresses {
				// Convert listen address to subnet.
				listenAddressNet, err := ParseIPToNet(listenAddress)
				if err != nil {
					return nil, fmt.Errorf("Invalid existing load balancer listen address %q", listenAddress)
				}

				// Create an externalSubnetUsage for the listen address by using the network ID
				// of the listen address to retrieve the already loaded network name from the
				// projectNetworks map.
				externalSubnets = append(externalSubnets, externalSubnetUsage{
					subnet:         *listenAddressNet,
					networkProject: projectName,
					networkName:    networkName,
					usageType:      subnetUsageNetworkLoadBalancer,
				})
			}
		}
	}

	return externalSubnets, nil
}

// loadBalancerValidate validates the load balancer request.
func (n *common) loadBalancerValidate(listenAddress net.IP, forward *api.NetworkLoadBalancerPut) ([]*loadBalancerPortMap, error) {
	if listenAddress == nil {
		return nil, errors.New("Invalid listen address")
	}

	listenIsIP4 := listenAddress.To4() != nil

	// For checking target addresses are within network's subnet.
	netIPKey := "ipv4.address"
	if !listenIsIP4 {
		netIPKey = "ipv6.address"
	}

	netIPAddress := n.config[netIPKey]

	var err error
	var netSubnet *net.IPNet
	if netIPAddress != "" {
		_, netSubnet, err = net.ParseCIDR(n.config[netIPKey])
		if err != nil {
			return nil, err
		}
	}

	// Check the configuration.
	lbOptions := map[string]func(value string) error{
		// gendoc:generate(entity=network_load_balancer, group=common, key=healthcheck)
		//
		// ---
		//  type: bool
		//  defaultdesc: `false`
		//  shortdesc: Whether to perform checks on the backends
		"healthcheck": validate.Optional(validate.IsBool),

		// gendoc:generate(entity=network_load_balancer, group=common, key=healthcheck.interval)
		//
		// ---
		//  type: integer
		//  shortdesc: Interval in seconds between health checks
		//  defaultdesc: `10`
		"healthcheck.interval": validate.IsUint32,

		// gendoc:generate(entity=network_load_balancer, group=common, key=healthcheck.success_count)
		//
		// ---
		//  type: integer
		//  shortdesc: Number of successful tests to consider the backend online
		//  defaultdesc: `3`
		"healthcheck.success_count": validate.IsUint32,

		// gendoc:generate(entity=network_load_balancer, group=common, key=healthcheck.failure_count)
		//
		// ---
		//  type: integer
		//  shortdesc: Number of failed tests to consider the backend offline
		//  defaultdesc: `3`
		"healthcheck.failure_count": validate.IsUint32,

		// gendoc:generate(entity=network_load_balancer, group=common, key=healthcheck.timeout)
		//
		// ---
		//  type: integer
		//  shortdesc: Test timeout
		//  defaultdesc: `30`
		"healthcheck.timeout": validate.IsUint32,
	}

	for k, v := range forward.Config {
		// User keys are not validated.

		// gendoc:generate(entity=network_load_balancer, group=common, key=user.*)
		// User keys can be used in search.
		// ---
		//  type: string
		//  shortdesc: Free form user key/value storage
		if internalInstance.IsUserConfig(k) {
			continue
		}

		checker, ok := lbOptions[k]
		if ok {
			err := checker(v)
			if err != nil {
				return nil, err
			}

			continue
		}

		return nil, fmt.Errorf("Invalid option %q", k)
	}

	// Validate port rules.
	validPortProcols := []string{"tcp", "udp"}

	// Used to ensure that each listen port is only used once.
	listenPorts := map[string]map[int64]struct{}{
		"tcp": make(map[int64]struct{}),
		"udp": make(map[int64]struct{}),
	}

	// Check backends config and store the parsed target by backend name.
	backendsByName := make(map[string]*forwardTarget, len(forward.Backends))
	for backendSpecID, backendSpec := range forward.Backends {
		for _, r := range backendSpec.Name {
			if unicode.IsSpace(r) {
				return nil, fmt.Errorf("Name cannot contain white space in backend specification %d", backendSpecID)
			}
		}

		_, found := backendsByName[backendSpec.Name]
		if found {
			return nil, fmt.Errorf("Duplicate name %q in backend specification %d", backendSpec.Name, backendSpecID)
		}

		targetAddress := net.ParseIP(backendSpec.TargetAddress)
		if targetAddress == nil {
			return nil, fmt.Errorf("Invalid target address for backend %q", backendSpec.Name)
		}

		targetIsIP4 := targetAddress.To4() != nil
		if listenIsIP4 != targetIsIP4 {
			return nil, fmt.Errorf("Cannot mix IP versions in listen address and backend %q target address", backendSpec.Name)
		}

		// Check target address is within network's subnet.
		if netSubnet != nil && !SubnetContainsIP(netSubnet, targetAddress) {
			return nil, fmt.Errorf("Target address is not within the network subnet for backend %q", backendSpec.Name)
		}

		// Check valid target port(s) supplied.
		target := forwardTarget{
			address: targetAddress,
		}

		for portSpecID, portSpec := range util.SplitNTrimSpace(backendSpec.TargetPort, ",", -1, true) {
			portFirst, portRange, err := ParsePortRange(portSpec)
			if err != nil {
				return nil, fmt.Errorf("Invalid backend port specification %d in backend specification %d: %w", portSpecID, backendSpecID, err)
			}

			for i := range portRange {
				port := portFirst + i
				target.ports = append(target.ports, uint64(port))
			}
		}

		backendsByName[backendSpec.Name] = &target
	}

	// Check ports config.
	portMaps := make([]*loadBalancerPortMap, 0, len(forward.Ports))
	for portSpecID, portSpec := range forward.Ports {
		if !slices.Contains(validPortProcols, portSpec.Protocol) {
			return nil, fmt.Errorf("Invalid port protocol in port specification %d, protocol must be one of: %s", portSpecID, strings.Join(validPortProcols, ", "))
		}

		// Check valid listen port(s) supplied.
		listenPortRanges := util.SplitNTrimSpace(portSpec.ListenPort, ",", -1, true)
		if len(listenPortRanges) <= 0 {
			return nil, fmt.Errorf("Missing listen port in port specification %d", portSpecID)
		}

		portMap := loadBalancerPortMap{
			listenPorts: make([]uint64, 0),
			protocol:    portSpec.Protocol,
			targets:     make([]forwardTarget, 0, len(portSpec.TargetBackend)),
		}

		for _, pr := range listenPortRanges {
			portFirst, portRange, err := ParsePortRange(pr)
			if err != nil {
				return nil, fmt.Errorf("Invalid listen port in port specification %d: %w", portSpecID, err)
			}

			for i := range portRange {
				port := portFirst + i
				_, found := listenPorts[portSpec.Protocol][port]
				if found {
					return nil, fmt.Errorf("Duplicate listen port %d for protocol %q in port specification %d", port, portSpec.Protocol, portSpecID)
				}

				listenPorts[portSpec.Protocol][port] = struct{}{}
				portMap.listenPorts = append(portMap.listenPorts, uint64(port))
			}
		}

		// Check each of the backends specified are compatible with the listen ports.
		for _, backendName := range portSpec.TargetBackend {
			// Check backend exists.
			backend, found := backendsByName[backendName]
			if !found {
				return nil, fmt.Errorf("Invalid target backend name %q in port specification %d", backendName, portSpecID)
			}

			// Only check if the target port count matches the listen port count if the target ports
			// are greater than 1, because we allow many-to-one type mapping and one-to-one mapping if
			// no target ports specified.
			portSpectTargetPortsLen := len(backend.ports)
			if portSpectTargetPortsLen > 1 && len(portMap.listenPorts) != portSpectTargetPortsLen {
				return nil, fmt.Errorf("Mismatch of listen port(s) and target port(s) count for backend %q in port specification %d", backendName, portSpecID)
			}

			portMap.targets = append(portMap.targets, *backend)
		}

		portMaps = append(portMaps, &portMap)
	}

	return portMaps, err
}

// LoadBalancerCreate returns ErrNotImplemented for drivers that do not support load balancers.
func (n *common) LoadBalancerCreate(loadBalancer api.NetworkLoadBalancersPost, clientType request.ClientType) error {
	return ErrNotImplemented
}

// LoadBalancerUpdate returns ErrNotImplemented for drivers that do not support load balancers..
func (n *common) LoadBalancerUpdate(listenAddress string, newLoadBalancer api.NetworkLoadBalancerPut, clientType request.ClientType) error {
	return ErrNotImplemented
}

// LoadBalancerState returns ErrNotImplemented for drivers that do not support load balancers..
func (n *common) LoadBalancerState(loadBalancer api.NetworkLoadBalancer) (*api.NetworkLoadBalancerState, error) {
	return nil, ErrNotImplemented
}

// LoadBalancerDelete returns ErrNotImplemented for drivers that do not support load balancers..
func (n *common) LoadBalancerDelete(listenAddress string, clientType request.ClientType) error {
	return ErrNotImplemented
}

// Leases returns ErrNotImplemented for drivers that don't support address leases.
func (n *common) Leases(projectName string, clientType request.ClientType) ([]api.NetworkLease, error) {
	return nil, ErrNotImplemented
}

// PeerCrete returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) PeerCreate(forward api.NetworkPeersPost) error {
	return ErrNotImplemented
}

// PeerUpdate returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) PeerUpdate(peerName string, newPeer api.NetworkPeerPut) error {
	return ErrNotImplemented
}

// PeerDelete returns ErrNotImplemented for drivers that do not support forwards.
func (n *common) PeerDelete(peerName string) error {
	return ErrNotImplemented
}

// peerValidate validates the peer request.
func (n *common) peerValidate(peerName string, peer *api.NetworkPeerPut) error {
	err := acl.ValidName(peerName)
	if err != nil {
		return err
	}

	if slices.Contains(acl.ReservedNetworkSubects, peerName) {
		return fmt.Errorf("Name cannot be one of the reserved network subjects: %v", acl.ReservedNetworkSubects)
	}

	// Look for any unknown config fields.
	for k := range peer.Config {
		if k == "target_address" {
			continue
		}

		// User keys are not validated.
		if internalInstance.IsUserConfig(k) {
			continue
		}

		return fmt.Errorf("Invalid option %q", k)
	}

	return nil
}

// PeerUsedBy returns a list of API endpoints referencing this peer.
func (n *common) PeerUsedBy(peerName string) ([]string, error) {
	return n.peerUsedBy(peerName, false)
}

// isUsed returns whether or not the peer is in use.
func (n *common) peerIsUsed(peerName string) (bool, error) {
	usedBy, err := n.peerUsedBy(peerName, true)
	if err != nil {
		return false, err
	}

	return len(usedBy) > 0, nil
}

// peerUsedBy returns a list of API endpoints referencing this peer.
func (n *common) peerUsedBy(peerName string, firstOnly bool) ([]string, error) {
	usedBy := []string{}

	rulesUsePeer := func(rules []api.NetworkACLRule) bool {
		for _, rule := range rules {
			for _, subject := range util.SplitNTrimSpace(rule.Source, ",", -1, true) {
				if !strings.HasPrefix(subject, "@") {
					continue
				}

				peerParts := strings.SplitN(strings.TrimPrefix(subject, "@"), "/", 2)
				if len(peerParts) != 2 {
					continue // Not a valid network/peer name combination.
				}

				peer := dbCluster.NetworkPeerConnection{
					NetworkName: peerParts[0],
					PeerName:    peerParts[1],
				}

				if peer.NetworkName == n.Name() && peer.PeerName == peerName {
					return true
				}
			}
		}

		return false
	}

	var aclNames []string

	err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
		projectName := n.Project()

		acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &projectName})
		if err != nil {
			return err
		}

		aclNames = make([]string, len(acls))
		for i, acl := range acls {
			aclNames[i] = acl.Name
		}

		return nil
	})
	if err != nil {
		return nil, err
	}

	for _, aclName := range aclNames {
		var aclInfo *api.NetworkACL

		err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
			_, aclInfo, err = dbCluster.GetNetworkACLAPI(ctx, tx.Tx(), n.Project(), aclName)

			return err
		})
		if err != nil {
			return nil, err
		}

		// Ingress rules can specify peer names in their Source subjects.
		for _, rules := range [][]api.NetworkACLRule{aclInfo.Ingress, aclInfo.Egress} {
			if rulesUsePeer(rules) {
				usedBy = append(usedBy, api.NewURL().Project(n.Project()).Path(version.APIVersion, "network-acls", aclName).String())

				if firstOnly {
					return usedBy, err
				}

				break
			}
		}
	}

	return usedBy, nil
}

func (n *common) State() (*api.NetworkState, error) {
	return resources.GetNetworkState(n.name)
}

func (n *common) setUnavailable() {
	pn := ProjectNetwork{
		ProjectName: n.Project(),
		NetworkName: n.Name(),
	}

	unavailableNetworksMu.Lock()
	unavailableNetworks[pn] = struct{}{}
	unavailableNetworksMu.Unlock()
}

func (n *common) setAvailable() {
	pn := ProjectNetwork{
		ProjectName: n.Project(),
		NetworkName: n.Name(),
	}

	unavailableNetworksMu.Lock()
	delete(unavailableNetworks, pn)
	unavailableNetworksMu.Unlock()
}