当前位置: 首页>>代码示例>>Golang>>正文


Golang container.NetworkMode函数代码示例

本文整理汇总了Golang中github.com/docker/engine-api/types/container.NetworkMode函数的典型用法代码示例。如果您正苦于以下问题:Golang NetworkMode函数的具体用法?Golang NetworkMode怎么用?Golang NetworkMode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NetworkMode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: updateNetworkSettings

func (daemon *Daemon) updateNetworkSettings(container *container.Container, n libnetwork.Network) error {
	if container.NetworkSettings == nil {
		container.NetworkSettings = &network.Settings{Networks: make(map[string]*networktypes.EndpointSettings)}
	}

	if !container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
		return runconfig.ErrConflictHostNetwork
	}

	for s := range container.NetworkSettings.Networks {
		sn, err := daemon.FindNetwork(s)
		if err != nil {
			continue
		}

		if sn.Name() == n.Name() {
			// Avoid duplicate config
			return nil
		}
		if !containertypes.NetworkMode(sn.Type()).IsPrivate() ||
			!containertypes.NetworkMode(n.Type()).IsPrivate() {
			return runconfig.ErrConflictSharedNetwork
		}
		if containertypes.NetworkMode(sn.Name()).IsNone() ||
			containertypes.NetworkMode(n.Name()).IsNone() {
			return runconfig.ErrConflictNoNetwork
		}
	}

	if _, ok := container.NetworkSettings.Networks[n.Name()]; !ok {
		container.NetworkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
	}

	return nil
}
开发者ID:slowreadr,项目名称:docker,代码行数:35,代码来源:container_operations_unix.go

示例2: TestModifyHostConfigWithSandboxID

func TestModifyHostConfigWithSandboxID(t *testing.T) {
	priv := true
	sandboxID := "sandbox"
	sandboxNSMode := fmt.Sprintf("container:%v", sandboxID)
	setPrivSC := &runtimeapi.LinuxContainerSecurityContext{}
	setPrivSC.Privileged = &priv
	setPrivHC := &dockercontainer.HostConfig{
		Privileged:  true,
		IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
		NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
	}
	setCapsHC := &dockercontainer.HostConfig{
		CapAdd:      []string{"addCapA", "addCapB"},
		CapDrop:     []string{"dropCapA", "dropCapB"},
		IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
		NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
	}
	setSELinuxHC := &dockercontainer.HostConfig{
		SecurityOpt: []string{
			fmt.Sprintf("%s:%s", securitycontext.DockerLabelUser, "user"),
			fmt.Sprintf("%s:%s", securitycontext.DockerLabelRole, "role"),
			fmt.Sprintf("%s:%s", securitycontext.DockerLabelType, "type"),
			fmt.Sprintf("%s:%s", securitycontext.DockerLabelLevel, "level"),
		},
		IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
		NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
	}

	cases := []struct {
		name     string
		sc       *runtimeapi.LinuxContainerSecurityContext
		expected *dockercontainer.HostConfig
	}{
		{
			name:     "container.SecurityContext.Privileged",
			sc:       setPrivSC,
			expected: setPrivHC,
		},
		{
			name: "container.SecurityContext.Capabilities",
			sc: &runtimeapi.LinuxContainerSecurityContext{
				Capabilities: inputCapabilities(),
			},
			expected: setCapsHC,
		},
		{
			name: "container.SecurityContext.SELinuxOptions",
			sc: &runtimeapi.LinuxContainerSecurityContext{
				SelinuxOptions: inputSELinuxOptions(),
			},
			expected: setSELinuxHC,
		},
	}

	for _, tc := range cases {
		dockerCfg := &dockercontainer.HostConfig{}
		modifyHostConfig(tc.sc, sandboxID, dockerCfg)
		assert.Equal(t, tc.expected, dockerCfg, "[Test case %q]", tc.name)
	}
}
开发者ID:humblec,项目名称:kubernetes,代码行数:60,代码来源:security_context_test.go

