//container.HostConfig.NetworkMode == constants.DockerHostMode
430840
func (d *DockerMonitor) resyncContainersByOrder(ctx context.Context, containers []types.Container, syncHost bool) error {
	for _, c := range containers {
		container, err := d.dockerClient.ContainerInspect(ctx, c.ID)
		if err != nil {
			continue
		}

		if (syncHost && container.HostConfig.NetworkMode != constants.DockerHostMode) ||
			(!syncHost && container.HostConfig.NetworkMode == constants.DockerHostMode) {
			continue
		}

		puID, _ := puIDFromDockerID(container.ID)

		runtime, err := d.extractMetadata(&container)
		if err != nil {
			continue
		}

		event := common.EventStop
		if container.State.Running {
			if !container.State.Paused {
				event = common.EventStart
			} else {
				event = common.EventPause
			}
		}

		// If it is a host container, we need to activate it as a Linux process. We will
		// override the options that the metadata extractor provided.
		if container.HostConfig.NetworkMode == constants.DockerHostMode {
			options := hostModeOptions(&container)
			options.PolicyExtensions = runtime.Options().PolicyExtensions
			runtime.SetOptions(*options)
			runtime.SetPUType(common.LinuxProcessPU)
		}

		runtime.SetOptions(runtime.Options())

		if err := d.config.Policy.HandlePUEvent(ctx, puID, event, runtime); err != nil {
			zap.L().Error("Unable to sync existing Container",
				zap.String("dockerID", c.ID),
				zap.Error(err),
			)
		}

		// if the container has hostnet set to true or is linked
		// to container with hostnet set to true, program the cgroup.
		if isHostNetworkContainer(runtime) {
			if err = d.setupHostMode(puID, runtime, &container); err != nil {
				return fmt.Errorf("unable to setup host mode for container %s: %s", puID, err)
			}
		}

	}

	return nil
}
937169
func (d *DockerMonitor) setupHostMode(puID string, runtimeInfo policy.RuntimeReader, dockerInfo *types.ContainerJSON) (err error) {

	pausePUID := puID
	if dockerInfo.HostConfig.NetworkMode == constants.DockerHostMode {
		if err = d.netcls.Creategroup(puID); err != nil {
			return err
		}

		// Clean the cgroup on exit, if we have failed t activate.
		defer func() {
			if err != nil {
				if derr := d.netcls.DeleteCgroup(puID); derr != nil {
					zap.L().Warn("Failed to clean cgroup",
						zap.String("puID", puID),
						zap.Error(derr),
						zap.Error(err),
					)
				}
			}
		}()

		markval := runtimeInfo.Options().CgroupMark
		if markval == "" {
			return errors.New("mark value not found")
		}

		mark, _ := strconv.ParseUint(markval, 10, 32)
		if err := d.netcls.AssignMark(puID, mark); err != nil {
			return err
		}
	} else {
		// Add the container pid that is linked to hostnet to
		// the cgroup of the parent container.

		pausePUID = getPausePUID(policyExtensions(runtimeInfo))
	}

	return d.netcls.AddProcess(pausePUID, dockerInfo.State.Pid)
}
299587
func modifyHostOptionsForSandbox(nsOpts *runtimeapi.NamespaceOption, network *knetwork.PluginManager, hc *dockercontainer.HostConfig) {
	if nsOpts.GetIpc() == runtimeapi.NamespaceMode_NODE {
		hc.IpcMode = namespaceModeHost
	}
	if nsOpts.GetNetwork() == runtimeapi.NamespaceMode_NODE {
		hc.NetworkMode = namespaceModeHost
		return
	}

	if network == nil {
		hc.NetworkMode = "default"
		return
	}

	switch network.PluginName() {
	case "cni":
		fallthrough
	case "kubenet":
		hc.NetworkMode = "none"
	default:
		hc.NetworkMode = "default"
	}
}
51932
func hostModeOptions(dockerInfo *types.ContainerJSON) *policy.OptionsType {

	options := policy.OptionsType{
		CgroupName: strconv.Itoa(dockerInfo.State.Pid),
		CgroupMark: strconv.FormatUint(cgnetcls.MarkVal(), 10),
	}

	for p := range dockerInfo.Config.ExposedPorts {
		if p.Proto() == "tcp" {
			s, err := portspec.NewPortSpecFromString(p.Port(), nil)
			if err != nil {
				continue
			}

			options.Services = append(options.Services, common.Service{
				Protocol: uint8(6),
				Ports:    s,
			})
		}
	}

	return &options
}
722664
func GetDockerActive(host *host.Host) (bool, error) {
	statusCmd := `sudo systemctl is-active docker`
	status, err := runSSHCommand(host, statusCmd)
	// systemd returns error code on inactive
	s := strings.TrimSpace(status)
	return err == nil && s == "active", nil
}
272414
func CreateStandaloneHost(f *Folder, spec types.HostConnectSpec) (*HostSystem, types.BaseMethodFault) {
	if spec.HostName == "" {
		return nil, &types.NoHost{}
	}

	pool := NewResourcePool()
	host := NewHostSystem(esx.HostSystem)

	host.Summary.Config.Name = spec.HostName
	host.Name = host.Summary.Config.Name
	host.Runtime.ConnectionState = types.HostSystemConnectionStateDisconnected

	summary := new(types.ComputeResourceSummary)
	addComputeResource(summary, host)

	cr := &mo.ComputeResource{
		ConfigurationEx: &types.ComputeResourceConfigInfo{
			VmSwapPlacement: string(types.VirtualMachineConfigInfoSwapPlacementTypeVmDirectory),
		},
		Summary:            summary,
		EnvironmentBrowser: newEnvironmentBrowser(),
	}

	Map.PutEntity(cr, Map.NewEntity(host))
	host.Summary.Host = &host.Self

	Map.PutEntity(cr, Map.NewEntity(pool))

	cr.Name = host.Name
	cr.Network = Map.getEntityDatacenter(f).defaultNetwork()
	cr.Host = append(cr.Host, host.Reference())
	cr.ResourcePool = &pool.Self

	f.putChild(cr)
	pool.Owner = cr.Self
	host.Network = cr.Network

	return host, nil
}
722575
func NetworkDisconnect(name, container string) error {
	return mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		return cli.NetworkDisconnect(ctx, name, container, false)
	})
}
1267109
func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
	container, err := daemon.GetContainer(containerName)
	if err != nil {
		if force {
			return daemon.ForceEndpointDelete(containerName, networkName)
		}
		return err
	}
	return daemon.DisconnectFromNetwork(container, networkName, force)
}
1215664
func (f Framework) HostPort() (string, string) {
	if f.PID.UPID != nil {
		return f.PID.Host, f.PID.Port
	}
	return f.Hostname, ""
}
1042841
func (u *Unit) containerAddress() (network.Address, error) {
	containerInfo, err := u.cloudContainer()
	if errors.IsNotFound(err) {
		return network.Address{}, network.NoAddressError("container")
	}
	if err != nil {
		return network.Address{}, errors.Trace(err)
	}
	addr := containerInfo.Address
	if addr == nil {
		return network.Address{}, network.NoAddressError("container")
	}
	return addr.networkAddress(), nil
}
954908
func (n *NetworkOpt) NetworkMode() string {
	networkIDOrName := "default"
	netOptVal := n.Value()
	if len(netOptVal) > 0 {
		networkIDOrName = netOptVal[0].Target
	}
	return networkIDOrName
}
1352623
func (c Config) HostUID(containerId int) (int, error) {
	if c.Namespaces.Contains(NEWUSER) {
		if c.UidMappings == nil {
			return -1, fmt.Errorf("User namespaces enabled, but no uid mappings found.")
		}
		id, found := c.hostIDFromMapping(containerId, c.UidMappings)
		if !found {
			return -1, fmt.Errorf("User namespaces enabled, but no user mapping found.")
		}
		return id, nil
	}
	// Return unchanged id.
	return containerId, nil
}
1046155
func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (types.ContainerCreateResponse, error) {
	var response types.ContainerCreateResponse
	query := url.Values{}
	if containerName != "" {
		query.Set("name", containerName)
	}

	body := configWrapper{
		Config:           config,
		HostConfig:       hostConfig,
		NetworkingConfig: networkingConfig,
	}

	serverResp, err := cli.post(ctx, "/containers/create", query, body, nil)
	if err != nil {
		if serverResp.statusCode == 404 && strings.Contains(err.Error(), "No such image") {
			return response, imageNotFoundError{config.Image}
		}
		return response, err
	}

	err = json.NewDecoder(serverResp.body).Decode(&response)
	ensureReaderClosed(serverResp)
	return response, err
}
449883
func (cli *Client) NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error {
	nc := types.NetworkConnect{
		Container:      containerID,
		EndpointConfig: config,
	}
	resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nc, nil)
	ensureReaderClosed(resp)
	return err
}
332871
func (n IpcMode) Container() string {
	parts := strings.SplitN(string(n), ":", 2)
	if len(parts) > 1 && parts[0] == "container" {
		return parts[1]
	}
	return ""
}
553933
func ValidateNetworkOptions(binary string, ctx *cli.Context) (*NetworkConfigs, error) {
	// 1. validate and set plugin mode
	pluginMode := strings.ToLower(ctx.String("mode"))
	switch pluginMode {
	case core.Docker, core.Kubernetes, core.SwarmMode, core.Test:
		logrus.Infof("Using %s mode: %v", binary, pluginMode)
	case "":
		return nil, fmt.Errorf("%s mode is not set", binary)
	default:
		return nil, fmt.Errorf("unknown %s mode: %v", binary, pluginMode)
	}

	// 2. validate and set network mode
	networkMode := strings.ToLower(ctx.String("netmode"))
	switch networkMode {
	case "vlan", "vxlan":
		logrus.Infof("Using %s network mode: %v", binary, networkMode)
	case "":
		return nil, fmt.Errorf("%s network mode is not set", binary)
	default:
		return nil, fmt.Errorf("unknown %s network mode: %v", binary, networkMode)
	}

	// 3. validate forwarding mode
	forwardMode := strings.ToLower(ctx.String("fwdmode"))
	if forwardMode == "" {
		return nil, fmt.Errorf("unknown %s forwarding mode: %v", binary, forwardMode)
	} else if forwardMode != "bridge" && forwardMode != "routing" {
		return nil, fmt.Errorf("%s forwarding mode is not set", binary)
	} else if networkMode == "vxlan" && forwardMode == "bridge" {
		return nil, fmt.Errorf("invalid %s forwarding mode: %q (network mode: %q)", binary, forwardMode, networkMode)
	}
	// vxlan/vlan+routing, vlan+bridge are valid combinations
	logrus.Infof("Using %s forwarding mode: %v", binary, forwardMode)
	return &NetworkConfigs{
		Mode:        pluginMode,
		NetworkMode: networkMode,
		ForwardMode: forwardMode,
	}, nil
}
1348460
func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, update bool) (warnings []string, err error) {
	if hostConfig == nil {
		return nil, nil
	}
	osv := system.GetOSVersion()
	hyperv := daemon.runAsHyperVContainer(hostConfig)

	// On RS5, we allow (but don't strictly support) process isolation on Client SKUs.
	// Prior to RS5, we don't allow process isolation on Client SKUs.
	// @engine maintainers. This block should not be removed. It partially enforces licensing
	// restrictions on Windows. Ping @jhowardmsft if there are concerns or PRs to change this.
	if !hyperv && system.IsWindowsClient() && osv.Build < 17763 {
		return warnings, fmt.Errorf("Windows client operating systems earlier than version 1809 can only run Hyper-V containers")
	}

	w, err := verifyPlatformContainerResources(&hostConfig.Resources, hyperv)
	warnings = append(warnings, w...)
	return warnings, err
}