// convertServerConfig takes an agent config and log output and returns a Nomad
// Config. There may be missing fields that must be set by the agent. To do this
// call finalizeServerConfig
338833
func convertServerConfig(agentConfig *Config) (*nomad.Config, error) {
	conf := agentConfig.NomadConfig
	if conf == nil {
		conf = nomad.DefaultConfig()
	}
	conf.DevMode = agentConfig.DevMode
	conf.Build = agentConfig.Version.VersionNumber()
	if agentConfig.Region != "" {
		conf.Region = agentConfig.Region
	}

	// Set the Authoritative Region if set, otherwise default to
	// the same as the local region.
	if agentConfig.Server.AuthoritativeRegion != "" {
		conf.AuthoritativeRegion = agentConfig.Server.AuthoritativeRegion
	} else if agentConfig.Region != "" {
		conf.AuthoritativeRegion = agentConfig.Region
	}

	if agentConfig.Datacenter != "" {
		conf.Datacenter = agentConfig.Datacenter
	}
	if agentConfig.NodeName != "" {
		conf.NodeName = agentConfig.NodeName
	}
	if agentConfig.Server.BootstrapExpect > 0 {
		if agentConfig.Server.BootstrapExpect == 1 {
			conf.Bootstrap = true
		} else {
			atomic.StoreInt32(&conf.BootstrapExpect, int32(agentConfig.Server.BootstrapExpect))
		}
	}
	if agentConfig.DataDir != "" {
		conf.DataDir = filepath.Join(agentConfig.DataDir, "server")
	}
	if agentConfig.Server.DataDir != "" {
		conf.DataDir = agentConfig.Server.DataDir
	}
	if agentConfig.Server.ProtocolVersion != 0 {
		conf.ProtocolVersion = uint8(agentConfig.Server.ProtocolVersion)
	}
	if agentConfig.Server.RaftProtocol != 0 {
		conf.RaftConfig.ProtocolVersion = raft.ProtocolVersion(agentConfig.Server.RaftProtocol)
	}
	if agentConfig.Server.NumSchedulers != nil {
		conf.NumSchedulers = *agentConfig.Server.NumSchedulers
	}
	if len(agentConfig.Server.EnabledSchedulers) != 0 {
		// Convert to a set and require the core scheduler
		set := make(map[string]struct{}, 4)
		set[structs.JobTypeCore] = struct{}{}
		for _, sched := range agentConfig.Server.EnabledSchedulers {
			set[sched] = struct{}{}
		}

		schedulers := make([]string, 0, len(set))
		for k := range set {
			schedulers = append(schedulers, k)
		}

		conf.EnabledSchedulers = schedulers

	}
	if agentConfig.ACL.Enabled {
		conf.ACLEnabled = true
	}
	if agentConfig.ACL.ReplicationToken != "" {
		conf.ReplicationToken = agentConfig.ACL.ReplicationToken
	}
	if agentConfig.Sentinel != nil {
		conf.SentinelConfig = agentConfig.Sentinel
	}
	if agentConfig.Server.NonVotingServer {
		conf.NonVoter = true
	}
	if agentConfig.Server.RedundancyZone != "" {
		conf.RedundancyZone = agentConfig.Server.RedundancyZone
	}
	if agentConfig.Server.UpgradeVersion != "" {
		conf.UpgradeVersion = agentConfig.Server.UpgradeVersion
	}
	if agentConfig.Autopilot != nil {
		if agentConfig.Autopilot.CleanupDeadServers != nil {
			conf.AutopilotConfig.CleanupDeadServers = *agentConfig.Autopilot.CleanupDeadServers
		}
		if agentConfig.Autopilot.ServerStabilizationTime != 0 {
			conf.AutopilotConfig.ServerStabilizationTime = agentConfig.Autopilot.ServerStabilizationTime
		}
		if agentConfig.Autopilot.LastContactThreshold != 0 {
			conf.AutopilotConfig.LastContactThreshold = agentConfig.Autopilot.LastContactThreshold
		}
		if agentConfig.Autopilot.MaxTrailingLogs != 0 {
			conf.AutopilotConfig.MaxTrailingLogs = uint64(agentConfig.Autopilot.MaxTrailingLogs)
		}
		if agentConfig.Autopilot.EnableRedundancyZones != nil {
			conf.AutopilotConfig.EnableRedundancyZones = *agentConfig.Autopilot.EnableRedundancyZones
		}
		if agentConfig.Autopilot.DisableUpgradeMigration != nil {
			conf.AutopilotConfig.DisableUpgradeMigration = *agentConfig.Autopilot.DisableUpgradeMigration
		}
		if agentConfig.Autopilot.EnableCustomUpgrades != nil {
			conf.AutopilotConfig.EnableCustomUpgrades = *agentConfig.Autopilot.EnableCustomUpgrades
		}
	}

	// Set up the bind addresses
	rpcAddr, err := net.ResolveTCPAddr("tcp", agentConfig.normalizedAddrs.RPC)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse RPC address %q: %v", agentConfig.normalizedAddrs.RPC, err)
	}
	serfAddr, err := net.ResolveTCPAddr("tcp", agentConfig.normalizedAddrs.Serf)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse Serf address %q: %v", agentConfig.normalizedAddrs.Serf, err)
	}
	conf.RPCAddr.Port = rpcAddr.Port
	conf.RPCAddr.IP = rpcAddr.IP
	conf.SerfConfig.MemberlistConfig.BindPort = serfAddr.Port
	conf.SerfConfig.MemberlistConfig.BindAddr = serfAddr.IP.String()

	// Set up the advertise addresses
	rpcAddr, err = net.ResolveTCPAddr("tcp", agentConfig.AdvertiseAddrs.RPC)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse RPC advertise address %q: %v", agentConfig.AdvertiseAddrs.RPC, err)
	}
	serfAddr, err = net.ResolveTCPAddr("tcp", agentConfig.AdvertiseAddrs.Serf)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse Serf advertise address %q: %v", agentConfig.AdvertiseAddrs.Serf, err)
	}

	// Server address is the serf advertise address and rpc port. This is the
	// address that all servers should be able to communicate over RPC with.
	serverAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(serfAddr.IP.String(), fmt.Sprintf("%d", rpcAddr.Port)))
	if err != nil {
		return nil, fmt.Errorf("Failed to resolve Serf advertise address %q: %v", agentConfig.AdvertiseAddrs.Serf, err)
	}

	conf.SerfConfig.MemberlistConfig.AdvertiseAddr = serfAddr.IP.String()
	conf.SerfConfig.MemberlistConfig.AdvertisePort = serfAddr.Port
	conf.ClientRPCAdvertise = rpcAddr
	conf.ServerRPCAdvertise = serverAddr

	// Set up gc threshold and heartbeat grace period
	if gcThreshold := agentConfig.Server.NodeGCThreshold; gcThreshold != "" {
		dur, err := time.ParseDuration(gcThreshold)
		if err != nil {
			return nil, err
		}
		conf.NodeGCThreshold = dur
	}
	if gcThreshold := agentConfig.Server.JobGCThreshold; gcThreshold != "" {
		dur, err := time.ParseDuration(gcThreshold)
		if err != nil {
			return nil, err
		}
		conf.JobGCThreshold = dur
	}
	if gcThreshold := agentConfig.Server.EvalGCThreshold; gcThreshold != "" {
		dur, err := time.ParseDuration(gcThreshold)
		if err != nil {
			return nil, err
		}
		conf.EvalGCThreshold = dur
	}
	if gcThreshold := agentConfig.Server.DeploymentGCThreshold; gcThreshold != "" {
		dur, err := time.ParseDuration(gcThreshold)
		if err != nil {
			return nil, err
		}
		conf.DeploymentGCThreshold = dur
	}

	if heartbeatGrace := agentConfig.Server.HeartbeatGrace; heartbeatGrace != 0 {
		conf.HeartbeatGrace = heartbeatGrace
	}
	if min := agentConfig.Server.MinHeartbeatTTL; min != 0 {
		conf.MinHeartbeatTTL = min
	}
	if maxHPS := agentConfig.Server.MaxHeartbeatsPerSecond; maxHPS != 0 {
		conf.MaxHeartbeatsPerSecond = maxHPS
	}

	if *agentConfig.Consul.AutoAdvertise && agentConfig.Consul.ServerServiceName == "" {
		return nil, fmt.Errorf("server_service_name must be set when auto_advertise is enabled")
	}

	// Add the Consul and Vault configs
	conf.ConsulConfig = agentConfig.Consul
	conf.VaultConfig = agentConfig.Vault

	// Set the TLS config
	conf.TLSConfig = agentConfig.TLSConfig

	// Setup telemetry related config
	conf.StatsCollectionInterval = agentConfig.Telemetry.collectionInterval
	conf.DisableTaggedMetrics = agentConfig.Telemetry.DisableTaggedMetrics
	conf.DisableDispatchedJobSummaryMetrics = agentConfig.Telemetry.DisableDispatchedJobSummaryMetrics
	conf.BackwardsCompatibleMetrics = agentConfig.Telemetry.BackwardsCompatibleMetrics

	return conf, nil
}
1105255
func convertClientConfig(agentConfig *Config) (*clientconfig.Config, error) {
	// Setup the configuration
	conf := agentConfig.ClientConfig
	if conf == nil {
		conf = clientconfig.DefaultConfig()
	}

	conf.Servers = agentConfig.Client.Servers
	conf.LogLevel = agentConfig.LogLevel
	conf.DevMode = agentConfig.DevMode
	if agentConfig.Region != "" {
		conf.Region = agentConfig.Region
	}
	if agentConfig.DataDir != "" {
		conf.StateDir = filepath.Join(agentConfig.DataDir, "client")
		conf.AllocDir = filepath.Join(agentConfig.DataDir, "alloc")
	}
	if agentConfig.Client.StateDir != "" {
		conf.StateDir = agentConfig.Client.StateDir
	}
	if agentConfig.Client.AllocDir != "" {
		conf.AllocDir = agentConfig.Client.AllocDir
	}
	if agentConfig.Client.NetworkInterface != "" {
		conf.NetworkInterface = agentConfig.Client.NetworkInterface
	}
	conf.ChrootEnv = agentConfig.Client.ChrootEnv
	conf.Options = agentConfig.Client.Options
	if agentConfig.Client.NetworkSpeed != 0 {
		conf.NetworkSpeed = agentConfig.Client.NetworkSpeed
	}
	if agentConfig.Client.CpuCompute != 0 {
		conf.CpuCompute = agentConfig.Client.CpuCompute
	}
	if agentConfig.Client.MemoryMB != 0 {
		conf.MemoryMB = agentConfig.Client.MemoryMB
	}
	if agentConfig.Client.MaxKillTimeout != "" {
		dur, err := time.ParseDuration(agentConfig.Client.MaxKillTimeout)
		if err != nil {
			return nil, fmt.Errorf("Error parsing max kill timeout: %s", err)
		}
		conf.MaxKillTimeout = dur
	}
	conf.ClientMaxPort = uint(agentConfig.Client.ClientMaxPort)
	conf.ClientMinPort = uint(agentConfig.Client.ClientMinPort)

	// Setup the node
	conf.Node = new(structs.Node)
	conf.Node.Datacenter = agentConfig.Datacenter
	conf.Node.Name = agentConfig.NodeName
	conf.Node.Meta = agentConfig.Client.Meta
	conf.Node.NodeClass = agentConfig.Client.NodeClass

	// Set up the HTTP advertise address
	conf.Node.HTTPAddr = agentConfig.AdvertiseAddrs.HTTP

	// Reserve resources on the node.
	// COMPAT(0.10): Remove in 0.10
	r := conf.Node.Reserved
	if r == nil {
		r = new(structs.Resources)
		conf.Node.Reserved = r
	}
	r.CPU = agentConfig.Client.Reserved.CPU
	r.MemoryMB = agentConfig.Client.Reserved.MemoryMB
	r.DiskMB = agentConfig.Client.Reserved.DiskMB

	res := conf.Node.ReservedResources
	if res == nil {
		res = new(structs.NodeReservedResources)
		conf.Node.ReservedResources = res
	}
	res.Cpu.CpuShares = int64(agentConfig.Client.Reserved.CPU)
	res.Memory.MemoryMB = int64(agentConfig.Client.Reserved.MemoryMB)
	res.Disk.DiskMB = int64(agentConfig.Client.Reserved.DiskMB)
	res.Networks.ReservedHostPorts = agentConfig.Client.Reserved.ReservedPorts

	conf.Version = agentConfig.Version

	if *agentConfig.Consul.AutoAdvertise && agentConfig.Consul.ClientServiceName == "" {
		return nil, fmt.Errorf("client_service_name must be set when auto_advertise is enabled")
	}

	conf.ConsulConfig = agentConfig.Consul
	conf.VaultConfig = agentConfig.Vault

	// Set up Telemetry configuration
	conf.StatsCollectionInterval = agentConfig.Telemetry.collectionInterval
	conf.PublishNodeMetrics = agentConfig.Telemetry.PublishNodeMetrics
	conf.PublishAllocationMetrics = agentConfig.Telemetry.PublishAllocationMetrics
	conf.DisableTaggedMetrics = agentConfig.Telemetry.DisableTaggedMetrics
	conf.BackwardsCompatibleMetrics = agentConfig.Telemetry.BackwardsCompatibleMetrics

	// Set the TLS related configs
	conf.TLSConfig = agentConfig.TLSConfig
	conf.Node.TLSEnabled = conf.TLSConfig.EnableHTTP

	// Set the GC related configs
	conf.GCInterval = agentConfig.Client.GCInterval
	conf.GCParallelDestroys = agentConfig.Client.GCParallelDestroys
	conf.GCDiskUsageThreshold = agentConfig.Client.GCDiskUsageThreshold
	conf.GCInodeUsageThreshold = agentConfig.Client.GCInodeUsageThreshold
	conf.GCMaxAllocs = agentConfig.Client.GCMaxAllocs
	if agentConfig.Client.NoHostUUID != nil {
		conf.NoHostUUID = *agentConfig.Client.NoHostUUID
	} else {
		// Default no_host_uuid to true
		conf.NoHostUUID = true
	}

	// Setup the ACLs
	conf.ACLEnabled = agentConfig.ACL.Enabled
	conf.ACLTokenTTL = agentConfig.ACL.TokenTTL
	conf.ACLPolicyTTL = agentConfig.ACL.PolicyTTL

	return conf, nil
}
318844
func Convert_v1_JenkinsPipelineConfig_To_config_JenkinsPipelineConfig(in *v1.JenkinsPipelineConfig, out *config.JenkinsPipelineConfig, s conversion.Scope) error {
	return autoConvert_v1_JenkinsPipelineConfig_To_config_JenkinsPipelineConfig(in, out, s)
}
911362
func Convert_v1_PolicyConfig_To_config_PolicyConfig(in *v1.PolicyConfig, out *config.PolicyConfig, s conversion.Scope) error {
	return autoConvert_v1_PolicyConfig_To_config_PolicyConfig(in, out, s)
}
4383
func Convert_v1_ImageConfig_To_config_ImageConfig(in *v1.ImageConfig, out *config.ImageConfig, s conversion.Scope) error {
	return autoConvert_v1_ImageConfig_To_config_ImageConfig(in, out, s)
}
108003
func Convert_v1_NodeAuthConfig_To_config_NodeAuthConfig(in *v1.NodeAuthConfig, out *config.NodeAuthConfig, s conversion.Scope) error {
	return autoConvert_v1_NodeAuthConfig_To_config_NodeAuthConfig(in, out, s)
}
775740
func (op *CaasOperatorAgent) ChangeConfig(mutate agent.ConfigMutator) error {
	err := op.AgentConf.ChangeConfig(mutate)
	op.configChangedVal.Set(true)
	return errors.Trace(err)
}
466377
func Convert_v1_EtcdConfig_To_config_EtcdConfig(in *v1.EtcdConfig, out *config.EtcdConfig, s conversion.Scope) error {
	return autoConvert_v1_EtcdConfig_To_config_EtcdConfig(in, out, s)
}
624462
func ConvertPortToPortConfig(
	port nat.Port,
	portBindings map[nat.Port][]nat.PortBinding,
) ([]swarm.PortConfig, error) {
	ports := []swarm.PortConfig{}

	for _, binding := range portBindings[port] {
		hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16)
		if err != nil && binding.HostPort != "" {
			return nil, fmt.Errorf("invalid hostport binding (%s) for port (%s)", binding.HostPort, port.Port())
		}
		ports = append(ports, swarm.PortConfig{
			//TODO Name: ?
			Protocol:      swarm.PortConfigProtocol(strings.ToLower(port.Proto())),
			TargetPort:    uint32(port.Int()),
			PublishedPort: uint32(hostPort),
			PublishMode:   swarm.PortConfigPublishModeIngress,
		})
	}
	return ports, nil
}
1022253
func DefaultConfig() *Config {
	config := &Config{
		Address:    "http://127.0.0.1:4646",
		httpClient: cleanhttp.DefaultClient(),
		TLSConfig:  &TLSConfig{},
	}
	transport := config.httpClient.Transport.(*http.Transport)
	transport.TLSHandshakeTimeout = 10 * time.Second
	transport.TLSClientConfig = &tls.Config{
		MinVersion: tls.VersionTLS12,
	}

	if addr := os.Getenv("NOMAD_ADDR"); addr != "" {
		config.Address = addr
	}
	if v := os.Getenv("NOMAD_REGION"); v != "" {
		config.Region = v
	}
	if v := os.Getenv("NOMAD_NAMESPACE"); v != "" {
		config.Namespace = v
	}
	if auth := os.Getenv("NOMAD_HTTP_AUTH"); auth != "" {
		var username, password string
		if strings.Contains(auth, ":") {
			split := strings.SplitN(auth, ":", 2)
			username = split[0]
			password = split[1]
		} else {
			username = auth
		}

		config.HttpAuth = &HttpBasicAuth{
			Username: username,
			Password: password,
		}
	}

	// Read TLS specific env vars
	if v := os.Getenv("NOMAD_CACERT"); v != "" {
		config.TLSConfig.CACert = v
	}
	if v := os.Getenv("NOMAD_CAPATH"); v != "" {
		config.TLSConfig.CAPath = v
	}
	if v := os.Getenv("NOMAD_CLIENT_CERT"); v != "" {
		config.TLSConfig.ClientCert = v
	}
	if v := os.Getenv("NOMAD_CLIENT_KEY"); v != "" {
		config.TLSConfig.ClientKey = v
	}
	if v := os.Getenv("NOMAD_SKIP_VERIFY"); v != "" {
		if insecure, err := strconv.ParseBool(v); err == nil {
			config.TLSConfig.Insecure = insecure
		}
	}
	if v := os.Getenv("NOMAD_TOKEN"); v != "" {
		config.SecretID = v
	}
	return config
}
406141
func Convert_v1_LDAPSyncConfig_To_config_LDAPSyncConfig(in *v1.LDAPSyncConfig, out *config.LDAPSyncConfig, s conversion.Scope) error {
	return autoConvert_v1_LDAPSyncConfig_To_config_LDAPSyncConfig(in, out, s)
}
543500
func AgentConfig(u string) (*ssh.ClientConfig, error) {
	a, err := Get()
	if err != nil {
		return nil, err
	}

	config := &ssh.ClientConfig{
		User: u,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeysCallback(a.Signers),
		},
	}
	return config, nil
}
285002
func Convert_v1_DNSConfig_To_config_DNSConfig(in *v1.DNSConfig, out *config.DNSConfig, s conversion.Scope) error {
	return autoConvert_v1_DNSConfig_To_config_DNSConfig(in, out, s)
}
1256559
func Convert_v1_DeploymentConfig_To_apps_DeploymentConfig(in *v1.DeploymentConfig, out *apps.DeploymentConfig, s conversion.Scope) error {
	return autoConvert_v1_DeploymentConfig_To_apps_DeploymentConfig(in, out, s)
}
554648
func ConvertServices(v1Services map[string]*ServiceConfigV1) (map[string]*ServiceConfig, error) {
	v2Services := make(map[string]*ServiceConfig)
	replacementFields := make(map[string]*ServiceConfig)

	for name, service := range v1Services {
		replacementFields[name] = &ServiceConfig{
			Build: yaml.Build{
				Context:    service.Build,
				Dockerfile: service.Dockerfile,
			},
			Logging: Log{
				Driver:  service.LogDriver,
				Options: service.LogOpt,
			},
			NetworkMode: service.Net,
		}

		v1Services[name].Build = ""
		v1Services[name].Dockerfile = ""
		v1Services[name].LogDriver = ""
		v1Services[name].LogOpt = nil
		v1Services[name].Net = ""
	}

	if err := utils.Convert(v1Services, &v2Services); err != nil {
		return nil, err
	}

	for name := range v2Services {
		v2Services[name].Build = replacementFields[name].Build
		v2Services[name].Logging = replacementFields[name].Logging
		v2Services[name].NetworkMode = replacementFields[name].NetworkMode
	}

	return v2Services, nil
}
200400
func Convert_v1_ServiceAccountConfig_To_config_ServiceAccountConfig(in *v1.ServiceAccountConfig, out *config.ServiceAccountConfig, s conversion.Scope) error {
	return autoConvert_v1_ServiceAccountConfig_To_config_ServiceAccountConfig(in, out, s)
}
63643
func Convert(c *config.ServiceConfig, ctx project.Context, clientFactory composeclient.Factory) (*container.Config, *container.HostConfig, error) {
	restartPolicy, err := restartPolicy(c)
	if err != nil {
		return nil, nil, err
	}

	exposedPorts, portBindings, err := ports(c)
	if err != nil {
		return nil, nil, err
	}

	deviceMappings, err := parseDevices(c.Devices)
	if err != nil {
		return nil, nil, err
	}

	var volumesFrom []string
	if c.VolumesFrom != nil {
		volumesFrom, err = getVolumesFrom(c.VolumesFrom, ctx.Project.ServiceConfigs, ctx.ProjectName)
		if err != nil {
			return nil, nil, err
		}
	}

	vols := volumes(c, ctx)

	config := &container.Config{
		Entrypoint:   strslice.StrSlice(utils.CopySlice(c.Entrypoint)),
		Hostname:     c.Hostname,
		Domainname:   c.DomainName,
		User:         c.User,
		Env:          utils.CopySlice(c.Environment),
		Cmd:          strslice.StrSlice(utils.CopySlice(c.Command)),
		Image:        c.Image,
		Labels:       utils.CopyMap(c.Labels),
		ExposedPorts: exposedPorts,
		Tty:          c.Tty,
		OpenStdin:    c.StdinOpen,
		WorkingDir:   c.WorkingDir,
		Volumes:      toMap(Filter(vols, isVolume)),
		MacAddress:   c.MacAddress,
		StopSignal:   c.StopSignal,
		StopTimeout:  utils.DurationStrToSecondsInt(c.StopGracePeriod),
	}

	ulimits := []*units.Ulimit{}
	if c.Ulimits.Elements != nil {
		for _, ulimit := range c.Ulimits.Elements {
			ulimits = append(ulimits, &units.Ulimit{
				Name: ulimit.Name,
				Soft: ulimit.Soft,
				Hard: ulimit.Hard,
			})
		}
	}

	memorySwappiness := int64(c.MemSwappiness)

	resources := container.Resources{
		CgroupParent:      c.CgroupParent,
		Memory:            int64(c.MemLimit),
		MemoryReservation: int64(c.MemReservation),
		MemorySwap:        int64(c.MemSwapLimit),
		MemorySwappiness:  &memorySwappiness,
		CPUShares:         int64(c.CPUShares),
		CPUQuota:          int64(c.CPUQuota),
		CpusetCpus:        c.CPUSet,
		Ulimits:           ulimits,
		Devices:           deviceMappings,
		OomKillDisable:    &c.OomKillDisable,
	}

	networkMode := c.NetworkMode
	if c.NetworkMode == "" {
		if c.Networks != nil && len(c.Networks.Networks) > 0 {
			networkMode = c.Networks.Networks[0].RealName
		}
	} else {
		switch {
		case strings.HasPrefix(c.NetworkMode, "service:"):
			serviceName := c.NetworkMode[8:]
			if serviceConfig, ok := ctx.Project.ServiceConfigs.Get(serviceName); ok {
				// FIXME(vdemeester) this is actually not right, should be fixed but not there
				service, err := ctx.ServiceFactory.Create(ctx.Project, serviceName, serviceConfig)
				if err != nil {
					return nil, nil, err
				}
				containers, err := service.Containers(context.Background())
				if err != nil {
					return nil, nil, err
				}
				if len(containers) != 0 {
					container := containers[0]
					containerID := container.ID()
					networkMode = "container:" + containerID
				}
				// FIXME(vdemeester) log/warn in case of len(containers) == 0
			}
		case strings.HasPrefix(c.NetworkMode, "container:"):
			containerName := c.NetworkMode[10:]
			client := clientFactory.Create(nil)
			container, err := composecontainer.Get(context.Background(), client, containerName)
			if err != nil {
				return nil, nil, err
			}
			networkMode = "container:" + container.ID
		default:
			// do nothing :)
		}
	}

	tmpfs := map[string]string{}
	for _, path := range c.Tmpfs {
		split := strings.SplitN(path, ":", 2)
		if len(split) == 1 {
			tmpfs[split[0]] = ""
		} else if len(split) == 2 {
			tmpfs[split[0]] = split[1]
		}
	}

	hostConfig := &container.HostConfig{
		VolumesFrom: volumesFrom,
		CapAdd:      strslice.StrSlice(utils.CopySlice(c.CapAdd)),
		CapDrop:     strslice.StrSlice(utils.CopySlice(c.CapDrop)),
		GroupAdd:    c.GroupAdd,
		ExtraHosts:  utils.CopySlice(c.ExtraHosts),
		Privileged:  c.Privileged,
		Binds:       Filter(vols, isBind),
		DNS:         utils.CopySlice(c.DNS),
		DNSOptions:  utils.CopySlice(c.DNSOpts),
		DNSSearch:   utils.CopySlice(c.DNSSearch),
		Isolation:   container.Isolation(c.Isolation),
		LogConfig: container.LogConfig{
			Type:   c.Logging.Driver,
			Config: utils.CopyMap(c.Logging.Options),
		},
		NetworkMode:    container.NetworkMode(networkMode),
		ReadonlyRootfs: c.ReadOnly,
		OomScoreAdj:    int(c.OomScoreAdj),
		PidMode:        container.PidMode(c.Pid),
		UTSMode:        container.UTSMode(c.Uts),
		IpcMode:        container.IpcMode(c.Ipc),
		PortBindings:   portBindings,
		RestartPolicy:  *restartPolicy,
		ShmSize:        int64(c.ShmSize),
		SecurityOpt:    utils.CopySlice(c.SecurityOpt),
		Tmpfs:          tmpfs,
		VolumeDriver:   c.VolumeDriver,
		Resources:      resources,
	}

	if config.Labels == nil {
		config.Labels = map[string]string{}
	}

	return config, hostConfig, nil
}