func (container *Container) RestoreNetwork() error { mode := container.hostConfig.NetworkMode // Don't attempt a restore if we previously didn't allocate networking. // This might be a legacy container with no network allocated, in which case the // allocation will happen once and for all at start. if !container.isNetworkAllocated() || container.Config.NetworkDisabled || !mode.IsPrivate() { return nil } // Re-allocate the interface with the same IP and MAC address. if _, err := bridge.Allocate(container.ID, container.NetworkSettings.MacAddress, container.NetworkSettings.IPAddress, ""); err != nil { return err } // Re-allocate any previously allocated ports. for port := range container.NetworkSettings.Ports { if err := container.allocatePort(port, container.NetworkSettings.Ports); err != nil { return err } } return nil }
func (container *Container) AllocateNetwork() error { mode := container.hostConfig.NetworkMode if container.Config.NetworkDisabled || !mode.IsPrivate() { return nil } var err error networkSettings, err := bridge.Allocate(container.ID, container.Config.MacAddress, "", "") if err != nil { return err } // Error handling: At this point, the interface is allocated so we have to // make sure that it is always released in case of error, otherwise we // might leak resources. if container.Config.PortSpecs != nil { if err = migratePortMappings(container.Config, container.hostConfig); err != nil { bridge.Release(container.ID) return err } container.Config.PortSpecs = nil if err = container.WriteHostConfig(); err != nil { bridge.Release(container.ID) return err } } var ( portSpecs = make(nat.PortSet) bindings = make(nat.PortMap) ) if container.Config.ExposedPorts != nil { portSpecs = container.Config.ExposedPorts } if container.hostConfig.PortBindings != nil { for p, b := range container.hostConfig.PortBindings { bindings[p] = []nat.PortBinding{} for _, bb := range b { bindings[p] = append(bindings[p], nat.PortBinding{ HostIp: bb.HostIp, HostPort: bb.HostPort, }) } } } container.NetworkSettings.PortMapping = nil for port := range portSpecs { if err = container.allocatePort(port, bindings); err != nil { bridge.Release(container.ID) return err } } container.WriteHostConfig() networkSettings.Ports = bindings container.NetworkSettings = networkSettings return nil }