示例3: SetDefaultNetModeIfBlank

// SetDefaultNetModeIfBlank changes the NetworkMode in a HostConfig structure
// to default if it is not populated. This ensures backwards compatibility after
// the validation of the network mode was moved from the docker CLI to the
// docker daemon.
func SetDefaultNetModeIfBlank(hc *container.HostConfig) *container.HostConfig {
	if hc != nil {
		if hc.NetworkMode == container.NetworkMode("") {
			hc.NetworkMode = container.NetworkMode("default")
		}
	}
	return hc
}
开发者ID:CadeLaRen,项目名称:docker-3,代码行数:12,代码来源:hostconfig.go

示例4: TestPortFilterForHostMode

func TestPortFilterForHostMode(t *testing.T) {
	var (
		p     = PortFilter{}
		nodes = []*node.Node{
			{
				ID:   "node-1-id",
				Name: "node-1-name",
				Addr: "node-1",
			},
			{
				ID:   "node-2-id",
				Name: "node-2-name",
				Addr: "node-2",
			},
			{
				ID:   "node-3-id",
				Name: "node-3-name",
				Addr: "node-3",
			},
		}
		result []*node.Node
		err    error
	)

	// Add a container taking away port 80 in the host mode to nodes[0].
	container := &cluster.Container{
		Container: types.Container{ID: "c1"},
		Info: types.ContainerJSON{
			Config: &containertypes.Config{
				ExposedPorts: map[nat.Port]struct{}{nat.Port("80"): {}},
			},
			ContainerJSONBase: &types.ContainerJSONBase{
				HostConfig: &containertypes.HostConfig{
					NetworkMode: containertypes.NetworkMode("host"),
				},
			},
		}}

	assert.NoError(t, nodes[0].AddContainer(container))

	// Request port 80 in the host mode
	config := &cluster.ContainerConfig{Config: containertypes.Config{
		ExposedPorts: map[nat.Port]struct{}{nat.Port("80"): {}},
	}, HostConfig: containertypes.HostConfig{
		NetworkMode: containertypes.NetworkMode("host"),
	}, NetworkingConfig: networktypes.NetworkingConfig{}}

	// nodes[0] should be excluded since port 80 is taken away
	result, err = p.Filter(config, nodes, true)
	assert.NoError(t, err)
	assert.Equal(t, 2, len(result))
	assert.NotContains(t, result, nodes[0])
}
开发者ID:swarm-hooks,项目名称:swarm,代码行数:53,代码来源:port_test.go

示例5: updateNetworkConfig

func (daemon *Daemon) updateNetworkConfig(container *container.Container, idOrName string, endpointConfig *networktypes.EndpointSettings, updateSettings bool) (libnetwork.Network, error) {
	if container.HostConfig.NetworkMode.IsContainer() {
		return nil, runconfig.ErrConflictSharedNetwork
	}

	if containertypes.NetworkMode(idOrName).IsBridge() &&
		daemon.configStore.DisableBridge {
		container.Config.NetworkDisabled = true
		return nil, nil
	}

	if !containertypes.NetworkMode(idOrName).IsUserDefined() {
		if hasUserDefinedIPAddress(endpointConfig) {
			return nil, runconfig.ErrUnsupportedNetworkAndIP
		}
		if endpointConfig != nil && len(endpointConfig.Aliases) > 0 {
			return nil, runconfig.ErrUnsupportedNetworkAndAlias
		}
	} else {
		addShortID := true
		shortID := stringid.TruncateID(container.ID)
		for _, alias := range endpointConfig.Aliases {
			if alias == shortID {
				addShortID = false
				break
			}
		}
		if addShortID {
			endpointConfig.Aliases = append(endpointConfig.Aliases, shortID)
		}
	}

	n, err := daemon.FindNetwork(idOrName)
	if err != nil {
		return nil, err
	}

	if err := validateNetworkingConfig(n, endpointConfig); err != nil {
		return nil, err
	}

	if updateSettings {
		if err := daemon.updateNetworkSettings(container, n); err != nil {
			return nil, err
		}
	}
	return n, nil
}
开发者ID:CheggEng,项目名称:docker,代码行数:48,代码来源:container_operations.go

