libnetwork: remove Network interface

There's only one implementation; drop the interface and use the
concrete type instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-07-22 00:38:57 +02:00
parent 454b6a7cf5
commit 64c6f72988
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C
31 changed files with 266 additions and 295 deletions

View file

@ -12,7 +12,7 @@ import (
// Backend is all the methods that need to be implemented // Backend is all the methods that need to be implemented
// to provide network specific functionality. // to provide network specific functionality.
type Backend interface { type Backend interface {
FindNetwork(idName string) (libnetwork.Network, error) FindNetwork(idName string) (*libnetwork.Network, error)
GetNetworks(filters.Args, types.NetworkListConfig) ([]types.NetworkResource, error) GetNetworks(filters.Args, types.NetworkListConfig) ([]types.NetworkResource, error)
CreateNetwork(nc types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) CreateNetwork(nc types.NetworkCreateRequest) (*types.NetworkCreateResponse, error)
ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error

View file

@ -95,7 +95,7 @@ type lnInterface struct {
provider *bridgeProvider provider *bridgeProvider
} }
func (iface *lnInterface) init(c *libnetwork.Controller, n libnetwork.Network) { func (iface *lnInterface) init(c *libnetwork.Controller, n *libnetwork.Network) {
defer close(iface.ready) defer close(iface.ready)
id := identity.NewID() id := identity.NewID()

View file

@ -35,7 +35,7 @@ import (
type Backend interface { type Backend interface {
CreateManagedNetwork(clustertypes.NetworkCreateRequest) error CreateManagedNetwork(clustertypes.NetworkCreateRequest) error
DeleteManagedNetwork(networkID string) error DeleteManagedNetwork(networkID string) error
FindNetwork(idName string) (libnetwork.Network, error) FindNetwork(idName string) (*libnetwork.Network, error)
SetupIngress(clustertypes.NetworkCreateRequest, string) (<-chan struct{}, error) SetupIngress(clustertypes.NetworkCreateRequest, string) (<-chan struct{}, error)
ReleaseIngress() (<-chan struct{}, error) ReleaseIngress() (<-chan struct{}, error)
CreateManagedContainer(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error) CreateManagedContainer(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error)

View file

@ -247,7 +247,7 @@ func (daemon *Daemon) buildSandboxOptions(cfg *config.Config, container *contain
return sboxOptions, nil return sboxOptions, nil
} }
func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings) error { func (daemon *Daemon) updateNetworkSettings(container *container.Container, n *libnetwork.Network, endpointConfig *networktypes.EndpointSettings) error {
if container.NetworkSettings == nil { if container.NetworkSettings == nil {
container.NetworkSettings = &network.Settings{} container.NetworkSettings = &network.Settings{}
} }
@ -293,7 +293,7 @@ func (daemon *Daemon) updateNetworkSettings(container *container.Container, n li
return nil return nil
} }
func (daemon *Daemon) updateEndpointNetworkSettings(cfg *config.Config, container *container.Container, n libnetwork.Network, ep *libnetwork.Endpoint) error { func (daemon *Daemon) updateEndpointNetworkSettings(cfg *config.Config, container *container.Container, n *libnetwork.Network, ep *libnetwork.Endpoint) error {
if err := buildEndpointInfo(container.NetworkSettings, n, ep); err != nil { if err := buildEndpointInfo(container.NetworkSettings, n, ep); err != nil {
return err return err
} }
@ -320,7 +320,7 @@ func (daemon *Daemon) updateNetwork(cfg *config.Config, container *container.Con
} }
// Find if container is connected to the default bridge network // Find if container is connected to the default bridge network
var n libnetwork.Network var n *libnetwork.Network
for name, v := range container.NetworkSettings.Networks { for name, v := range container.NetworkSettings.Networks {
sn, err := daemon.FindNetwork(getNetworkID(name, v.EndpointSettings)) sn, err := daemon.FindNetwork(getNetworkID(name, v.EndpointSettings))
if err != nil { if err != nil {
@ -351,7 +351,7 @@ func (daemon *Daemon) updateNetwork(cfg *config.Config, container *container.Con
return nil return nil
} }
func (daemon *Daemon) findAndAttachNetwork(container *container.Container, idOrName string, epConfig *networktypes.EndpointSettings) (libnetwork.Network, *networktypes.NetworkingConfig, error) { func (daemon *Daemon) findAndAttachNetwork(container *container.Container, idOrName string, epConfig *networktypes.EndpointSettings) (*libnetwork.Network, *networktypes.NetworkingConfig, error) {
id := getNetworkID(idOrName, epConfig) id := getNetworkID(idOrName, epConfig)
n, err := daemon.FindNetwork(id) n, err := daemon.FindNetwork(id)
@ -451,7 +451,7 @@ func (daemon *Daemon) findAndAttachNetwork(container *container.Container, idOrN
// updateContainerNetworkSettings updates the network settings // updateContainerNetworkSettings updates the network settings
func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container, endpointsConfig map[string]*networktypes.EndpointSettings) { func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container, endpointsConfig map[string]*networktypes.EndpointSettings) {
var n libnetwork.Network var n *libnetwork.Network
mode := container.HostConfig.NetworkMode mode := container.HostConfig.NetworkMode
if container.Config.NetworkDisabled || mode.IsContainer() { if container.Config.NetworkDisabled || mode.IsContainer() {
@ -622,7 +622,7 @@ func hasUserDefinedIPAddress(ipamConfig *networktypes.EndpointIPAMConfig) bool {
} }
// User specified ip address is acceptable only for networks with user specified subnets. // User specified ip address is acceptable only for networks with user specified subnets.
func validateNetworkingConfig(n libnetwork.Network, epConfig *networktypes.EndpointSettings) error { func validateNetworkingConfig(n *libnetwork.Network, epConfig *networktypes.EndpointSettings) error {
if n == nil || epConfig == nil { if n == nil || epConfig == nil {
return nil return nil
} }
@ -684,7 +684,7 @@ func cleanOperationalData(es *network.EndpointSettings) {
} }
} }
func (daemon *Daemon) updateNetworkConfig(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings, updateSettings bool) error { func (daemon *Daemon) updateNetworkConfig(container *container.Container, n *libnetwork.Network, endpointConfig *networktypes.EndpointSettings, updateSettings bool) error {
if containertypes.NetworkMode(n.Name()).IsUserDefined() { if containertypes.NetworkMode(n.Name()).IsUserDefined() {
addShortID := true addShortID := true
shortID := stringid.TruncateID(container.ID) shortID := stringid.TruncateID(container.ID)
@ -835,7 +835,7 @@ func (daemon *Daemon) connectToNetwork(cfg *config.Config, container *container.
return nil return nil
} }
func updateJoinInfo(networkSettings *network.Settings, n libnetwork.Network, ep *libnetwork.Endpoint) error { func updateJoinInfo(networkSettings *network.Settings, n *libnetwork.Network, ep *libnetwork.Endpoint) error {
if ep == nil { if ep == nil {
return errors.New("invalid enppoint whhile building portmap info") return errors.New("invalid enppoint whhile building portmap info")
} }
@ -880,7 +880,7 @@ func (daemon *Daemon) ForceEndpointDelete(name string, networkName string) error
return ep.Delete(true) return ep.Delete(true)
} }
func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error { func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n *libnetwork.Network, force bool) error {
var ( var (
ep *libnetwork.Endpoint ep *libnetwork.Endpoint
sbox *libnetwork.Sandbox sbox *libnetwork.Sandbox
@ -932,7 +932,7 @@ func (daemon *Daemon) disconnectFromNetwork(container *container.Container, n li
return nil return nil
} }
func (daemon *Daemon) tryDetachContainerFromClusterNetwork(network libnetwork.Network, container *container.Container) { func (daemon *Daemon) tryDetachContainerFromClusterNetwork(network *libnetwork.Network, container *container.Container) {
if daemon.clusterProvider != nil && network.Info().Dynamic() && !container.Managed { if daemon.clusterProvider != nil && network.Info().Dynamic() && !container.Managed {
if err := daemon.clusterProvider.DetachNetwork(network.Name(), container.ID); err != nil { if err := daemon.clusterProvider.DetachNetwork(network.Name(), container.ID); err != nil {
log.G(context.TODO()).Warnf("error detaching from network %s: %v", network.Name(), err) log.G(context.TODO()).Warnf("error detaching from network %s: %v", network.Name(), err)
@ -1018,7 +1018,7 @@ func (daemon *Daemon) releaseNetwork(container *container.Container) {
return return
} }
var networks []libnetwork.Network var networks []*libnetwork.Network
for n, epSettings := range settings { for n, epSettings := range settings {
if nw, err := daemon.FindNetwork(getNetworkID(n, epSettings.EndpointSettings)); err == nil { if nw, err := daemon.FindNetwork(getNetworkID(n, epSettings.EndpointSettings)); err == nil {
networks = append(networks, nw) networks = append(networks, nw)

View file

@ -323,8 +323,8 @@ func (daemon *Daemon) initNetworkController(daemonCfg *config.Config, activeSand
if networkTypeNorm == "private" || networkTypeNorm == "internal" { if networkTypeNorm == "private" || networkTypeNorm == "internal" {
continue // workaround for HNS reporting unsupported networks continue // workaround for HNS reporting unsupported networks
} }
var n libnetwork.Network var n *libnetwork.Network
s := func(current libnetwork.Network) bool { s := func(current *libnetwork.Network) bool {
hnsid := current.Info().DriverOptions()[winlibnetwork.HNSID] hnsid := current.Info().DriverOptions()[winlibnetwork.HNSID]
if hnsid == v.Id { if hnsid == v.Id {
n = current n = current

View file

@ -67,12 +67,12 @@ func (daemon *Daemon) LogVolumeEvent(volumeID, action string, attributes map[str
} }
// LogNetworkEvent generates an event related to a network with only the default attributes. // LogNetworkEvent generates an event related to a network with only the default attributes.
func (daemon *Daemon) LogNetworkEvent(nw libnetwork.Network, action string) { func (daemon *Daemon) LogNetworkEvent(nw *libnetwork.Network, action string) {
daemon.LogNetworkEventWithAttributes(nw, action, map[string]string{}) daemon.LogNetworkEventWithAttributes(nw, action, map[string]string{})
} }
// LogNetworkEventWithAttributes generates an event related to a network with specific given attributes. // LogNetworkEventWithAttributes generates an event related to a network with specific given attributes.
func (daemon *Daemon) LogNetworkEventWithAttributes(nw libnetwork.Network, action string, attributes map[string]string) { func (daemon *Daemon) LogNetworkEventWithAttributes(nw *libnetwork.Network, action string, attributes map[string]string) {
attributes["name"] = nw.Name() attributes["name"] = nw.Name()
attributes["type"] = nw.Type() attributes["type"] = nw.Type()
actor := events.Actor{ actor := events.Actor{

View file

@ -61,9 +61,9 @@ func (daemon *Daemon) NetworkController() *libnetwork.Controller {
// 2. Full Name // 2. Full Name
// 3. Partial ID // 3. Partial ID
// as long as there is no ambiguity // as long as there is no ambiguity
func (daemon *Daemon) FindNetwork(term string) (libnetwork.Network, error) { func (daemon *Daemon) FindNetwork(term string) (*libnetwork.Network, error) {
listByFullName := []libnetwork.Network{} listByFullName := []*libnetwork.Network{}
listByPartialID := []libnetwork.Network{} listByPartialID := []*libnetwork.Network{}
for _, nw := range daemon.getAllNetworks() { for _, nw := range daemon.getAllNetworks() {
if nw.ID() == term { if nw.ID() == term {
return nw, nil return nw, nil
@ -94,7 +94,7 @@ func (daemon *Daemon) FindNetwork(term string) (libnetwork.Network, error) {
// GetNetworkByID function returns a network whose ID matches the given ID. // GetNetworkByID function returns a network whose ID matches the given ID.
// It fails with an error if no matching network is found. // It fails with an error if no matching network is found.
func (daemon *Daemon) GetNetworkByID(id string) (libnetwork.Network, error) { func (daemon *Daemon) GetNetworkByID(id string) (*libnetwork.Network, error) {
c := daemon.netController c := daemon.netController
if c == nil { if c == nil {
return nil, errors.Wrap(libnetwork.ErrNoSuchNetwork(id), "netcontroller is nil") return nil, errors.Wrap(libnetwork.ErrNoSuchNetwork(id), "netcontroller is nil")
@ -104,7 +104,7 @@ func (daemon *Daemon) GetNetworkByID(id string) (libnetwork.Network, error) {
// GetNetworkByName function returns a network for a given network name. // GetNetworkByName function returns a network for a given network name.
// If no network name is given, the default network is returned. // If no network name is given, the default network is returned.
func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) { func (daemon *Daemon) GetNetworkByName(name string) (*libnetwork.Network, error) {
c := daemon.netController c := daemon.netController
if c == nil { if c == nil {
return nil, libnetwork.ErrNoSuchNetwork(name) return nil, libnetwork.ErrNoSuchNetwork(name)
@ -116,13 +116,13 @@ func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error)
} }
// GetNetworksByIDPrefix returns a list of networks whose ID partially matches zero or more networks // GetNetworksByIDPrefix returns a list of networks whose ID partially matches zero or more networks
func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []libnetwork.Network { func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []*libnetwork.Network {
c := daemon.netController c := daemon.netController
if c == nil { if c == nil {
return nil return nil
} }
list := []libnetwork.Network{} list := []*libnetwork.Network{}
l := func(nw libnetwork.Network) bool { l := func(nw *libnetwork.Network) bool {
if strings.HasPrefix(nw.ID(), partialID) { if strings.HasPrefix(nw.ID(), partialID) {
list = append(list, nw) list = append(list, nw)
} }
@ -134,7 +134,7 @@ func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []libnetwork.Netwo
} }
// getAllNetworks returns a list containing all networks // getAllNetworks returns a list containing all networks
func (daemon *Daemon) getAllNetworks() []libnetwork.Network { func (daemon *Daemon) getAllNetworks() []*libnetwork.Network {
c := daemon.netController c := daemon.netController
if c == nil { if c == nil {
return nil return nil
@ -527,7 +527,7 @@ func (daemon *Daemon) DeleteNetwork(networkID string) error {
return daemon.deleteNetwork(n, false) return daemon.deleteNetwork(n, false)
} }
func (daemon *Daemon) deleteNetwork(nw libnetwork.Network, dynamic bool) error { func (daemon *Daemon) deleteNetwork(nw *libnetwork.Network, dynamic bool) error {
if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic { if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic {
err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name()) err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name())
return errdefs.Forbidden(err) return errdefs.Forbidden(err)
@ -564,9 +564,9 @@ func (daemon *Daemon) GetNetworks(filter filters.Args, config types.NetworkListC
networks := daemon.getAllNetworks() networks := daemon.getAllNetworks()
list := make([]types.NetworkResource, 0, len(networks)) list := make([]types.NetworkResource, 0, len(networks))
var idx map[string]libnetwork.Network var idx map[string]*libnetwork.Network
if config.Detailed { if config.Detailed {
idx = make(map[string]libnetwork.Network) idx = make(map[string]*libnetwork.Network)
} }
for _, n := range networks { for _, n := range networks {
@ -594,7 +594,7 @@ func (daemon *Daemon) GetNetworks(filter filters.Args, config types.NetworkListC
return list, nil return list, nil
} }
func buildNetworkResource(nw libnetwork.Network) types.NetworkResource { func buildNetworkResource(nw *libnetwork.Network) types.NetworkResource {
r := types.NetworkResource{} r := types.NetworkResource{}
if nw == nil { if nw == nil {
return r return r
@ -628,7 +628,7 @@ func buildNetworkResource(nw libnetwork.Network) types.NetworkResource {
return r return r
} }
func buildDetailedNetworkResources(r *types.NetworkResource, nw libnetwork.Network, verbose bool) { func buildDetailedNetworkResources(r *types.NetworkResource, nw *libnetwork.Network, verbose bool) {
if nw == nil { if nw == nil {
return return
} }
@ -797,7 +797,7 @@ func (daemon *Daemon) clearAttachableNetworks() {
} }
// buildCreateEndpointOptions builds endpoint options from a given network. // buildCreateEndpointOptions builds endpoint options from a given network.
func buildCreateEndpointOptions(c *container.Container, n libnetwork.Network, epConfig *network.EndpointSettings, sb *libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) { func buildCreateEndpointOptions(c *container.Container, n *libnetwork.Network, epConfig *network.EndpointSettings, sb *libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) {
var ( var (
bindings = make(nat.PortMap) bindings = make(nat.PortMap)
pbList []networktypes.PortBinding pbList []networktypes.PortBinding
@ -1028,7 +1028,7 @@ func getEndpointPortMapInfo(ep *libnetwork.Endpoint) (nat.PortMap, error) {
} }
// buildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint. // buildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
func buildEndpointInfo(networkSettings *internalnetwork.Settings, n libnetwork.Network, ep *libnetwork.Endpoint) error { func buildEndpointInfo(networkSettings *internalnetwork.Settings, n *libnetwork.Network, ep *libnetwork.Endpoint) error {
if ep == nil { if ep == nil {
return errors.New("endpoint cannot be nil") return errors.New("endpoint cannot be nil")
} }

View file

@ -7,7 +7,7 @@ import (
) )
// getEndpointInNetwork returns the container's endpoint to the provided network. // getEndpointInNetwork returns the container's endpoint to the provided network.
func getEndpointInNetwork(name string, n libnetwork.Network) (*libnetwork.Endpoint, error) { func getEndpointInNetwork(name string, n *libnetwork.Network) (*libnetwork.Endpoint, error) {
endpointName := strings.TrimPrefix(name, "/") endpointName := strings.TrimPrefix(name, "/")
return n.EndpointByName(endpointName) return n.EndpointByName(endpointName)
} }

View file

@ -102,7 +102,7 @@ func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filte
until, _ := getUntilFromPruneFilters(pruneFilters) until, _ := getUntilFromPruneFilters(pruneFilters)
// When the function returns true, the walk will stop. // When the function returns true, the walk will stop.
l := func(nw libnetwork.Network) bool { daemon.netController.WalkNetworks(func(nw *libnetwork.Network) bool {
select { select {
case <-ctx.Done(): case <-ctx.Done():
// context cancelled // context cancelled
@ -131,8 +131,7 @@ func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filte
} }
rep.NetworksDeleted = append(rep.NetworksDeleted, nwName) rep.NetworksDeleted = append(rep.NetworksDeleted, nwName)
return false return false
} })
daemon.netController.WalkNetworks(l)
return rep return rep
} }

View file

@ -436,7 +436,7 @@ type epRecord struct {
lbIndex int lbIndex int
} }
func (n *network) Services() map[string]ServiceInfo { func (n *Network) Services() map[string]ServiceInfo {
eps := make(map[string]epRecord) eps := make(map[string]epRecord)
if !n.isClusterEligible() { if !n.isClusterEligible() {
@ -519,14 +519,14 @@ func (n *network) Services() map[string]ServiceInfo {
return sinfo return sinfo
} }
func (n *network) isClusterEligible() bool { func (n *Network) isClusterEligible() bool {
if n.scope != datastore.SwarmScope || !n.driverIsMultihost() { if n.scope != datastore.SwarmScope || !n.driverIsMultihost() {
return false return false
} }
return n.getController().getAgent() != nil return n.getController().getAgent() != nil
} }
func (n *network) joinCluster() error { func (n *Network) joinCluster() error {
if !n.isClusterEligible() { if !n.isClusterEligible() {
return nil return nil
} }
@ -539,7 +539,7 @@ func (n *network) joinCluster() error {
return agent.networkDB.JoinNetwork(n.ID()) return agent.networkDB.JoinNetwork(n.ID())
} }
func (n *network) leaveCluster() error { func (n *Network) leaveCluster() error {
if !n.isClusterEligible() { if !n.isClusterEligible() {
return nil return nil
} }
@ -743,7 +743,7 @@ func (ep *Endpoint) deleteServiceInfoFromCluster(sb *Sandbox, fullRemove bool, m
return nil return nil
} }
func disableServiceInNetworkDB(a *agent, n *network, ep *Endpoint) { func disableServiceInNetworkDB(a *agent, n *Network, ep *Endpoint) {
var epRec EndpointRecord var epRec EndpointRecord
log.G(context.TODO()).Debugf("disableServiceInNetworkDB for %s %s", ep.svcName, ep.ID()) log.G(context.TODO()).Debugf("disableServiceInNetworkDB for %s %s", ep.svcName, ep.ID())
@ -772,7 +772,7 @@ func disableServiceInNetworkDB(a *agent, n *network, ep *Endpoint) {
} }
} }
func (n *network) addDriverWatches() { func (n *Network) addDriverWatches() {
if !n.isClusterEligible() { if !n.isClusterEligible() {
return return
} }
@ -808,7 +808,7 @@ func (n *network) addDriverWatches() {
} }
} }
func (n *network) cancelDriverWatches() { func (n *Network) cancelDriverWatches() {
if !n.isClusterEligible() { if !n.isClusterEligible() {
return return
} }
@ -839,7 +839,7 @@ func (c *Controller) handleTableEvents(ch *events.Channel, fn func(events.Event)
} }
} }
func (n *network) handleDriverTableEvent(ev events.Event) { func (n *Network) handleDriverTableEvent(ev events.Event) {
d, err := n.driver(false) d, err := n.driver(false)
if err != nil { if err != nil {
log.G(context.TODO()).Errorf("Could not resolve driver %s while handling driver table event: %v", n.networkType, err) log.G(context.TODO()).Errorf("Could not resolve driver %s while handling driver table event: %v", n.networkType, err)

View file

@ -76,7 +76,7 @@ import (
// NetworkWalker is a client provided function which will be used to walk the Networks. // NetworkWalker is a client provided function which will be used to walk the Networks.
// When the function returns true, the walk will stop. // When the function returns true, the walk will stop.
type NetworkWalker func(nw Network) bool type NetworkWalker func(nw *Network) bool
// SandboxWalker is a client provided function which will be used to walk the Sandboxes. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
// When the function returns true, the walk will stop. // When the function returns true, the walk will stop.
@ -461,11 +461,11 @@ const overlayDSROptionString = "dsr"
// NewNetwork creates a new network of the specified network type. The options // NewNetwork creates a new network of the specified network type. The options
// are network specific and modeled in a generic way. // are network specific and modeled in a generic way.
func (c *Controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) { func (c *Controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (*Network, error) {
var ( var (
caps driverapi.Capability caps driverapi.Capability
err error err error
t *network t *Network
skipCfgEpCount bool skipCfgEpCount bool
) )
@ -488,7 +488,7 @@ func (c *Controller) NewNetwork(networkType, name string, id string, options ...
defaultIpam := defaultIpamForNetworkType(networkType) defaultIpam := defaultIpamForNetworkType(networkType)
// Construct the network object // Construct the network object
nw := &network{ nw := &Network{
name: name, name: name,
networkType: networkType, networkType: networkType,
generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)}, generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
@ -603,7 +603,7 @@ func (c *Controller) NewNetwork(networkType, name string, id string, options ...
// time pressure to get this in without adding changes to moby, // time pressure to get this in without adding changes to moby,
// swarm and CLI, it is being implemented as a driver-specific // swarm and CLI, it is being implemented as a driver-specific
// option. Unfortunately, drivers can't influence the core // option. Unfortunately, drivers can't influence the core
// "libnetwork.network" data type. Hence we need this hack code // "libnetwork.Network" data type. Hence we need this hack code
// to implement in this manner. // to implement in this manner.
if gval, ok := nw.generic[netlabel.GenericData]; ok && nw.networkType == "overlay" { if gval, ok := nw.generic[netlabel.GenericData]; ok && nw.networkType == "overlay" {
optMap := gval.(map[string]string) optMap := gval.(map[string]string)
@ -670,15 +670,14 @@ addToStore:
return nw, nil return nw, nil
} }
var joinCluster NetworkWalker = func(nw Network) bool { var joinCluster NetworkWalker = func(nw *Network) bool {
n := nw.(*network) if nw.configOnly {
if n.configOnly {
return false return false
} }
if err := n.joinCluster(); err != nil { if err := nw.joinCluster(); err != nil {
log.G(context.TODO()).Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err) log.G(context.TODO()).Errorf("Failed to join network %s (%s) into agent cluster: %v", nw.Name(), nw.ID(), err)
} }
n.addDriverWatches() nw.addDriverWatches()
return false return false
} }
@ -746,7 +745,7 @@ func (c *Controller) reservePools() {
} }
} }
func doReplayPoolReserve(n *network) bool { func doReplayPoolReserve(n *Network) bool {
_, caps, err := n.getController().getIPAMDriver(n.ipamType) _, caps, err := n.getController().getIPAMDriver(n.ipamType)
if err != nil { if err != nil {
log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err) log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
@ -755,7 +754,7 @@ func doReplayPoolReserve(n *network) bool {
return caps.RequiresRequestReplay return caps.RequiresRequestReplay
} }
func (c *Controller) addNetwork(n *network) error { func (c *Controller) addNetwork(n *Network) error {
d, err := n.driver(true) d, err := n.driver(true)
if err != nil { if err != nil {
return err return err
@ -772,8 +771,8 @@ func (c *Controller) addNetwork(n *network) error {
} }
// Networks returns the list of Network(s) managed by this controller. // Networks returns the list of Network(s) managed by this controller.
func (c *Controller) Networks() []Network { func (c *Controller) Networks() []*Network {
var list []Network var list []*Network
for _, n := range c.getNetworksFromStore() { for _, n := range c.getNetworksFromStore() {
if n.inDelete { if n.inDelete {
@ -796,21 +795,19 @@ func (c *Controller) WalkNetworks(walker NetworkWalker) {
// NetworkByName returns the Network which has the passed name. // NetworkByName returns the Network which has the passed name.
// If not found, the error [ErrNoSuchNetwork] is returned. // If not found, the error [ErrNoSuchNetwork] is returned.
func (c *Controller) NetworkByName(name string) (Network, error) { func (c *Controller) NetworkByName(name string) (*Network, error) {
if name == "" { if name == "" {
return nil, ErrInvalidName(name) return nil, ErrInvalidName(name)
} }
var n Network var n *Network
s := func(current Network) bool { c.WalkNetworks(func(current *Network) bool {
if current.Name() == name { if current.Name() == name {
n = current n = current
return true return true
} }
return false return false
} })
c.WalkNetworks(s)
if n == nil { if n == nil {
return nil, ErrNoSuchNetwork(name) return nil, ErrNoSuchNetwork(name)
@ -821,7 +818,7 @@ func (c *Controller) NetworkByName(name string) (Network, error) {
// NetworkByID returns the Network which has the passed id. // NetworkByID returns the Network which has the passed id.
// If not found, the error [ErrNoSuchNetwork] is returned. // If not found, the error [ErrNoSuchNetwork] is returned.
func (c *Controller) NetworkByID(id string) (Network, error) { func (c *Controller) NetworkByID(id string) (*Network, error) {
if id == "" { if id == "" {
return nil, ErrInvalidID(id) return nil, ErrInvalidID(id)
} }

View file

@ -162,7 +162,7 @@ func (ep *Endpoint) endpointInGWNetwork() bool {
// Looks for the default gw network and creates it if not there. // Looks for the default gw network and creates it if not there.
// Parallel executions are serialized. // Parallel executions are serialized.
func (c *Controller) defaultGwNetwork() (Network, error) { func (c *Controller) defaultGwNetwork() (*Network, error) {
procGwNetwork <- true procGwNetwork <- true
defer func() { <-procGwNetwork }() defer func() { <-procGwNetwork }()

View file

@ -8,6 +8,6 @@ func getPlatformOption() EndpointOption {
return nil return nil
} }
func (c *Controller) createGWNetwork() (Network, error) { func (c *Controller) createGWNetwork() (*Network, error) {
return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in freebsd") return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in freebsd")
} }

View file

@ -13,15 +13,13 @@ func getPlatformOption() EndpointOption {
return nil return nil
} }
func (c *Controller) createGWNetwork() (Network, error) { func (c *Controller) createGWNetwork() (*Network, error) {
netOption := map[string]string{
bridge.BridgeName: libnGWNetwork,
bridge.EnableICC: strconv.FormatBool(false),
bridge.EnableIPMasquerade: strconv.FormatBool(true),
}
n, err := c.NewNetwork("bridge", libnGWNetwork, "", n, err := c.NewNetwork("bridge", libnGWNetwork, "",
NetworkOptionDriverOpts(netOption), NetworkOptionDriverOpts(map[string]string{
bridge.BridgeName: libnGWNetwork,
bridge.EnableICC: strconv.FormatBool(false),
bridge.EnableIPMasquerade: strconv.FormatBool(true),
}),
NetworkOptionEnableIPv6(false), NetworkOptionEnableIPv6(false),
) )
if err != nil { if err != nil {

View file

@ -16,6 +16,6 @@ func getPlatformOption() EndpointOption {
return EndpointOptionGeneric(epOption) return EndpointOptionGeneric(epOption)
} }
func (c *Controller) createGWNetwork() (Network, error) { func (c *Controller) createGWNetwork() (*Network, error) {
return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in windows") return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in windows")
} }

View file

@ -24,7 +24,7 @@ type EndpointOption func(ep *Endpoint)
type Endpoint struct { type Endpoint struct {
name string name string
id string id string
network *network network *Network
iface *endpointInterface iface *endpointInterface
joinInfo *endpointJoinInfo joinInfo *endpointJoinInfo
sandboxID string sandboxID string
@ -378,14 +378,14 @@ func (ep *Endpoint) processOptions(options ...EndpointOption) {
} }
} }
func (ep *Endpoint) getNetwork() *network { func (ep *Endpoint) getNetwork() *Network {
ep.mu.Lock() ep.mu.Lock()
defer ep.mu.Unlock() defer ep.mu.Unlock()
return ep.network return ep.network
} }
func (ep *Endpoint) getNetworkFromStore() (*network, error) { func (ep *Endpoint) getNetworkFromStore() (*Network, error) {
if ep.network == nil { if ep.network == nil {
return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name()) return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name())
} }
@ -932,7 +932,7 @@ func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]
} }
// CreateOptionExposedPorts function returns an option setter for the container exposed // CreateOptionExposedPorts function returns an option setter for the container exposed
// ports option to be passed to network.CreateEndpoint() method. // ports option to be passed to [Network.CreateEndpoint] method.
func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption { func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
return func(ep *Endpoint) { return func(ep *Endpoint) {
// Defensive copy // Defensive copy
@ -945,7 +945,7 @@ func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption
} }
// CreateOptionPortMapping function returns an option setter for the mapping // CreateOptionPortMapping function returns an option setter for the mapping
// ports option to be passed to network.CreateEndpoint() method. // ports option to be passed to [Network.CreateEndpoint] method.
func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption { func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
return func(ep *Endpoint) { return func(ep *Endpoint) {
// Store a copy of the bindings as generic data to pass to the driver // Store a copy of the bindings as generic data to pass to the driver

View file

@ -9,7 +9,7 @@ import (
) )
type endpointCnt struct { type endpointCnt struct {
n *network n *Network
Count uint64 Count uint64
dbIndex uint64 dbIndex uint64
dbExists bool dbExists bool

View file

@ -20,7 +20,7 @@ import (
) )
func TestNetworkMarshalling(t *testing.T) { func TestNetworkMarshalling(t *testing.T) {
n := &network{ n := &Network{
name: "Miao", name: "Miao",
id: "abccba", id: "abccba",
ipamType: "default", ipamType: "default",
@ -128,7 +128,7 @@ func TestNetworkMarshalling(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
nn := &network{} nn := &Network{}
err = json.Unmarshal(b, nn) err = json.Unmarshal(b, nn)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -319,7 +319,7 @@ func TestAuxAddresses(t *testing.T) {
} }
defer c.Stop() defer c.Stop()
n := &network{ipamType: ipamapi.DefaultIPAM, networkType: "bridge", ctrlr: c} n := &Network{ipamType: ipamapi.DefaultIPAM, networkType: "bridge", ctrlr: c}
input := []struct { input := []struct {
masterPool string masterPool string
@ -486,12 +486,12 @@ func TestServiceVIPReuse(t *testing.T) {
} }
// Add 2 services with same name but different service ID to share the same VIP // Add 2 services with same name but different service ID to share the same VIP
n.(*network).addSvcRecords("ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.addSvcRecords("ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
n.(*network).addSvcRecords("ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.addSvcRecords("ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
ipToResolve := netutils.ReverseIP("192.168.0.1") ipToResolve := netutils.ReverseIP("192.168.0.1")
ipList, _ := n.(*network).ResolveName("service_test", types.IPv4) ipList, _ := n.ResolveName("service_test", types.IPv4)
if len(ipList) == 0 { if len(ipList) == 0 {
t.Fatal("There must be the VIP") t.Fatal("There must be the VIP")
} }
@ -501,7 +501,7 @@ func TestServiceVIPReuse(t *testing.T) {
if ipList[0].String() != "192.168.0.1" { if ipList[0].String() != "192.168.0.1" {
t.Fatal("The service VIP is 192.168.0.1") t.Fatal("The service VIP is 192.168.0.1")
} }
name := n.(*network).ResolveIP(ipToResolve) name := n.ResolveIP(ipToResolve)
if name == "" { if name == "" {
t.Fatal("It must return a name") t.Fatal("It must return a name")
} }
@ -510,8 +510,8 @@ func TestServiceVIPReuse(t *testing.T) {
} }
// Delete service record for one of the services, the IP should remain because one service is still associated with it // Delete service record for one of the services, the IP should remain because one service is still associated with it
n.(*network).deleteSvcRecords("ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.deleteSvcRecords("ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
ipList, _ = n.(*network).ResolveName("service_test", types.IPv4) ipList, _ = n.ResolveName("service_test", types.IPv4)
if len(ipList) == 0 { if len(ipList) == 0 {
t.Fatal("There must be the VIP") t.Fatal("There must be the VIP")
} }
@ -521,7 +521,7 @@ func TestServiceVIPReuse(t *testing.T) {
if ipList[0].String() != "192.168.0.1" { if ipList[0].String() != "192.168.0.1" {
t.Fatal("The service VIP is 192.168.0.1") t.Fatal("The service VIP is 192.168.0.1")
} }
name = n.(*network).ResolveIP(ipToResolve) name = n.ResolveIP(ipToResolve)
if name == "" { if name == "" {
t.Fatal("It must return a name") t.Fatal("It must return a name")
} }
@ -530,8 +530,8 @@ func TestServiceVIPReuse(t *testing.T) {
} }
// Delete again the service using the previous service ID, nothing should happen // Delete again the service using the previous service ID, nothing should happen
n.(*network).deleteSvcRecords("ep2", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.deleteSvcRecords("ep2", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
ipList, _ = n.(*network).ResolveName("service_test", types.IPv4) ipList, _ = n.ResolveName("service_test", types.IPv4)
if len(ipList) == 0 { if len(ipList) == 0 {
t.Fatal("There must be the VIP") t.Fatal("There must be the VIP")
} }
@ -541,7 +541,7 @@ func TestServiceVIPReuse(t *testing.T) {
if ipList[0].String() != "192.168.0.1" { if ipList[0].String() != "192.168.0.1" {
t.Fatal("The service VIP is 192.168.0.1") t.Fatal("The service VIP is 192.168.0.1")
} }
name = n.(*network).ResolveIP(ipToResolve) name = n.ResolveIP(ipToResolve)
if name == "" { if name == "" {
t.Fatal("It must return a name") t.Fatal("It must return a name")
} }
@ -550,12 +550,12 @@ func TestServiceVIPReuse(t *testing.T) {
} }
// Delete now using the second service ID, now all the entries should be gone // Delete now using the second service ID, now all the entries should be gone
n.(*network).deleteSvcRecords("ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.deleteSvcRecords("ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
ipList, _ = n.(*network).ResolveName("service_test", types.IPv4) ipList, _ = n.ResolveName("service_test", types.IPv4)
if len(ipList) != 0 { if len(ipList) != 0 {
t.Fatal("All the VIPs should be gone now") t.Fatal("All the VIPs should be gone now")
} }
name = n.(*network).ResolveIP(ipToResolve) name = n.ResolveIP(ipToResolve)
if name != "" { if name != "" {
t.Fatalf("It must return empty no more services associated, instead:%s", name) t.Fatalf("It must return empty no more services associated, instead:%s", name)
} }

View file

@ -31,7 +31,7 @@ const (
bridgeNetType = "bridge" bridgeNetType = "bridge"
) )
func makeTesthostNetwork(t *testing.T, c *libnetwork.Controller) libnetwork.Network { func makeTesthostNetwork(t *testing.T, c *libnetwork.Controller) *libnetwork.Network {
t.Helper() t.Helper()
n, err := createTestNetwork(c, "host", "testhost", options.Generic{}, nil, nil) n, err := createTestNetwork(c, "host", "testhost", options.Generic{}, nil, nil)
if err != nil { if err != nil {
@ -847,7 +847,7 @@ func TestResolvConf(t *testing.T) {
type parallelTester struct { type parallelTester struct {
osctx *testutils.OSContext osctx *testutils.OSContext
controller *libnetwork.Controller controller *libnetwork.Controller
net1, net2 libnetwork.Network net1, net2 *libnetwork.Network
iterCnt int iterCnt int
} }

View file

@ -47,7 +47,7 @@ func newController(t *testing.T) *libnetwork.Controller {
return c return c
} }
func createTestNetwork(c *libnetwork.Controller, networkType, networkName string, netOption options.Generic, ipamV4Configs, ipamV6Configs []*libnetwork.IpamConf) (libnetwork.Network, error) { func createTestNetwork(c *libnetwork.Controller, networkType, networkName string, netOption options.Generic, ipamV4Configs, ipamV6Configs []*libnetwork.IpamConf) (*libnetwork.Network, error) {
return c.NewNetwork(networkType, networkName, "", return c.NewNetwork(networkType, networkName, "",
libnetwork.NetworkOptionGeneric(netOption), libnetwork.NetworkOptionGeneric(netOption),
libnetwork.NetworkOptionIpam(ipamapi.DefaultIPAM, "", ipamV4Configs, ipamV6Configs, nil)) libnetwork.NetworkOptionIpam(ipamapi.DefaultIPAM, "", ipamV4Configs, ipamV6Configs, nil))
@ -549,8 +549,8 @@ func TestNetworkEndpointsWalkers(t *testing.T) {
// Test Network Walk method // Test Network Walk method
var netName string var netName string
var netWanted libnetwork.Network var netWanted *libnetwork.Network
nwWlk := func(nw libnetwork.Network) bool { nwWlk := func(nw *libnetwork.Network) bool {
if nw.Name() == netName { if nw.Name() == netName {
netWanted = nw netWanted = nw
return true return true

View file

@ -24,41 +24,6 @@ import (
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
) )
// A Network represents a logical connectivity zone that containers may
// join using the Link method. A Network is managed by a specific driver.
type Network interface {
// Name returns a user chosen name for this network.
Name() string
// ID returns a system generated id for this network.
ID() string
// Type returns the type of network, which corresponds to its managing driver.
Type() string
// CreateEndpoint creates a new endpoint to this network symbolically identified by the
// specified unique name. The options parameter carries driver specific options.
CreateEndpoint(name string, options ...EndpointOption) (*Endpoint, error)
// Delete the network.
Delete(options ...NetworkDeleteOption) error
// Endpoints returns the list of Endpoint(s) in this network.
Endpoints() []*Endpoint
// WalkEndpoints uses the provided function to walk the Endpoints.
WalkEndpoints(walker EndpointWalker)
// EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
EndpointByName(name string) (*Endpoint, error)
// EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
EndpointByID(id string) (*Endpoint, error)
// Info returns certain operational data belonging to this network.
Info() NetworkInfo
}
// NetworkInfo returns some configuration and operational information about the network // NetworkInfo returns some configuration and operational information about the network
type NetworkInfo interface { type NetworkInfo interface {
IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf)
@ -199,7 +164,9 @@ func (i *IpamInfo) UnmarshalJSON(data []byte) error {
return nil return nil
} }
type network struct { // Network represents a logical connectivity zone that containers may
// join using the Link method. A network is managed by a specific driver.
type Network struct {
ctrlr *Controller ctrlr *Controller
name string name string
networkType string networkType string
@ -243,45 +210,48 @@ const (
loadBalancerModeDefault = loadBalancerModeNAT loadBalancerModeDefault = loadBalancerModeNAT
) )
func (n *network) Name() string { // Name returns a user chosen name for this network.
func (n *Network) Name() string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.name return n.name
} }
func (n *network) ID() string { // ID returns a system generated id for this network.
func (n *Network) ID() string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.id return n.id
} }
func (n *network) Created() time.Time { func (n *Network) Created() time.Time {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.created return n.created
} }
func (n *network) Type() string { // Type returns the type of network, which corresponds to its managing driver.
func (n *Network) Type() string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.networkType return n.networkType
} }
func (n *network) Key() []string { func (n *Network) Key() []string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return []string{datastore.NetworkKeyPrefix, n.id} return []string{datastore.NetworkKeyPrefix, n.id}
} }
func (n *network) KeyPrefix() []string { func (n *Network) KeyPrefix() []string {
return []string{datastore.NetworkKeyPrefix} return []string{datastore.NetworkKeyPrefix}
} }
func (n *network) Value() []byte { func (n *Network) Value() []byte {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
b, err := json.Marshal(n) b, err := json.Marshal(n)
@ -291,40 +261,40 @@ func (n *network) Value() []byte {
return b return b
} }
func (n *network) SetValue(value []byte) error { func (n *Network) SetValue(value []byte) error {
return json.Unmarshal(value, n) return json.Unmarshal(value, n)
} }
func (n *network) Index() uint64 { func (n *Network) Index() uint64 {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.dbIndex return n.dbIndex
} }
func (n *network) SetIndex(index uint64) { func (n *Network) SetIndex(index uint64) {
n.mu.Lock() n.mu.Lock()
n.dbIndex = index n.dbIndex = index
n.dbExists = true n.dbExists = true
n.mu.Unlock() n.mu.Unlock()
} }
func (n *network) Exists() bool { func (n *Network) Exists() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.dbExists return n.dbExists
} }
func (n *network) Skip() bool { func (n *Network) Skip() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return !n.persist return !n.persist
} }
func (n *network) New() datastore.KVObject { func (n *Network) New() datastore.KVObject {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return &network{ return &Network{
ctrlr: n.ctrlr, ctrlr: n.ctrlr,
drvOnce: &sync.Once{}, drvOnce: &sync.Once{},
scope: n.scope, scope: n.scope,
@ -369,7 +339,7 @@ func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
return nil return nil
} }
func (n *network) validateConfiguration() error { func (n *Network) validateConfiguration() error {
if n.configOnly { if n.configOnly {
// Only supports network specific configurations. // Only supports network specific configurations.
// Network operator configurations are not supported. // Network operator configurations are not supported.
@ -417,7 +387,7 @@ func (n *network) validateConfiguration() error {
} }
// applyConfigurationTo applies network specific configurations. // applyConfigurationTo applies network specific configurations.
func (n *network) applyConfigurationTo(to *network) error { func (n *Network) applyConfigurationTo(to *Network) error {
to.enableIPv6 = n.enableIPv6 to.enableIPv6 = n.enableIPv6
if len(n.labels) > 0 { if len(n.labels) > 0 {
to.labels = make(map[string]string, len(n.labels)) to.labels = make(map[string]string, len(n.labels))
@ -455,11 +425,11 @@ func (n *network) applyConfigurationTo(to *network) error {
return nil return nil
} }
func (n *network) CopyTo(o datastore.KVObject) error { func (n *Network) CopyTo(o datastore.KVObject) error {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
dstN := o.(*network) dstN := o.(*Network)
dstN.name = n.name dstN.name = n.name
dstN.id = n.id dstN.id = n.id
dstN.created = n.created dstN.created = n.created
@ -537,7 +507,7 @@ func (n *network) CopyTo(o datastore.KVObject) error {
return nil return nil
} }
func (n *network) DataScope() string { func (n *Network) DataScope() string {
s := n.Scope() s := n.Scope()
// All swarm scope networks have local datascope // All swarm scope networks have local datascope
if s == datastore.SwarmScope { if s == datastore.SwarmScope {
@ -546,7 +516,7 @@ func (n *network) DataScope() string {
return s return s
} }
func (n *network) getEpCnt() *endpointCnt { func (n *Network) getEpCnt() *endpointCnt {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
@ -554,7 +524,7 @@ func (n *network) getEpCnt() *endpointCnt {
} }
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
func (n *network) MarshalJSON() ([]byte, error) { func (n *Network) MarshalJSON() ([]byte, error) {
netMap := make(map[string]interface{}) netMap := make(map[string]interface{})
netMap["name"] = n.name netMap["name"] = n.name
netMap["id"] = n.id netMap["id"] = n.id
@ -611,7 +581,7 @@ func (n *network) MarshalJSON() ([]byte, error) {
} }
// TODO : Can be made much more generic with the help of reflection (but has some golang limitations) // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
func (n *network) UnmarshalJSON(b []byte) (err error) { func (n *Network) UnmarshalJSON(b []byte) (err error) {
var netMap map[string]interface{} var netMap map[string]interface{}
if err := json.Unmarshal(b, &netMap); err != nil { if err := json.Unmarshal(b, &netMap); err != nil {
return err return err
@ -734,12 +704,12 @@ func (n *network) UnmarshalJSON(b []byte) (err error) {
// NetworkOption is an option setter function type used to pass various options to // NetworkOption is an option setter function type used to pass various options to
// NewNetwork method. The various setter functions of type NetworkOption are // NewNetwork method. The various setter functions of type NetworkOption are
// provided by libnetwork, they look like NetworkOptionXXXX(...) // provided by libnetwork, they look like NetworkOptionXXXX(...)
type NetworkOption func(n *network) type NetworkOption func(n *Network)
// NetworkOptionGeneric function returns an option setter for a Generic option defined // NetworkOptionGeneric function returns an option setter for a Generic option defined
// in a Dictionary of Key-Value pair // in a Dictionary of Key-Value pair
func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption { func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
return func(n *network) { return func(n *Network) {
if n.generic == nil { if n.generic == nil {
n.generic = make(map[string]interface{}) n.generic = make(map[string]interface{})
} }
@ -758,21 +728,21 @@ func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
// NetworkOptionIngress returns an option setter to indicate if a network is // NetworkOptionIngress returns an option setter to indicate if a network is
// an ingress network. // an ingress network.
func NetworkOptionIngress(ingress bool) NetworkOption { func NetworkOptionIngress(ingress bool) NetworkOption {
return func(n *network) { return func(n *Network) {
n.ingress = ingress n.ingress = ingress
} }
} }
// NetworkOptionPersist returns an option setter to set persistence policy for a network // NetworkOptionPersist returns an option setter to set persistence policy for a network
func NetworkOptionPersist(persist bool) NetworkOption { func NetworkOptionPersist(persist bool) NetworkOption {
return func(n *network) { return func(n *Network) {
n.persist = persist n.persist = persist
} }
} }
// NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6 // NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption { func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
return func(n *network) { return func(n *Network) {
if n.generic == nil { if n.generic == nil {
n.generic = make(map[string]interface{}) n.generic = make(map[string]interface{})
} }
@ -784,7 +754,7 @@ func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
// NetworkOptionInternalNetwork returns an option setter to config the network // NetworkOptionInternalNetwork returns an option setter to config the network
// to be internal which disables default gateway service // to be internal which disables default gateway service
func NetworkOptionInternalNetwork() NetworkOption { func NetworkOptionInternalNetwork() NetworkOption {
return func(n *network) { return func(n *Network) {
if n.generic == nil { if n.generic == nil {
n.generic = make(map[string]interface{}) n.generic = make(map[string]interface{})
} }
@ -795,7 +765,7 @@ func NetworkOptionInternalNetwork() NetworkOption {
// NetworkOptionAttachable returns an option setter to set attachable for a network // NetworkOptionAttachable returns an option setter to set attachable for a network
func NetworkOptionAttachable(attachable bool) NetworkOption { func NetworkOptionAttachable(attachable bool) NetworkOption {
return func(n *network) { return func(n *Network) {
n.attachable = attachable n.attachable = attachable
} }
} }
@ -803,14 +773,14 @@ func NetworkOptionAttachable(attachable bool) NetworkOption {
// NetworkOptionScope returns an option setter to overwrite the network's scope. // NetworkOptionScope returns an option setter to overwrite the network's scope.
// By default the network's scope is set to the network driver's datascope. // By default the network's scope is set to the network driver's datascope.
func NetworkOptionScope(scope string) NetworkOption { func NetworkOptionScope(scope string) NetworkOption {
return func(n *network) { return func(n *Network) {
n.scope = scope n.scope = scope
} }
} }
// NetworkOptionIpam function returns an option setter for the ipam configuration for this network // NetworkOptionIpam function returns an option setter for the ipam configuration for this network
func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption { func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption {
return func(n *network) { return func(n *Network) {
if ipamDriver != "" { if ipamDriver != "" {
n.ipamType = ipamDriver n.ipamType = ipamDriver
if ipamDriver == ipamapi.DefaultIPAM { if ipamDriver == ipamapi.DefaultIPAM {
@ -826,14 +796,14 @@ func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ip
// NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network // NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network
func NetworkOptionLBEndpoint(ip net.IP) NetworkOption { func NetworkOptionLBEndpoint(ip net.IP) NetworkOption {
return func(n *network) { return func(n *Network) {
n.loadBalancerIP = ip n.loadBalancerIP = ip
} }
} }
// NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map // NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map
func NetworkOptionDriverOpts(opts map[string]string) NetworkOption { func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
return func(n *network) { return func(n *Network) {
if n.generic == nil { if n.generic == nil {
n.generic = make(map[string]interface{}) n.generic = make(map[string]interface{})
} }
@ -847,14 +817,14 @@ func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
// NetworkOptionLabels function returns an option setter for labels specific to a network // NetworkOptionLabels function returns an option setter for labels specific to a network
func NetworkOptionLabels(labels map[string]string) NetworkOption { func NetworkOptionLabels(labels map[string]string) NetworkOption {
return func(n *network) { return func(n *Network) {
n.labels = labels n.labels = labels
} }
} }
// NetworkOptionDynamic function returns an option setter for dynamic option for a network // NetworkOptionDynamic function returns an option setter for dynamic option for a network
func NetworkOptionDynamic() NetworkOption { func NetworkOptionDynamic() NetworkOption {
return func(n *network) { return func(n *Network) {
n.dynamic = true n.dynamic = true
} }
} }
@ -864,7 +834,7 @@ func NetworkOptionDynamic() NetworkOption {
// to a container as combination of fixed-cidr-v6 + mac-address // to a container as combination of fixed-cidr-v6 + mac-address
// TODO: Remove this option setter once we support endpoint ipam options // TODO: Remove this option setter once we support endpoint ipam options
func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption { func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
return func(n *network) { return func(n *Network) {
n.postIPv6 = enable n.postIPv6 = enable
} }
} }
@ -873,7 +843,7 @@ func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
// a configuration only network. It serves as a configuration // a configuration only network. It serves as a configuration
// for other networks. // for other networks.
func NetworkOptionConfigOnly() NetworkOption { func NetworkOptionConfigOnly() NetworkOption {
return func(n *network) { return func(n *Network) {
n.configOnly = true n.configOnly = true
} }
} }
@ -881,12 +851,12 @@ func NetworkOptionConfigOnly() NetworkOption {
// NetworkOptionConfigFrom tells controller to pick the // NetworkOptionConfigFrom tells controller to pick the
// network configuration from a configuration only network // network configuration from a configuration only network
func NetworkOptionConfigFrom(name string) NetworkOption { func NetworkOptionConfigFrom(name string) NetworkOption {
return func(n *network) { return func(n *Network) {
n.configFrom = name n.configFrom = name
} }
} }
func (n *network) processOptions(options ...NetworkOption) { func (n *Network) processOptions(options ...NetworkOption) {
for _, opt := range options { for _, opt := range options {
if opt != nil { if opt != nil {
opt(n) opt(n)
@ -899,10 +869,10 @@ type networkDeleteParams struct {
} }
// NetworkDeleteOption is a type for optional parameters to pass to the // NetworkDeleteOption is a type for optional parameters to pass to the
// network.Delete() function. // Network.Delete() function.
type NetworkDeleteOption func(p *networkDeleteParams) type NetworkDeleteOption func(p *networkDeleteParams)
// NetworkDeleteOptionRemoveLB informs a network.Delete() operation that should // NetworkDeleteOptionRemoveLB informs a Network.Delete() operation that should
// remove the load balancer endpoint for this network. Note that the Delete() // remove the load balancer endpoint for this network. Note that the Delete()
// method will automatically remove a load balancing endpoint for most networks // method will automatically remove a load balancing endpoint for most networks
// when the network is otherwise empty. However, this does not occur for some // when the network is otherwise empty. However, this does not occur for some
@ -916,7 +886,7 @@ func NetworkDeleteOptionRemoveLB(p *networkDeleteParams) {
p.rmLBEndpoint = true p.rmLBEndpoint = true
} }
func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, driverapi.Capability, error) { func (n *Network) resolveDriver(name string, load bool) (driverapi.Driver, driverapi.Capability, error) {
c := n.getController() c := n.getController()
// Check if a driver for the specified network type is available // Check if a driver for the specified network type is available
@ -941,7 +911,7 @@ func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, drive
return d, cap, nil return d, cap, nil
} }
func (n *network) driverIsMultihost() bool { func (n *Network) driverIsMultihost() bool {
_, cap, err := n.resolveDriver(n.networkType, true) _, cap, err := n.resolveDriver(n.networkType, true)
if err != nil { if err != nil {
return false return false
@ -949,7 +919,7 @@ func (n *network) driverIsMultihost() bool {
return cap.ConnectivityScope == datastore.GlobalScope return cap.ConnectivityScope == datastore.GlobalScope
} }
func (n *network) driver(load bool) (driverapi.Driver, error) { func (n *Network) driver(load bool) (driverapi.Driver, error) {
d, cap, err := n.resolveDriver(n.networkType, load) d, cap, err := n.resolveDriver(n.networkType, load)
if err != nil { if err != nil {
return nil, err return nil, err
@ -969,7 +939,8 @@ func (n *network) driver(load bool) (driverapi.Driver, error) {
return d, nil return d, nil
} }
func (n *network) Delete(options ...NetworkDeleteOption) error { // Delete the network.
func (n *Network) Delete(options ...NetworkDeleteOption) error {
var params networkDeleteParams var params networkDeleteParams
for _, opt := range options { for _, opt := range options {
opt(&params) opt(&params)
@ -985,7 +956,7 @@ func (n *network) Delete(options ...NetworkDeleteOption) error {
// remove load balancer and network if endpoint count == 1 // remove load balancer and network if endpoint count == 1
// - controller.networkCleanup() -- (true, true) // - controller.networkCleanup() -- (true, true)
// remove the network no matter what // remove the network no matter what
func (n *network) delete(force bool, rmLBEndpoint bool) error { func (n *Network) delete(force bool, rmLBEndpoint bool) error {
n.mu.Lock() n.mu.Lock()
c := n.ctrlr c := n.ctrlr
name := n.name name := n.name
@ -1093,7 +1064,7 @@ func (n *network) delete(force bool, rmLBEndpoint bool) error {
removeFromStore: removeFromStore:
// deleteFromStore performs an atomic delete operation and the // deleteFromStore performs an atomic delete operation and the
// network.epCnt will help prevent any possible // Network.epCnt will help prevent any possible
// race between endpoint join and network delete // race between endpoint join and network delete
if err = c.deleteFromStore(n.getEpCnt()); err != nil { if err = c.deleteFromStore(n.getEpCnt()); err != nil {
if !force { if !force {
@ -1109,10 +1080,10 @@ removeFromStore:
return nil return nil
} }
func (n *network) deleteNetwork() error { func (n *Network) deleteNetwork() error {
d, err := n.driver(true) d, err := n.driver(true)
if err != nil { if err != nil {
return fmt.Errorf("failed deleting network: %v", err) return fmt.Errorf("failed deleting Network: %v", err)
} }
if err := d.DeleteNetwork(n.ID()); err != nil { if err := d.DeleteNetwork(n.ID()); err != nil {
@ -1132,7 +1103,7 @@ func (n *network) deleteNetwork() error {
return nil return nil
} }
func (n *network) addEndpoint(ep *Endpoint) error { func (n *Network) addEndpoint(ep *Endpoint) error {
d, err := n.driver(true) d, err := n.driver(true)
if err != nil { if err != nil {
return fmt.Errorf("failed to add endpoint: %v", err) return fmt.Errorf("failed to add endpoint: %v", err)
@ -1147,7 +1118,9 @@ func (n *network) addEndpoint(ep *Endpoint) error {
return nil return nil
} }
func (n *network) CreateEndpoint(name string, options ...EndpointOption) (*Endpoint, error) { // CreateEndpoint creates a new endpoint to this network symbolically identified by the
// specified unique name. The options parameter carries driver specific options.
func (n *Network) CreateEndpoint(name string, options ...EndpointOption) (*Endpoint, error) {
var err error var err error
if strings.TrimSpace(name) == "" { if strings.TrimSpace(name) == "" {
return nil, ErrInvalidName(name) return nil, ErrInvalidName(name)
@ -1167,7 +1140,7 @@ func (n *network) CreateEndpoint(name string, options ...EndpointOption) (*Endpo
return n.createEndpoint(name, options...) return n.createEndpoint(name, options...)
} }
func (n *network) createEndpoint(name string, options ...EndpointOption) (*Endpoint, error) { func (n *Network) createEndpoint(name string, options ...EndpointOption) (*Endpoint, error) {
var err error var err error
ep := &Endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}} ep := &Endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
@ -1265,7 +1238,8 @@ func (n *network) createEndpoint(name string, options ...EndpointOption) (*Endpo
return ep, nil return ep, nil
} }
func (n *network) Endpoints() []*Endpoint { // Endpoints returns the list of Endpoint(s) in this network.
func (n *Network) Endpoints() []*Endpoint {
endpoints, err := n.getEndpointsFromStore() endpoints, err := n.getEndpointsFromStore()
if err != nil { if err != nil {
log.G(context.TODO()).Error(err) log.G(context.TODO()).Error(err)
@ -1273,7 +1247,8 @@ func (n *network) Endpoints() []*Endpoint {
return endpoints return endpoints
} }
func (n *network) WalkEndpoints(walker EndpointWalker) { // WalkEndpoints uses the provided function to walk the Endpoints.
func (n *Network) WalkEndpoints(walker EndpointWalker) {
for _, e := range n.Endpoints() { for _, e := range n.Endpoints() {
if walker(e) { if walker(e) {
return return
@ -1281,7 +1256,9 @@ func (n *network) WalkEndpoints(walker EndpointWalker) {
} }
} }
func (n *network) EndpointByName(name string) (*Endpoint, error) { // EndpointByName returns the Endpoint which has the passed name. If not found,
// the error ErrNoSuchEndpoint is returned.
func (n *Network) EndpointByName(name string) (*Endpoint, error) {
if name == "" { if name == "" {
return nil, ErrInvalidName(name) return nil, ErrInvalidName(name)
} }
@ -1304,7 +1281,9 @@ func (n *network) EndpointByName(name string) (*Endpoint, error) {
return e, nil return e, nil
} }
func (n *network) EndpointByID(id string) (*Endpoint, error) { // EndpointByID returns the Endpoint which has the passed id. If not found,
// the error ErrNoSuchEndpoint is returned.
func (n *Network) EndpointByID(id string) (*Endpoint, error) {
if id == "" { if id == "" {
return nil, ErrInvalidID(id) return nil, ErrInvalidID(id)
} }
@ -1317,7 +1296,7 @@ func (n *network) EndpointByID(id string) (*Endpoint, error) {
return ep, nil return ep, nil
} }
func (n *network) updateSvcRecord(ep *Endpoint, localEps []*Endpoint, isAdd bool) { func (n *Network) updateSvcRecord(ep *Endpoint, localEps []*Endpoint, isAdd bool) {
var ipv6 net.IP var ipv6 net.IP
epName := ep.Name() epName := ep.Name()
if iface := ep.Iface(); iface != nil && iface.Address() != nil { if iface := ep.Iface(); iface != nil && iface.Address() != nil {
@ -1393,7 +1372,7 @@ func delNameToIP(svcMap *setmatrix.SetMatrix[svcMapEntry], name, serviceID strin
}) })
} }
func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) { func (n *Network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) {
// Do not add service names for ingress network as this is a // Do not add service names for ingress network as this is a
// routing only network // routing only network
if n.ingress { if n.ingress {
@ -1425,7 +1404,7 @@ func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP
} }
} }
func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) { func (n *Network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) {
// Do not delete service names from ingress network as this is a // Do not delete service names from ingress network as this is a
// routing only network // routing only network
if n.ingress { if n.ingress {
@ -1458,7 +1437,7 @@ func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epI
} }
} }
func (n *network) getSvcRecords(ep *Endpoint) []etchosts.Record { func (n *Network) getSvcRecords(ep *Endpoint) []etchosts.Record {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
@ -1503,13 +1482,13 @@ func (n *network) getSvcRecords(ep *Endpoint) []etchosts.Record {
return recs return recs
} }
func (n *network) getController() *Controller { func (n *Network) getController() *Controller {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.ctrlr return n.ctrlr
} }
func (n *network) ipamAllocate() error { func (n *Network) ipamAllocate() error {
if n.hasSpecialDriver() { if n.hasSpecialDriver() {
return nil return nil
} }
@ -1544,7 +1523,7 @@ func (n *network) ipamAllocate() error {
return err return err
} }
func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) { func (n *Network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
for { for {
poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6) poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6)
if err != nil { if err != nil {
@ -1585,7 +1564,7 @@ func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPo
} }
} }
func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error { func (n *Network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
var ( var (
cfgList *[]*IpamConf cfgList *[]*IpamConf
infoList *[]*IpamInfo infoList *[]*IpamInfo
@ -1673,7 +1652,7 @@ func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
return nil return nil
} }
func (n *network) ipamRelease() { func (n *Network) ipamRelease() {
if n.hasSpecialDriver() { if n.hasSpecialDriver() {
return return
} }
@ -1686,7 +1665,7 @@ func (n *network) ipamRelease() {
n.ipamReleaseVersion(6, ipam) n.ipamReleaseVersion(6, ipam)
} }
func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) { func (n *Network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
var infoList *[]*IpamInfo var infoList *[]*IpamInfo
switch ipVer { switch ipVer {
@ -1728,7 +1707,7 @@ func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
*infoList = nil *infoList = nil
} }
func (n *network) getIPInfo(ipVer int) []*IpamInfo { func (n *Network) getIPInfo(ipVer int) []*IpamInfo {
var info []*IpamInfo var info []*IpamInfo
switch ipVer { switch ipVer {
case 4: case 4:
@ -1745,7 +1724,7 @@ func (n *network) getIPInfo(ipVer int) []*IpamInfo {
return l return l
} }
func (n *network) getIPData(ipVer int) []driverapi.IPAMData { func (n *Network) getIPData(ipVer int) []driverapi.IPAMData {
var info []*IpamInfo var info []*IpamInfo
switch ipVer { switch ipVer {
case 4: case 4:
@ -1764,7 +1743,7 @@ func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
return l return l
} }
func (n *network) deriveAddressSpace() (string, error) { func (n *Network) deriveAddressSpace() (string, error) {
ipam, _ := n.getController().ipamRegistry.IPAM(n.ipamType) ipam, _ := n.getController().ipamRegistry.IPAM(n.ipamType)
if ipam == nil { if ipam == nil {
return "", types.NotFoundErrorf("failed to get default address space: unknown ipam type %q", n.ipamType) return "", types.NotFoundErrorf("failed to get default address space: unknown ipam type %q", n.ipamType)
@ -1779,11 +1758,12 @@ func (n *network) deriveAddressSpace() (string, error) {
return local, nil return local, nil
} }
func (n *network) Info() NetworkInfo { // Info returns certain operational data belonging to this network.
func (n *Network) Info() NetworkInfo {
return n return n
} }
func (n *network) Peers() []networkdb.PeerInfo { func (n *Network) Peers() []networkdb.PeerInfo {
if !n.Dynamic() { if !n.Dynamic() {
return []networkdb.PeerInfo{} return []networkdb.PeerInfo{}
} }
@ -1796,7 +1776,7 @@ func (n *network) Peers() []networkdb.PeerInfo {
return agent.networkDB.Peers(n.ID()) return agent.networkDB.Peers(n.ID())
} }
func (n *network) DriverOptions() map[string]string { func (n *Network) DriverOptions() map[string]string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
if n.generic != nil { if n.generic != nil {
@ -1807,13 +1787,13 @@ func (n *network) DriverOptions() map[string]string {
return map[string]string{} return map[string]string{}
} }
func (n *network) Scope() string { func (n *Network) Scope() string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.scope return n.scope
} }
func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) { func (n *Network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
@ -1839,7 +1819,7 @@ func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamC
return n.ipamType, n.ipamOptions, v4L, v6L return n.ipamType, n.ipamOptions, v4L, v6L
} }
func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) { func (n *Network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
@ -1865,56 +1845,56 @@ func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
return v4Info, v6Info return v4Info, v6Info
} }
func (n *network) Internal() bool { func (n *Network) Internal() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.internal return n.internal
} }
func (n *network) Attachable() bool { func (n *Network) Attachable() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.attachable return n.attachable
} }
func (n *network) Ingress() bool { func (n *Network) Ingress() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.ingress return n.ingress
} }
func (n *network) Dynamic() bool { func (n *Network) Dynamic() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.dynamic return n.dynamic
} }
func (n *network) IPv6Enabled() bool { func (n *Network) IPv6Enabled() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.enableIPv6 return n.enableIPv6
} }
func (n *network) ConfigFrom() string { func (n *Network) ConfigFrom() string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.configFrom return n.configFrom
} }
func (n *network) ConfigOnly() bool { func (n *Network) ConfigOnly() bool {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
return n.configOnly return n.configOnly
} }
func (n *network) Labels() map[string]string { func (n *Network) Labels() map[string]string {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
@ -1926,7 +1906,7 @@ func (n *network) Labels() map[string]string {
return lbls return lbls
} }
func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectType) error { func (n *Network) TableEventRegister(tableName string, objType driverapi.ObjectType) error {
if !driverapi.IsValidType(objType) { if !driverapi.IsValidType(objType) {
return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName) return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName)
} }
@ -1941,7 +1921,7 @@ func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectT
return nil return nil
} }
func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) { func (n *Network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) {
ipamV4Config := make([]*IpamConf, len(ipV4Data)) ipamV4Config := make([]*IpamConf, len(ipV4Data))
for i, data := range ipV4Data { for i, data := range ipV4Data {
@ -1956,16 +1936,16 @@ func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) {
n.ipamV4Config = ipamV4Config n.ipamV4Config = ipamV4Config
} }
// Special drivers are ones which do not need to perform any network plumbing // Special drivers are ones which do not need to perform any Network plumbing
func (n *network) hasSpecialDriver() bool { func (n *Network) hasSpecialDriver() bool {
return n.Type() == "host" || n.Type() == "null" return n.Type() == "host" || n.Type() == "null"
} }
func (n *network) hasLoadBalancerEndpoint() bool { func (n *Network) hasLoadBalancerEndpoint() bool {
return len(n.loadBalancerIP) != 0 return len(n.loadBalancerIP) != 0
} }
func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) { func (n *Network) ResolveName(req string, ipType int) ([]net.IP, bool) {
var ipv6Miss bool var ipv6Miss bool
c := n.getController() c := n.getController()
@ -2009,7 +1989,7 @@ func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) {
return nil, ipv6Miss return nil, ipv6Miss
} }
func (n *network) HandleQueryResp(name string, ip net.IP) { func (n *Network) HandleQueryResp(name string, ip net.IP) {
networkID := n.ID() networkID := n.ID()
c := n.getController() c := n.getController()
c.mu.Lock() c.mu.Lock()
@ -2029,7 +2009,7 @@ func (n *network) HandleQueryResp(name string, ip net.IP) {
} }
} }
func (n *network) ResolveIP(ip string) string { func (n *Network) ResolveIP(ip string) string {
networkID := n.ID() networkID := n.ID()
c := n.getController() c := n.getController()
c.mu.Lock() c.mu.Lock()
@ -2059,7 +2039,7 @@ func (n *network) ResolveIP(ip string) string {
return elem.name + "." + nwName return elem.name + "." + nwName
} }
func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) { func (n *Network) ResolveService(name string) ([]*net.SRV, []net.IP) {
c := n.getController() c := n.getController()
srv := []*net.SRV{} srv := []*net.SRV{}
@ -2114,36 +2094,33 @@ func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) {
return srv, ip return srv, ip
} }
func (n *network) ExecFunc(f func()) error { func (n *Network) ExecFunc(f func()) error {
return types.NotImplementedErrorf("ExecFunc not supported by network") return types.NotImplementedErrorf("ExecFunc not supported by network")
} }
func (n *network) NdotsSet() bool { func (n *Network) NdotsSet() bool {
return false return false
} }
// config-only network is looked up by name // config-only network is looked up by name
func (c *Controller) getConfigNetwork(name string) (*network, error) { func (c *Controller) getConfigNetwork(name string) (*Network, error) {
var n Network var n *Network
c.WalkNetworks(func(current *Network) bool {
s := func(current Network) bool {
if current.Info().ConfigOnly() && current.Name() == name { if current.Info().ConfigOnly() && current.Name() == name {
n = current n = current
return true return true
} }
return false return false
} })
c.WalkNetworks(s)
if n == nil { if n == nil {
return nil, types.NotFoundErrorf("configuration network %q not found", name) return nil, types.NotFoundErrorf("configuration network %q not found", name)
} }
return n.(*network), nil return n, nil
} }
func (n *network) lbSandboxName() string { func (n *Network) lbSandboxName() string {
name := "lb-" + n.name name := "lb-" + n.name
if n.ingress { if n.ingress {
name = n.name + "-sbox" name = n.name + "-sbox"
@ -2151,11 +2128,11 @@ func (n *network) lbSandboxName() string {
return name return name
} }
func (n *network) lbEndpointName() string { func (n *Network) lbEndpointName() string {
return n.name + "-endpoint" return n.name + "-endpoint"
} }
func (n *network) createLoadBalancerSandbox() (retErr error) { func (n *Network) createLoadBalancerSandbox() (retErr error) {
sandboxName := n.lbSandboxName() sandboxName := n.lbSandboxName()
// Mark the sandbox to be a load balancer // Mark the sandbox to be a load balancer
sbOptions := []SandboxOption{OptionLoadBalancer(n.id)} sbOptions := []SandboxOption{OptionLoadBalancer(n.id)}
@ -2202,7 +2179,7 @@ func (n *network) createLoadBalancerSandbox() (retErr error) {
return sb.EnableService() return sb.EnableService()
} }
func (n *network) deleteLoadBalancerSandbox() error { func (n *Network) deleteLoadBalancerSandbox() error {
n.mu.Lock() n.mu.Lock()
c := n.ctrlr c := n.ctrlr
name := n.name name := n.name

View file

@ -6,7 +6,7 @@ import "github.com/docker/docker/libnetwork/ipamapi"
// Stub implementations for DNS related functions // Stub implementations for DNS related functions
func (n *network) startResolver() { func (n *Network) startResolver() {
} }
func defaultIpamForNetworkType(networkType string) string { func defaultIpamForNetworkType(networkType string) string {

View file

@ -28,7 +28,7 @@ func executeInCompartment(compartmentID uint32, x func()) {
x() x()
} }
func (n *network) startResolver() { func (n *Network) startResolver() {
if n.networkType == "ics" { if n.networkType == "ics" {
return return
} }

View file

@ -139,7 +139,7 @@ func TestDNSIPQuery(t *testing.T) {
} }
// add service records which are used to resolve names. These are the real targets for the DNS querries // add service records which are used to resolve names. These are the real targets for the DNS querries
n.(*network).addSvcRecords("ep1", "name1", "svc1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n.addSvcRecords("ep1", "name1", "svc1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
w := new(tstwriter) w := new(tstwriter)
// the unit tests right now will focus on non-proxyed DNS requests // the unit tests right now will focus on non-proxyed DNS requests

View file

@ -234,7 +234,7 @@ func (c *Controller) sandboxCleanup(activeSandboxes map[string]interface{}) {
var ep *Endpoint var ep *Endpoint
if err != nil { if err != nil {
log.G(context.TODO()).Errorf("getNetworkFromStore for nid %s failed while trying to build sandbox for cleanup: %v", eps.Nid, err) log.G(context.TODO()).Errorf("getNetworkFromStore for nid %s failed while trying to build sandbox for cleanup: %v", eps.Nid, err)
n = &network{id: eps.Nid, ctrlr: c, drvOnce: &sync.Once{}, persist: true} n = &Network{id: eps.Nid, ctrlr: c, drvOnce: &sync.Once{}, persist: true}
ep = &Endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID} ep = &Endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID}
} else { } else {
ep, err = n.getEndpointFromStore(eps.Eid) ep, err = n.getEndpointFromStore(eps.Eid)

View file

@ -14,7 +14,7 @@ import (
"gotest.tools/v3/skip" "gotest.tools/v3/skip"
) )
func getTestEnv(t *testing.T, opts ...[]NetworkOption) (*Controller, []Network) { func getTestEnv(t *testing.T, opts ...[]NetworkOption) (*Controller, []*Network) {
skip.If(t, runtime.GOOS == "windows", "test only works on linux") skip.If(t, runtime.GOOS == "windows", "test only works on linux")
const netType = "bridge" const netType = "bridge"
@ -33,7 +33,7 @@ func getTestEnv(t *testing.T, opts ...[]NetworkOption) (*Controller, []Network)
return c, nil return c, nil
} }
nwList := make([]Network, 0, len(opts)) nwList := make([]*Network, 0, len(opts))
for i, opt := range opts { for i, opt := range opts {
name := "test_nw_" + strconv.Itoa(i) name := "test_nw_" + strconv.Itoa(i)
newOptions := []NetworkOption{ newOptions := []NetworkOption{

View file

@ -31,23 +31,23 @@ func (c *Controller) addEndpointNameResolution(svcName, svcID, nID, eID, contain
} }
// Add endpoint IP to special "tasks.svc_name" so that the applications have access to DNS RR. // Add endpoint IP to special "tasks.svc_name" so that the applications have access to DNS RR.
n.(*network).addSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method) n.addSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).addSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method) n.addSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method)
} }
// Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR // Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR
if len(vip) == 0 { if len(vip) == 0 {
n.(*network).addSvcRecords(eID, svcName, serviceID, ip, nil, false, method) n.addSvcRecords(eID, svcName, serviceID, ip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).addSvcRecords(eID, alias, serviceID, ip, nil, false, method) n.addSvcRecords(eID, alias, serviceID, ip, nil, false, method)
} }
} }
if addService && len(vip) != 0 { if addService && len(vip) != 0 {
n.(*network).addSvcRecords(eID, svcName, serviceID, vip, nil, false, method) n.addSvcRecords(eID, svcName, serviceID, vip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).addSvcRecords(eID, alias, serviceID, vip, nil, false, method) n.addSvcRecords(eID, alias, serviceID, vip, nil, false, method)
} }
} }
@ -62,11 +62,11 @@ func (c *Controller) addContainerNameResolution(nID, eID, containerName string,
log.G(context.TODO()).Debugf("addContainerNameResolution %s %s", eID, containerName) log.G(context.TODO()).Debugf("addContainerNameResolution %s %s", eID, containerName)
// Add resolution for container name // Add resolution for container name
n.(*network).addSvcRecords(eID, containerName, eID, ip, nil, true, method) n.addSvcRecords(eID, containerName, eID, ip, nil, true, method)
// Add resolution for taskaliases // Add resolution for taskaliases
for _, alias := range taskAliases { for _, alias := range taskAliases {
n.(*network).addSvcRecords(eID, alias, eID, ip, nil, false, method) n.addSvcRecords(eID, alias, eID, ip, nil, false, method)
} }
return nil return nil
@ -93,25 +93,25 @@ func (c *Controller) deleteEndpointNameResolution(svcName, svcID, nID, eID, cont
// Delete the special "tasks.svc_name" backend record. // Delete the special "tasks.svc_name" backend record.
if !multipleEntries { if !multipleEntries {
n.(*network).deleteSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method) n.deleteSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).deleteSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method) n.deleteSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method)
} }
} }
// If we are doing DNS RR delete the endpoint IP from DNS record right away. // If we are doing DNS RR delete the endpoint IP from DNS record right away.
if !multipleEntries && len(vip) == 0 { if !multipleEntries && len(vip) == 0 {
n.(*network).deleteSvcRecords(eID, svcName, serviceID, ip, nil, false, method) n.deleteSvcRecords(eID, svcName, serviceID, ip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).deleteSvcRecords(eID, alias, serviceID, ip, nil, false, method) n.deleteSvcRecords(eID, alias, serviceID, ip, nil, false, method)
} }
} }
// Remove the DNS record for VIP only if we are removing the service // Remove the DNS record for VIP only if we are removing the service
if rmService && len(vip) != 0 && !multipleEntries { if rmService && len(vip) != 0 && !multipleEntries {
n.(*network).deleteSvcRecords(eID, svcName, serviceID, vip, nil, false, method) n.deleteSvcRecords(eID, svcName, serviceID, vip, nil, false, method)
for _, alias := range serviceAliases { for _, alias := range serviceAliases {
n.(*network).deleteSvcRecords(eID, alias, serviceID, vip, nil, false, method) n.deleteSvcRecords(eID, alias, serviceID, vip, nil, false, method)
} }
} }
@ -126,11 +126,11 @@ func (c *Controller) delContainerNameResolution(nID, eID, containerName string,
log.G(context.TODO()).Debugf("delContainerNameResolution %s %s", eID, containerName) log.G(context.TODO()).Debugf("delContainerNameResolution %s %s", eID, containerName)
// Delete resolution for container name // Delete resolution for container name
n.(*network).deleteSvcRecords(eID, containerName, eID, ip, nil, true, method) n.deleteSvcRecords(eID, containerName, eID, ip, nil, true, method)
// Delete resolution for taskaliases // Delete resolution for taskaliases
for _, alias := range taskAliases { for _, alias := range taskAliases {
n.(*network).deleteSvcRecords(eID, alias, eID, ip, nil, true, method) n.deleteSvcRecords(eID, alias, eID, ip, nil, true, method)
} }
return nil return nil
@ -299,7 +299,7 @@ func (c *Controller) addServiceBinding(svcName, svcID, nID, eID, containerName s
} }
// Add loadbalancer service and backend to the network // Add loadbalancer service and backend to the network
n.(*network).addLBBackend(ip, lb) n.addLBBackend(ip, lb)
// Add the appropriate name resolutions // Add the appropriate name resolutions
if err := c.addEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, addService, "addServiceBinding"); err != nil { if err := c.addEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, addService, "addServiceBinding"); err != nil {
@ -382,7 +382,7 @@ func (c *Controller) rmServiceBinding(svcName, svcID, nID, eID, containerName st
// removing the network from the store or dataplane. // removing the network from the store or dataplane.
n, err := c.NetworkByID(nID) n, err := c.NetworkByID(nID)
if err == nil { if err == nil {
n.(*network).rmLBBackend(ip, lb, rmService, fullRemove) n.rmLBBackend(ip, lb, rmService, fullRemove)
} }
} }

View file

@ -20,7 +20,7 @@ func TestCleanupServiceDiscovery(t *testing.T) {
assert.NilError(t, err) assert.NilError(t, err)
defer c.Stop() defer c.Stop()
cleanup := func(n Network) { cleanup := func(n *Network) {
if err := n.Delete(); err != nil { if err := n.Delete(); err != nil {
t.Error(err) t.Error(err)
} }
@ -33,11 +33,11 @@ func TestCleanupServiceDiscovery(t *testing.T) {
assert.NilError(t, err) assert.NilError(t, err)
defer cleanup(n2) defer cleanup(n2)
n1.(*network).addSvcRecords("N1ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test") n1.addSvcRecords("N1ep1", "service_test", "serviceID1", net.ParseIP("192.168.0.1"), net.IP{}, true, "test")
n1.(*network).addSvcRecords("N2ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.2"), net.IP{}, true, "test") n1.addSvcRecords("N2ep2", "service_test", "serviceID2", net.ParseIP("192.168.0.2"), net.IP{}, true, "test")
n2.(*network).addSvcRecords("N2ep1", "service_test", "serviceID1", net.ParseIP("192.168.1.1"), net.IP{}, true, "test") n2.addSvcRecords("N2ep1", "service_test", "serviceID1", net.ParseIP("192.168.1.1"), net.IP{}, true, "test")
n2.(*network).addSvcRecords("N2ep2", "service_test", "serviceID2", net.ParseIP("192.168.1.2"), net.IP{}, true, "test") n2.addSvcRecords("N2ep2", "service_test", "serviceID2", net.ParseIP("192.168.1.2"), net.IP{}, true, "test")
if len(c.svcRecords) != 2 { if len(c.svcRecords) != 2 {
t.Fatalf("Service record not added correctly:%v", c.svcRecords) t.Fatalf("Service record not added correctly:%v", c.svcRecords)

View file

@ -38,7 +38,7 @@ func (sb *Sandbox) populateLoadBalancers(ep *Endpoint) {
} }
} }
func (n *network) findLBEndpointSandbox() (*Endpoint, *Sandbox, error) { func (n *Network) findLBEndpointSandbox() (*Endpoint, *Sandbox, error) {
// TODO: get endpoint from store? See EndpointInfo() // TODO: get endpoint from store? See EndpointInfo()
var ep *Endpoint var ep *Endpoint
// Find this node's LB sandbox endpoint: there should be exactly one // Find this node's LB sandbox endpoint: there should be exactly one
@ -79,7 +79,7 @@ func findIfaceDstName(sb *Sandbox, ep *Endpoint) string {
// Add loadbalancer backend to the loadbalncer sandbox for the network. // Add loadbalancer backend to the loadbalncer sandbox for the network.
// If needed add the service as well. // If needed add the service as well.
func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) { func (n *Network) addLBBackend(ip net.IP, lb *loadBalancer) {
if len(lb.vip) == 0 { if len(lb.vip) == 0 {
return return
} }
@ -168,7 +168,7 @@ func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) {
// network. If 'rmService' is true, then remove the service entry as well. // network. If 'rmService' is true, then remove the service entry as well.
// If 'fullRemove' is true then completely remove the entry, otherwise // If 'fullRemove' is true then completely remove the entry, otherwise
// just deweight it for now. // just deweight it for now.
func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) { func (n *Network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) {
if len(lb.vip) == 0 { if len(lb.vip) == 0 {
return return
} }

View file

@ -15,7 +15,7 @@ type policyLists struct {
var lbPolicylistMap = make(map[*loadBalancer]*policyLists) var lbPolicylistMap = make(map[*loadBalancer]*policyLists)
func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) { func (n *Network) addLBBackend(ip net.IP, lb *loadBalancer) {
if len(lb.vip) == 0 { if len(lb.vip) == 0 {
return return
} }
@ -117,7 +117,7 @@ func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) {
} }
} }
func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) { func (n *Network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) {
if len(lb.vip) == 0 { if len(lb.vip) == 0 {
return return
} }

View file

@ -46,7 +46,7 @@ func (c *Controller) getStore() datastore.DataStore {
return c.store return c.store
} }
func (c *Controller) getNetworkFromStore(nid string) (*network, error) { func (c *Controller) getNetworkFromStore(nid string) (*Network, error) {
for _, n := range c.getNetworksFromStore() { for _, n := range c.getNetworksFromStore() {
if n.id == nid { if n.id == nid {
return n, nil return n, nil
@ -55,8 +55,8 @@ func (c *Controller) getNetworkFromStore(nid string) (*network, error) {
return nil, ErrNoSuchNetwork(nid) return nil, ErrNoSuchNetwork(nid)
} }
func (c *Controller) getNetworks() ([]*network, error) { func (c *Controller) getNetworks() ([]*Network, error) {
var nl []*network var nl []*Network
store := c.getStore() store := c.getStore()
if store == nil { if store == nil {
@ -64,13 +64,13 @@ func (c *Controller) getNetworks() ([]*network, error) {
} }
kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix), kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix),
&network{ctrlr: c}) &Network{ctrlr: c})
if err != nil && err != datastore.ErrKeyNotFound { if err != nil && err != datastore.ErrKeyNotFound {
return nil, fmt.Errorf("failed to get networks: %w", err) return nil, fmt.Errorf("failed to get networks: %w", err)
} }
for _, kvo := range kvol { for _, kvo := range kvol {
n := kvo.(*network) n := kvo.(*Network)
n.ctrlr = c n.ctrlr = c
ec := &endpointCnt{n: n} ec := &endpointCnt{n: n}
@ -90,11 +90,11 @@ func (c *Controller) getNetworks() ([]*network, error) {
return nl, nil return nl, nil
} }
func (c *Controller) getNetworksFromStore() []*network { // FIXME: unify with c.getNetworks() func (c *Controller) getNetworksFromStore() []*Network { // FIXME: unify with c.getNetworks()
var nl []*network var nl []*Network
store := c.getStore() store := c.getStore()
kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix), &network{ctrlr: c}) kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix), &Network{ctrlr: c})
if err != nil { if err != nil {
if err != datastore.ErrKeyNotFound { if err != datastore.ErrKeyNotFound {
log.G(context.TODO()).Debugf("failed to get networks from store: %v", err) log.G(context.TODO()).Debugf("failed to get networks from store: %v", err)
@ -108,7 +108,7 @@ func (c *Controller) getNetworksFromStore() []*network { // FIXME: unify with c.
} }
for _, kvo := range kvol { for _, kvo := range kvol {
n := kvo.(*network) n := kvo.(*Network)
n.mu.Lock() n.mu.Lock()
n.ctrlr = c n.ctrlr = c
ec := &endpointCnt{n: n} ec := &endpointCnt{n: n}
@ -128,7 +128,7 @@ func (c *Controller) getNetworksFromStore() []*network { // FIXME: unify with c.
return nl return nl
} }
func (n *network) getEndpointFromStore(eid string) (*Endpoint, error) { func (n *Network) getEndpointFromStore(eid string) (*Endpoint, error) {
store := n.ctrlr.getStore() store := n.ctrlr.getStore()
ep := &Endpoint{id: eid, network: n} ep := &Endpoint{id: eid, network: n}
err := store.GetObject(datastore.Key(ep.Key()...), ep) err := store.GetObject(datastore.Key(ep.Key()...), ep)
@ -138,7 +138,7 @@ func (n *network) getEndpointFromStore(eid string) (*Endpoint, error) {
return ep, nil return ep, nil
} }
func (n *network) getEndpointsFromStore() ([]*Endpoint, error) { func (n *Network) getEndpointsFromStore() ([]*Endpoint, error) {
var epl []*Endpoint var epl []*Endpoint
tmp := Endpoint{network: n} tmp := Endpoint{network: n}
@ -332,8 +332,8 @@ func (c *Controller) networkCleanup() {
} }
} }
var populateSpecial NetworkWalker = func(nw Network) bool { var populateSpecial NetworkWalker = func(nw *Network) bool {
if n := nw.(*network); n.hasSpecialDriver() && !n.ConfigOnly() { if n := nw; n.hasSpecialDriver() && !n.ConfigOnly() {
if err := n.getController().addNetwork(n); err != nil { if err := n.getController().addNetwork(n); err != nil {
log.G(context.TODO()).Warnf("Failed to populate network %q with driver %q", nw.Name(), nw.Type()) log.G(context.TODO()).Warnf("Failed to populate network %q with driver %q", nw.Name(), nw.Type())
} }