本文整理汇总了Golang中github.com/docker/docker/api/types/container.HostConfig类的典型用法代码示例。如果您正苦于以下问题:Golang HostConfig类的具体用法?Golang HostConfig怎么用?Golang HostConfig使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HostConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: adaptContainerSettings
// adaptContainerSettings is called during container creation to modify any
// settings necessary in the HostConfig structure.
func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
if adjustCPUShares && hostConfig.CPUShares > 0 {
// Handle unsupported CPUShares
if hostConfig.CPUShares < linuxMinCPUShares {
logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
hostConfig.CPUShares = linuxMinCPUShares
} else if hostConfig.CPUShares > linuxMaxCPUShares {
logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
hostConfig.CPUShares = linuxMaxCPUShares
}
}
if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
// By default, MemorySwap is set to twice the size of Memory.
hostConfig.MemorySwap = hostConfig.Memory * 2
}
if hostConfig.ShmSize == 0 {
hostConfig.ShmSize = container.DefaultSHMSize
}
var err error
if hostConfig.SecurityOpt == nil {
hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode)
if err != nil {
return err
}
}
if hostConfig.MemorySwappiness == nil {
defaultSwappiness := int64(-1)
hostConfig.MemorySwappiness = &defaultSwappiness
}
return nil
}
示例2: createRoach
// createRoach creates the docker container for a testNode. It may be called in
// parallel to start many nodes at once, and thus should remain threadsafe.
func (l *LocalCluster) createRoach(
ctx context.Context, node *testNode, vols *Container, env []string, cmd ...string,
) {
l.panicOnStop()
hostConfig := container.HostConfig{
PublishAllPorts: true,
NetworkMode: container.NetworkMode(l.networkID),
Privileged: l.privileged,
}
if vols != nil {
hostConfig.VolumesFrom = append(hostConfig.VolumesFrom, vols.id)
}
var hostname string
if node.index >= 0 {
hostname = fmt.Sprintf("roach-%s-%d", l.clusterID, node.index)
}
log.Infof(ctx, "creating docker container with name: %s", hostname)
var entrypoint []string
if *cockroachImage == builderImageFull {
entrypoint = append(entrypoint, CockroachBinaryInContainer)
} else if *cockroachEntry != "" {
entrypoint = append(entrypoint, *cockroachEntry)
}
var err error
node.Container, err = createContainer(
ctx,
l,
container.Config{
Hostname: hostname,
Image: *cockroachImage,
ExposedPorts: map[nat.Port]struct{}{
DefaultTCP: {},
defaultHTTP: {},
},
Entrypoint: entrypoint,
Env: env,
Cmd: cmd,
Labels: map[string]string{
// Allow for `docker ps --filter label=Hostname=roach-<id>-0` or `--filter label=Roach`.
"Hostname": hostname,
"Roach": "",
"Acceptance-cluster-id": l.clusterID,
},
},
hostConfig,
node.nodeStr,
)
maybePanic(err)
}
示例3: adaptContainerSettings
// adaptContainerSettings is called during container creation to modify any
// settings necessary in the HostConfig structure.
func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
if hostConfig == nil {
return nil
}
if hostConfig.CPUShares < 0 {
logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, windowsMinCPUShares)
hostConfig.CPUShares = windowsMinCPUShares
} else if hostConfig.CPUShares > windowsMaxCPUShares {
logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, windowsMaxCPUShares)
hostConfig.CPUShares = windowsMaxCPUShares
}
return nil
}
示例4: ContainerCreate
// ContainerCreate creates a new container based in the given configuration.
// It can be associated with a name, but it's not mandatory.
func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) {
var response container.ContainerCreateCreatedBody
if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
return response, err
}
// When using API 1.24 and under, the client is responsible for removing the container
if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") {
hostConfig.AutoRemove = false
}
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
}
示例5: OneShot
// OneShot runs a container, expecting it to successfully run to completion
// and die, after which it is removed. Not goroutine safe: only one OneShot
// can be running at once.
// Adds the same binds as the cluster containers (certs, binary, etc).
func (l *LocalCluster) OneShot(
ctx context.Context,
ref string,
ipo types.ImagePullOptions,
containerConfig container.Config,
hostConfig container.HostConfig,
name string,
) error {
if err := pullImage(ctx, l, ref, ipo); err != nil {
return err
}
hostConfig.VolumesFrom = []string{l.vols.id}
container, err := createContainer(ctx, l, containerConfig, hostConfig, name)
if err != nil {
return err
}
l.oneshot = container
defer func() {
if err := l.oneshot.Remove(ctx); err != nil {
log.Errorf(ctx, "ContainerRemove: %s", err)
}
l.oneshot = nil
}()
if err := l.oneshot.Start(ctx); err != nil {
return err
}
if err := l.oneshot.Wait(ctx); err != nil {
return err
}
return nil
}
示例6: verifyPlatformContainerSettings
// verifyPlatformContainerSettings performs platform-specific validation of the
// hostconfig and config structures.
func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
warnings := []string{}
sysInfo := sysinfo.New(true)
warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
if err != nil {
return warnings, err
}
w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
// no matter err is nil or not, w could have data in itself.
warnings = append(warnings, w...)
if err != nil {
return warnings, err
}
if hostConfig.ShmSize < 0 {
return warnings, fmt.Errorf("SHM size can not be less than 0")
}
if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
}
// ip-forwarding does not affect container with '--net=host' (or '--net=none')
if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
}
// check for various conflicting options with user namespaces
if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
if hostConfig.Privileged {
return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
}
if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
}
if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
}
}
if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
// CgroupParent for systemd cgroup should be named as "xxx.slice"
if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
}
}
if hostConfig.Runtime == "" {
hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
}
if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
}
return warnings, nil
}
示例7: 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
}
示例8: populateAdditionalHostConfig
func (s *Service) populateAdditionalHostConfig(hostConfig *containertypes.HostConfig) error {
links, err := s.getLinks()
if err != nil {
return err
}
for _, link := range s.DependentServices() {
if !s.project.ServiceConfigs.Has(link.Target) {
continue
}
service, err := s.project.CreateService(link.Target)
if err != nil {
return err
}
containers, err := service.Containers(context.Background())
if err != nil {
return err
}
if link.Type == project.RelTypeIpcNamespace {
hostConfig, err = addIpc(hostConfig, service, containers, s.serviceConfig.Ipc)
} else if link.Type == project.RelTypeNetNamespace {
hostConfig, err = addNetNs(hostConfig, service, containers, s.serviceConfig.NetworkMode)
}
if err != nil {
return err
}
}
hostConfig.Links = []string{}
for k, v := range links {
hostConfig.Links = append(hostConfig.Links, strings.Join([]string{v, k}, ":"))
}
for _, v := range s.serviceConfig.ExternalLinks {
hostConfig.Links = append(hostConfig.Links, v)
}
return nil
}
示例9: 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(context.Background(), &containerConfig, &hostConfig, nil, containerName)
if err != nil {
return nil, err
}
return &Container{
id: resp.ID,
name: containerName,
cluster: l,
}, nil
}
示例10: adaptContainerSettings
// adaptContainerSettings is called during container creation to modify any
// settings necessary in the HostConfig structure.
func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
if hostConfig == nil {
return nil
}
numCPU := int64(sysinfo.NumCPU())
if hostConfig.CPUCount < 0 {
logrus.Warnf("Changing requested CPUCount of %d to minimum allowed of %d", hostConfig.CPUCount, windowsMinCPUCount)
hostConfig.CPUCount = windowsMinCPUCount
} else if hostConfig.CPUCount > numCPU {
logrus.Warnf("Changing requested CPUCount of %d to current number of processors, %d", hostConfig.CPUCount, numCPU)
hostConfig.CPUCount = numCPU
}
if hostConfig.CPUShares < 0 {
logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, windowsMinCPUShares)
hostConfig.CPUShares = windowsMinCPUShares
} else if hostConfig.CPUShares > windowsMaxCPUShares {
logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, windowsMaxCPUShares)
hostConfig.CPUShares = windowsMaxCPUShares
}
if hostConfig.CPUPercent < 0 {
logrus.Warnf("Changing requested CPUPercent of %d to minimum allowed of %d", hostConfig.CPUPercent, windowsMinCPUPercent)
hostConfig.CPUPercent = windowsMinCPUPercent
} else if hostConfig.CPUPercent > windowsMaxCPUPercent {
logrus.Warnf("Changing requested CPUPercent of %d to maximum allowed of %d", hostConfig.CPUPercent, windowsMaxCPUPercent)
hostConfig.CPUPercent = windowsMaxCPUPercent
}
return nil
}
示例11: addIpc
func addIpc(config *containertypes.HostConfig, service project.Service, containers []project.Container, ipc string) (*containertypes.HostConfig, error) {
if len(containers) == 0 {
return nil, fmt.Errorf("Failed to find container for IPC %v", ipc)
}
id, err := containers[0].ID()
if err != nil {
return nil, err
}
config.IpcMode = containertypes.IpcMode("container:" + id)
return config, nil
}
示例12: 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
}
示例13: mergeUlimits
// mergeUlimits merge the Ulimits from HostConfig with daemon defaults, and update HostConfig
func (daemon *Daemon) mergeUlimits(c *containertypes.HostConfig) {
ulimits := c.Ulimits
// Merge ulimits with daemon defaults
ulIdx := make(map[string]struct{})
for _, ul := range ulimits {
ulIdx[ul.Name] = struct{}{}
}
for name, ul := range daemon.configStore.Ulimits {
if _, exists := ulIdx[name]; !exists {
ulimits = append(ulimits, ul)
}
}
c.Ulimits = ulimits
}
示例14: adaptContainerSettings
func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
if hostConfig.CPUShares < 0 {
logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, solarisMinCPUShares)
hostConfig.CPUShares = solarisMinCPUShares
} else if hostConfig.CPUShares > solarisMaxCPUShares {
logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, solarisMaxCPUShares)
hostConfig.CPUShares = solarisMaxCPUShares
}
if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
// By default, MemorySwap is set to twice the size of Memory.
hostConfig.MemorySwap = hostConfig.Memory * 2
}
if hostConfig.ShmSize != 0 {
hostConfig.ShmSize = container.DefaultSHMSize
}
if hostConfig.OomKillDisable == nil {
defaultOomKillDisable := false
hostConfig.OomKillDisable = &defaultOomKillDisable
}
return nil
}
示例15: registerLinks
// registerLinks writes the links to a file.
func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
if hostConfig == nil || hostConfig.Links == nil {
return nil
}
for _, l := range hostConfig.Links {
name, alias, err := runconfigopts.ParseLink(l)
if err != nil {
return err
}
child, err := daemon.GetContainer(name)
if err != nil {
//An error from daemon.GetContainer() means this name could not be found
return fmt.Errorf("Could not get container for %s", name)
}
for child.HostConfig.NetworkMode.IsContainer() {
parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
child, err = daemon.GetContainer(parts[1])
if err != nil {
return fmt.Errorf("Could not get container for %s", parts[1])
}
}
if child.HostConfig.NetworkMode.IsHost() {
return runconfig.ErrConflictHostNetworkAndLinks
}
if err := daemon.registerLink(container, child, alias); err != nil {
return err
}
}
// After we load all the links into the daemon
// set them to nil on the hostconfig
hostConfig.Links = nil
if err := container.WriteHostConfig(); err != nil {
return err
}
return nil
}