示例6: DisconnectFromNetwork

// DisconnectFromNetwork disconnects container from network n.
func (daemon *Daemon) DisconnectFromNetwork(container *container.Container, n libnetwork.Network, force bool) error {
	if container.HostConfig.NetworkMode.IsHost() && containertypes.NetworkMode(n.Type()).IsHost() {
		return runconfig.ErrConflictHostNetwork
	}
	if !container.Running {
		if container.RemovalInProgress || container.Dead {
			return errRemovalContainer(container.ID)
		}
		if _, ok := container.NetworkSettings.Networks[n.Name()]; ok {
			delete(container.NetworkSettings.Networks, n.Name())
		} else {
			return fmt.Errorf("container %s is not connected to the network %s", container.ID, n.Name())
		}
	} else {
		if err := disconnectFromNetwork(container, n, false); err != nil {
			return err
		}
	}

	if err := container.ToDiskLocking(); err != nil {
		return fmt.Errorf("Error saving container to disk: %v", err)
	}

	attributes := map[string]string{
		"container": container.ID,
	}
	daemon.LogNetworkEventWithAttributes(n, "disconnect", attributes)
	return nil
}
开发者ID:contiv,项目名称:docker,代码行数:30,代码来源:container_operations_unix.go

示例7: createContainer

func (c *Cluster) createContainer(config *cluster.ContainerConfig, name string, withImageAffinity bool, authConfig *types.AuthConfig) (*cluster.Container, error) {
	c.scheduler.Lock()

	// Ensure the name is available
	if !c.checkNameUniqueness(name) {
		c.scheduler.Unlock()
		return nil, fmt.Errorf("Conflict: The name %s is already assigned. You have to delete (or rename) that container to be able to assign %s to a container again.", name, name)
	}

	swarmID := config.SwarmID()
	if swarmID == "" {
		// Associate a Swarm ID to the container we are creating.
		swarmID = c.generateUniqueID()
		config.SetSwarmID(swarmID)
	}

	if network := c.Networks().Get(string(config.HostConfig.NetworkMode)); network != nil && network.Scope == "local" {
		if !config.HaveNodeConstraint() {
			config.AddConstraint("node==~" + network.Engine.Name)
		}
		config.HostConfig.NetworkMode = containertypes.NetworkMode(network.Name)
	}

	if withImageAffinity {
		config.AddAffinity("image==" + config.Image)
	}

	nodes, err := c.scheduler.SelectNodesForContainer(c.listNodes(), config)

	if withImageAffinity {
		config.RemoveAffinity("image==" + config.Image)
	}

	if err != nil {
		c.scheduler.Unlock()
		return nil, err
	}
	n := nodes[0]
	engine, ok := c.engines[n.ID]
	if !ok {
		c.scheduler.Unlock()
		return nil, fmt.Errorf("error creating container")
	}

	c.pendingContainers[swarmID] = &pendingContainer{
		Name:   name,
		Config: config,
		Engine: engine,
	}

	c.scheduler.Unlock()

	container, err := engine.Create(config, name, true, authConfig)

	c.scheduler.Lock()
	delete(c.pendingContainers, swarmID)
	c.scheduler.Unlock()

	return container, err
}
开发者ID:thaJeztah,项目名称:swarm,代码行数:60,代码来源:cluster.go

示例8: TestModifyContainerNamespaceOptions

