// ContainerManagerConfig returns information from the model config that is
// needed for configuring the container manager.
167766
func (p *ProvisionerAPI) ContainerManagerConfig(args params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) {
	var result params.ContainerManagerConfig
	cfg := make(map[string]string)
	cfg[container.ConfigModelUUID] = p.st.ModelUUID()

	switch args.Type {
	case instance.LXD:
		// TODO(jam): DefaultMTU needs to be handled here
	}

	mConfig, err := p.m.ModelConfig()
	if err != nil {
		return result, err
	}
	if url, set := mConfig.ContainerImageMetadataURL(); set {
		cfg[config.ContainerImageMetadataURLKey] = url
	}
	cfg[config.ContainerImageStreamKey] = mConfig.ContainerImageStream()

	result.ManagerConfig = cfg
	return result, nil
}
558861
func (p *Project) Config() (string, error) {
	cfg := ExportedConfig{
		Version:  "2.0",
		Services: p.ServiceConfigs.All(),
		Volumes:  p.VolumeConfigs,
		Networks: p.NetworkConfigs,
	}

	bytes, err := yaml.Marshal(cfg)
	return string(bytes), err
}
773899
func (b *DockerBuilder) buildSysconfig(c *fi.ModelBuilderContext) error {
	var docker kops.DockerConfig
	if b.Cluster.Spec.Docker != nil {
		docker = *b.Cluster.Spec.Docker
	}

	// ContainerOS now sets the storage flag in /etc/docker/daemon.json, and it is an error to set it twice
	if b.Distribution == distros.DistributionContainerOS {
		// So that we can support older COS images though, we do check for /etc/docker/daemon.json
		if b, err := ioutil.ReadFile("/etc/docker/daemon.json"); err != nil {
			if os.IsNotExist(err) {
				glog.V(2).Infof("/etc/docker/daemon.json not found")
			} else {
				glog.Warningf("error reading /etc/docker/daemon.json: %v", err)
			}
		} else {
			// Maybe we get smarter here?
			data := make(map[string]interface{})
			if err := json.Unmarshal(b, &data); err != nil {
				glog.Warningf("error deserializing /etc/docker/daemon.json: %v", err)
			} else {
				storageDriver := data["storage-driver"]
				glog.Infof("/etc/docker/daemon.json has storage-driver: %q", storageDriver)
			}
			docker.Storage = nil
		}
	}

	// RHEL-family / docker has a bug with 17.x where it fails to use overlay2 because it does a broken kernel check
	if b.Distribution.IsRHELFamily() {
		dockerVersion := b.dockerVersion()
		if strings.HasPrefix(dockerVersion, "17.") {
			storageOpts := strings.Join(docker.StorageOpts, ",")
			if strings.Contains(storageOpts, "overlay2.override_kernel_check=1") {
				// Already there
			} else if !strings.Contains(storageOpts, "overlay2.override_kernel_check") {
				docker.StorageOpts = append(docker.StorageOpts, "overlay2.override_kernel_check=1")
			} else {
				glog.Infof("detected image was RHEL and overlay2.override_kernel_check=1 was probably needed, but overlay2.override_kernel_check was already set (%q) so won't set", storageOpts)
			}
		}
	}

	flagsString, err := flagbuilder.BuildFlags(&docker)
	if err != nil {
		return fmt.Errorf("error building docker flags: %v", err)
	}

	lines := []string{
		"DOCKER_OPTS=" + flagsString,
		"DOCKER_NOFILE=1000000",
	}
	contents := strings.Join(lines, "\n")

	c.AddTask(&nodetasks.File{
		Path:     "/etc/sysconfig/docker",
		Contents: fi.NewStringResource(contents),
		Type:     nodetasks.FileType_File,
	})

	return nil
}
885330
func DialContainerManagementProtocolService(host string, port int) (ContainerManagementProtocolService, error) {
	clientId, _ := uuid.NewV4()
	ugi, _ := gohadoop.CreateSimpleUGIProto()
	c := &hadoop_ipc_client.Client{ClientId: clientId, Ugi: ugi, ServerAddress: net.JoinHostPort(host, strconv.Itoa(port))}
	return &ContainerManagementProtocolServiceClient{c}, nil
}
1039109
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 = config.DefaultShmSize
		if daemon.configStore != nil {
			hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
		}
	}
	// Set default IPC mode, if unset for container
	if hostConfig.IpcMode.IsEmpty() {
		m := config.DefaultIpcMode
		if daemon.configStore != nil {
			m = daemon.configStore.IpcMode
		}
		hostConfig.IpcMode = containertypes.IpcMode(m)
	}

	adaptSharedNamespaceContainer(daemon, hostConfig)

	var err error
	opts, err := daemon.generateSecurityOpt(hostConfig)
	if err != nil {
		return err
	}
	hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, opts...)
	if hostConfig.OomKillDisable == nil {
		defaultOomKillDisable := false
		hostConfig.OomKillDisable = &defaultOomKillDisable
	}

	return nil
}
255127
func (d *Driver) createContainer(client createContainerClient, config docker.CreateContainerOptions,
	driverConfig *TaskConfig) (*docker.Container, error) {
	// Create a container
	attempted := 0
CREATE:
	container, createErr := client.CreateContainer(config)
	if createErr == nil {
		return container, nil
	}

	d.logger.Debug("failed to create container", "container_name",
		config.Name, "image_name", driverConfig.Image, "image_id", config.Config.Image,
		"attempt", attempted+1, "error", createErr)

	// Volume management tools like Portworx may not have detached a volume
	// from a previous node before Nomad started a task replacement task.
	// Treat these errors as recoverable so we retry.
	if strings.Contains(strings.ToLower(createErr.Error()), "volume is attached on another node") {
		return nil, nstructs.NewRecoverableError(createErr, true)
	}

	// If the container already exists determine whether it's already
	// running or if it's dead and needs to be recreated.
	if strings.Contains(strings.ToLower(createErr.Error()), "container already exists") {
		containers, err := client.ListContainers(docker.ListContainersOptions{
			All: true,
		})
		if err != nil {
			d.logger.Error("failed to query list of containers matching name", "container_name", config.Name)
			return nil, recoverableErrTimeouts(fmt.Errorf("Failed to query list of containers: %s", err))
		}

		// Delete matching containers
		// Adding a / infront of the container name since Docker returns the
		// container names with a / pre-pended to the Nomad generated container names
		containerName := "/" + config.Name
		d.logger.Debug("searching for container to purge", "container_name", containerName)
		for _, shimContainer := range containers {
			d.logger.Debug("listed container", "names", hclog.Fmt("%+v", shimContainer.Names))
			found := false
			for _, name := range shimContainer.Names {
				if name == containerName {
					d.logger.Debug("Found container", "containter_name", containerName, "container_id", shimContainer.ID)
					found = true
					break
				}
			}

			if !found {
				continue
			}

			// Inspect the container and if the container isn't dead then return
			// the container
			container, err := client.InspectContainer(shimContainer.ID)
			if err != nil {
				err = fmt.Errorf("Failed to inspect container %s: %s", shimContainer.ID, err)

				// This error is always recoverable as it could
				// be caused by races between listing
				// containers and this container being removed.
				// See #2802
				return nil, nstructs.NewRecoverableError(err, true)
			}
			if container != nil && container.State.Running {
				return container, nil
			}

			err = client.RemoveContainer(docker.RemoveContainerOptions{
				ID:    container.ID,
				Force: true,
			})
			if err != nil {
				d.logger.Error("failed to purge container", "container_id", container.ID)
				return nil, recoverableErrTimeouts(fmt.Errorf("Failed to purge container %s: %s", container.ID, err))
			} else if err == nil {
				d.logger.Info("purged container", "container_id", container.ID)
			}
		}

		if attempted < 5 {
			attempted++
			time.Sleep(1 * time.Second)
			goto CREATE
		}
	} else if strings.Contains(strings.ToLower(createErr.Error()), "no such image") {
		// There is still a very small chance this is possible even with the
		// coordinator so retry.
		return nil, nstructs.NewRecoverableError(createErr, true)
	}

	return nil, recoverableErrTimeouts(createErr)
}
878835
func NewConfigurationManager(dispatcher core.Dispatcher) core.ConfigMgr {
	configMgr := new(ConfigurationManager)
	configMgr.dispatcher = dispatcher
	configMgr.Sources = make(map[string]core.ConfigSource)
	configMgr.ConfigurationMap = make(map[string]string)
	//configMgr.logger = cLogger

	return configMgr
}
805119
func RunInResourceContainer(containerName string) error {
	manager := fs.Manager{
		Cgroups: &configs.Cgroup{
			Name:            containerName,
			AllowAllDevices: true,
		},
	}

	return manager.Apply(os.Getpid())
}
83341
func (ctx *containerProfileContext) ProcessOneContainer(
	_ environs.Environ, _ context.ProviderCallContext, idx int, _, guest Machine,
) error {
	units, err := guest.Units()
	if err != nil {
		ctx.result.Results[idx].Error = common.ServerError(err)
		return errors.Trace(err)
	}
	var resPro []*params.ContainerLXDProfile
	for _, unit := range units {
		app, err := unit.Application()
		if err != nil {
			ctx.SetError(idx, err)
			return errors.Trace(err)
		}
		ch, _, err := app.Charm()
		if err != nil {
			ctx.SetError(idx, err)
			return errors.Trace(err)
		}
		profile := ch.LXDProfile()
		if profile == nil || (profile != nil && profile.Empty()) {
			logger.Tracef("no profile to return for %q", unit.Name())
			continue
		}
		resPro = append(resPro, &params.ContainerLXDProfile{
			Profile: params.CharmLXDProfile{
				Config:      profile.Config,
				Description: profile.Description,
				Devices:     profile.Devices,
			},
			Name: lxdprofile.Name(ctx.modelName, app.Name(), ch.Revision()),
		})
	}

	ctx.result.Results[idx].LXDProfiles = resPro
	return nil
}
1120600
func toContainerConfig(c *yaml.Container) *dockerclient.ContainerConfig {
	config := &dockerclient.ContainerConfig{
		Image:      c.Image,
		Env:        toEnvironmentSlice(c.Environment),
		Cmd:        c.Command,
		Entrypoint: c.Entrypoint,
		WorkingDir: c.WorkingDir,
		HostConfig: dockerclient.HostConfig{
			Privileged:       c.Privileged,
			NetworkMode:      c.Network,
			Memory:           c.MemLimit,
			CpuShares:        c.CPUShares,
			CpuQuota:         c.CPUQuota,
			CpusetCpus:       c.CPUSet,
			MemorySwappiness: -1,
			OomKillDisable:   c.OomKillDisable,
		},
	}

	if len(config.Entrypoint) == 0 {
		config.Entrypoint = nil
	}
	if len(config.Cmd) == 0 {
		config.Cmd = nil
	}
	if len(c.ExtraHosts) > 0 {
		config.HostConfig.ExtraHosts = c.ExtraHosts
	}
	if len(c.DNS) != 0 {
		config.HostConfig.Dns = c.DNS
	}
	if len(c.DNSSearch) != 0 {
		config.HostConfig.DnsSearch = c.DNSSearch
	}
	if len(c.VolumesFrom) != 0 {
		config.HostConfig.VolumesFrom = c.VolumesFrom
	}

	config.Volumes = map[string]struct{}{}
	for _, path := range c.Volumes {
		if strings.Index(path, ":") == -1 {
			config.Volumes[path] = struct{}{}
			continue
		}
		parts := strings.Split(path, ":")
		config.Volumes[parts[1]] = struct{}{}
		config.HostConfig.Binds = append(config.HostConfig.Binds, path)
	}

	for _, path := range c.Devices {
		if strings.Index(path, ":") == -1 {
			continue
		}
		parts := strings.Split(path, ":")
		device := dockerclient.DeviceMapping{
			PathOnHost:        parts[0],
			PathInContainer:   parts[1],
			CgroupPermissions: "rwm",
		}
		config.HostConfig.Devices = append(config.HostConfig.Devices, device)
	}

	return config
}
598193
func DevConfig() *Config {
	conf := DefaultConfig()
	conf.BindAddr = "127.0.0.1"
	conf.LogLevel = "DEBUG"
	conf.Client.Enabled = true
	conf.Server.Enabled = true
	conf.DevMode = true
	conf.EnableDebug = true
	conf.DisableAnonymousSignature = true
	conf.Consul.AutoAdvertise = helper.BoolToPtr(true)
	if runtime.GOOS == "darwin" {
		conf.Client.NetworkInterface = "lo0"
	} else if runtime.GOOS == "linux" {
		conf.Client.NetworkInterface = "lo"
	}
	conf.Client.Options = map[string]string{
		"driver.raw_exec.enable": "true",
		"driver.docker.volumes":  "true",
	}
	conf.Client.GCInterval = 10 * time.Minute
	conf.Client.GCDiskUsageThreshold = 99
	conf.Client.GCInodeUsageThreshold = 99
	conf.Client.GCMaxAllocs = 50
	conf.Telemetry.PrometheusMetrics = true
	conf.Telemetry.PublishAllocationMetrics = true
	conf.Telemetry.PublishNodeMetrics = true

	return conf
}
679434
func (u *Unit) ContainerInfo() (CloudContainer, error) {
	doc, err := u.cloudContainer()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &cloudContainer{doc: *doc, unitName: u.Name()}, nil
}
212137
func (s *LUCIConfigProvider) Config(c context.Context) (*config.Config, error) {
	s.lock.Lock()
	defer s.lock.Unlock()

	// Load/cache the global config.
	if s.gcfg == nil {
		var err error
		s.gcfg, err = config.Load(c)
		if err != nil {
			return nil, err
		}
	}

	return s.gcfg, nil
}
737228
func (s *AgentVersion) SetConfigurationManager(v *StackConfigurationManager) *AgentVersion {
	s.ConfigurationManager = v
	return s
}
416811
func Convert_v1_DockerConfig_To_config_DockerConfig(in *v1.DockerConfig, out *config.DockerConfig, s conversion.Scope) error {
	return autoConvert_v1_DockerConfig_To_config_DockerConfig(in, out, s)
}
1237775
func (r *DeploymentConfigRef) DeploymentConfig() (*appsv1.DeploymentConfig, error) {
	if len(r.Name) == 0 {
		suggestions := NameSuggestions{}
		for i := range r.Images {
			suggestions = append(suggestions, r.Images[i])
		}
		name, ok := suggestions.SuggestName()
		if !ok {
			return nil, fmt.Errorf("unable to suggest a name for this DeploymentConfig")
		}
		r.Name = name
	}

	selector := map[string]string{
		"deploymentconfig": r.Name,
	}
	if len(r.Labels) > 0 {
		if err := util.MergeInto(selector, r.Labels, 0); err != nil {
			return nil, err
		}
	}

	triggers := []appsv1.DeploymentTriggerPolicy{
		// By default, always deploy on change
		{
			Type: appsv1.DeploymentTriggerOnConfigChange,
		},
	}

	template := corev1.PodSpec{}
	for i := range r.Images {
		c, containerTriggers, err := r.Images[i].DeployableContainer()
		if err != nil {
			return nil, err
		}
		triggers = append(triggers, containerTriggers...)
		template.Containers = append(template.Containers, *c)
	}

	// Create EmptyDir volumes for all container volume mounts
	for _, c := range template.Containers {
		for _, v := range c.VolumeMounts {
			template.Volumes = append(template.Volumes, corev1.Volume{
				Name: v.Name,
				VolumeSource: corev1.VolumeSource{
					EmptyDir: &corev1.EmptyDirVolumeSource{Medium: corev1.StorageMediumDefault},
				},
			})
		}
	}

	for i := range template.Containers {
		template.Containers[i].Env = append(template.Containers[i].Env, r.Env.List()...)
	}

	dc := &appsv1.DeploymentConfig{
		// this is ok because we know exactly how we want to be serialized
		TypeMeta: metav1.TypeMeta{APIVersion: appsv1.SchemeGroupVersion.String(), Kind: "DeploymentConfig"},
		ObjectMeta: metav1.ObjectMeta{
			Name: r.Name,
		},
		Spec: appsv1.DeploymentConfigSpec{
			Replicas: 1,
			Test:     r.AsTest,
			Selector: selector,
			Template: &corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: selector,
				},
				Spec: template,
			},
			Triggers: triggers,
		},
	}
	if r.PostHook != nil {
		//dc.Spec.Strategy.Type = "Rolling"
		if len(r.PostHook.Shell) > 0 {
			dc.Spec.Strategy.RecreateParams = &appsv1.RecreateDeploymentStrategyParams{
				Post: &appsv1.LifecycleHook{
					ExecNewPod: &appsv1.ExecNewPodHook{
						Command: []string{"/bin/sh", "-c", r.PostHook.Shell},
					},
				},
			}
		}
	}

	return dc, nil
}
1182107
func (c *ControllerAPI) HostedModelConfigs() (params.HostedModelConfigsResults, error) {
	result := params.HostedModelConfigsResults{}
	if err := c.checkHasAdmin(); err != nil {
		return result, errors.Trace(err)
	}

	modelUUIDs, err := c.state.AllModelUUIDs()
	if err != nil {
		return result, errors.Trace(err)
	}

	for _, modelUUID := range modelUUIDs {
		if modelUUID == c.state.ControllerModelUUID() {
			continue
		}
		st, err := c.statePool.Get(modelUUID)
		if err != nil {
			// This model could have been removed.
			if errors.IsNotFound(err) {
				continue
			}
			return result, errors.Trace(err)
		}
		defer st.Release()
		model, err := st.Model()
		if err != nil {
			return result, errors.Trace(err)
		}

		config := params.HostedModelConfig{
			Name:     model.Name(),
			OwnerTag: model.Owner().String(),
		}
		modelConf, err := model.Config()
		if err != nil {
			config.Error = common.ServerError(err)
		} else {
			config.Config = modelConf.AllAttrs()
		}
		cloudSpec := c.GetCloudSpec(model.ModelTag())
		if config.Error == nil {
			config.CloudSpec = cloudSpec.Result
			config.Error = cloudSpec.Error
		}
		result.Models = append(result.Models, config)
	}

	return result, nil
}