func TestModifyContainerNamespaceOptions(t *testing.T) {
	set := true
	sandboxID := "sandbox"
	sandboxNSMode := fmt.Sprintf("container:%v", sandboxID)
	cases := []struct {
		name     string
		nsOpt    *runtimeapi.NamespaceOption
		expected *dockercontainer.HostConfig
	}{
		{
			name: "NamespaceOption.HostNetwork",
			nsOpt: &runtimeapi.NamespaceOption{
				HostNetwork: &set,
			},
			expected: &dockercontainer.HostConfig{
				NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
				IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
				UTSMode:     namespaceModeHost,
			},
		},
		{
			name: "NamespaceOption.HostIpc",
			nsOpt: &runtimeapi.NamespaceOption{
				HostIpc: &set,
			},
			expected: &dockercontainer.HostConfig{
				NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
				IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
			},
		},
		{
			name: "NamespaceOption.HostPid",
			nsOpt: &runtimeapi.NamespaceOption{
				HostPid: &set,
			},
			expected: &dockercontainer.HostConfig{
				NetworkMode: dockercontainer.NetworkMode(sandboxNSMode),
				IpcMode:     dockercontainer.IpcMode(sandboxNSMode),
			},
		},
	}
	for _, tc := range cases {
		dockerCfg := &dockercontainer.HostConfig{}
		modifyContainerNamespaceOptions(tc.nsOpt, sandboxID, dockerCfg)
		assert.Equal(t, tc.expected, dockerCfg, "[Test case %q]", tc.name)
	}
}
开发者ID:jonboulle,项目名称:kubernetes,代码行数:47,代码来源:security_context_test.go

示例9: modifyHostNetworkOptionForContainer

// modifyHostNetworkOptionForContainer applies NetworkMode/UTSMode to container's dockercontainer.HostConfig.
func modifyHostNetworkOptionForContainer(hostNetwork bool, sandboxID string, hc *dockercontainer.HostConfig) {
	sandboxNSMode := fmt.Sprintf("container:%v", sandboxID)
	hc.NetworkMode = dockercontainer.NetworkMode(sandboxNSMode)
	hc.IpcMode = dockercontainer.IpcMode(sandboxNSMode)
	hc.UTSMode = ""
	hc.PidMode = ""

	if hostNetwork {
		hc.UTSMode = namespaceModeHost
	}
}
开发者ID:jonboulle,项目名称:kubernetes,代码行数:12,代码来源:security_context.go

示例10: updateEndpointNetworkSettings

func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
	if err := container.BuildEndpointInfo(n, ep); err != nil {
		return err
	}

	if container.HostConfig.NetworkMode == containertypes.NetworkMode("bridge") {
		container.NetworkSettings.Bridge = daemon.configStore.Bridge.Iface
	}

	return nil
}
开发者ID:slowreadr,项目名称:docker,代码行数:11,代码来源:container_operations_unix.go

示例11: createRoach

func (l *LocalCluster) createRoach(node *testNode, vols *Container, cmd ...string) {
	l.panicOnStop()

	hostConfig := container.HostConfig{
		PublishAllPorts: true,
		NetworkMode:     container.NetworkMode(l.networkID),
	}

	if vols != nil {
		hostConfig.VolumesFrom = append(hostConfig.VolumesFrom, vols.id)
	}

	var hostname string
	if node.index >= 0 {
		hostname = fmt.Sprintf("roach%d", node.index)
	}
	var entrypoint []string
	if *cockroachImage == builderImageFull {
		entrypoint = append(entrypoint, "/"+filepath.Base(*cockroachBinary))
	} else if *cockroachEntry != "" {
		entrypoint = append(entrypoint, *cockroachEntry)
	}
	var err error
	node.Container, err = createContainer(
		l,
		container.Config{
			Hostname: hostname,
			Image:    *cockroachImage,
			ExposedPorts: map[nat.Port]struct{}{
				defaultTCP: {},
			},
			Entrypoint: entrypoint,
			// TODO(pmattis): Figure out why the Go DNS resolver is misbehaving.
			Env: []string{"GODEBUG=netdns=cgo"},
			Cmd: cmd,
			Labels: map[string]string{
				// Allow for `docker ps --filter label=Hostname=roach0` or `--filter label=Roach`.
				"Hostname": hostname,
				"Roach":    "",
			},
		},
		hostConfig,
		&network.NetworkingConfig{
			EndpointsConfig: map[string]*network.EndpointSettings{
				l.networkID: {
					Aliases: []string{hostname},
				},
			},
		},
		node.nodeStr,
	)
	maybePanic(err)
}
开发者ID:liugangnhm,项目名称:cockroach,代码行数:53,代码来源:localcluster.go

示例12: addNetNs

func (c *Container) addNetNs(config *container.HostConfig, service project.Service, containers []project.Container) (*container.HostConfig, error) {
	if len(containers) == 0 {
		return nil, fmt.Errorf("Failed to find container for networks ns %v", c.service.Config().Net)
	}

	id, err := containers[0].ID()
	if err != nil {
		return nil, err
	}

	config.NetworkMode = container.NetworkMode("container:" + id)
	return config, nil
}
开发者ID:kunalkushwaha,项目名称:libcompose,代码行数:13,代码来源:container.go

示例13: addNetNs

func addNetNs(config *containertypes.HostConfig, service project.Service, containers []project.Container, networkMode string) (*containertypes.HostConfig, error) {
	if len(containers) == 0 {
		return nil, fmt.Errorf("Failed to find container for networks ns %v", networkMode)
	}

	id, err := containers[0].ID()
	if err != nil {
		return nil, err
	}

	config.NetworkMode = containertypes.NetworkMode("container:" + id)
	return config, nil
}
开发者ID:jainvipin,项目名称:libcompose,代码行数:13,代码来源:service_create.go

示例14: createContainer

// createContainer creates a new container using the specified
// options. Per the docker API, the created container is not running
// and must be started explicitly. Note that the passed-in hostConfig
// will be augmented with the necessary settings to use the network
// defined by l.createNetwork().
func createContainer(l *LocalCluster, containerConfig container.Config, hostConfig container.HostConfig, containerName string) (*Container, error) {
	hostConfig.NetworkMode = container.NetworkMode(l.networkID)
	// Disable DNS search under the host machine's domain. This can
	// catch upstream wildcard DNS matching and result in odd behavior.
	hostConfig.DNSSearch = []string{"."}
	resp, err := l.client.ContainerCreate(&containerConfig, &hostConfig, nil, containerName)
	if err != nil {
		return nil, err
	}
	return &Container{
		id:      resp.ID,
		name:    containerName,
		cluster: l,
	}, nil
}
开发者ID:cuongdo,项目名称:cockroach,代码行数:20,代码来源:docker.go

示例15: asDockerHostConfig

// asDockerHostConfig converts a RunContainerOptions into a HostConfig
// understood by the docker client
func (rco RunContainerOptions) asDockerHostConfig() dockercontainer.HostConfig {
	hostConfig := dockercontainer.HostConfig{
		CapDrop:         rco.CapDrop,
		PublishAllPorts: rco.TargetImage,
		NetworkMode:     dockercontainer.NetworkMode(rco.NetworkMode),
		Binds:           rco.Binds,
	}
	if rco.CGroupLimits != nil {
		hostConfig.Resources.Memory = rco.CGroupLimits.MemoryLimitBytes
		hostConfig.Resources.MemorySwap = rco.CGroupLimits.MemorySwap
		hostConfig.Resources.CPUShares = rco.CGroupLimits.CPUShares
		hostConfig.Resources.CPUQuota = rco.CGroupLimits.CPUQuota
		hostConfig.Resources.CPUPeriod = rco.CGroupLimits.CPUPeriod
	}
	return hostConfig
}
开发者ID:php-coder,项目名称:source-to-image,代码行数:18,代码来源:docker.go


注:本文中的github.com/docker/engine-api/types/container.NetworkMode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。