// prepareContainerAccessEnvironment retrieves the environment, host machine, and access
// for working with containers.
540296
func (p *ProvisionerAPI) prepareContainerAccessEnvironment() (environs.Environ, *state.Machine, common.AuthFunc, error) {
	env, err := environs.GetEnviron(p.configGetter, environs.New)
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}
	// TODO(jam): 2017-02-01 NetworkingEnvironFromModelConfig used to do this, but it doesn't feel good
	if env.Config().Type() == "dummy" {
		return nil, nil, nil, errors.NotSupportedf("dummy provider network config")
	}

	canAccess, err := p.getAuthFunc()
	if err != nil {
		return nil, nil, nil, errors.Annotate(err, "cannot authenticate request")
	}
	hostAuthTag := p.authorizer.GetAuthTag()
	if hostAuthTag == nil {
		return nil, nil, nil, errors.Errorf("authenticated entity tag is nil")
	}
	hostTag, err := names.ParseMachineTag(hostAuthTag.String())
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}
	host, err := p.getMachine(canAccess, hostTag)
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}
	return env, host, canAccess, nil
}
1316477
func (s *AttemptContainerDetail) SetContainerInstanceArn(v string) *AttemptContainerDetail {
	s.ContainerInstanceArn = &v
	return s
}
717723
func ConvertEnvironmentToDocker(env api.EnvironmentList) (result string) {
	for i, e := range env {
		if i == 0 {
			result += fmt.Sprintf("ENV %s=\"%s\"", e.Name, e.Value)
		} else {
			result += fmt.Sprintf(" \\\n    %s=\"%s\"", e.Name, e.Value)
		}
	}
	result += "\n"
	return
}
984772
func (s *UpdateComputeEnvironmentInput) SetComputeEnvironment(v string) *UpdateComputeEnvironmentInput {
	s.ComputeEnvironment = &v
	return s
}
248747
func (p *Provisioner) prepareEnvVars(elevated bool) (err error) {
	// Collate all required env vars into a plain string with required
	// formatting applied
	flattenedEnvVars := p.createFlattenedEnvVars(elevated)
	// Create a powershell script on the target build fs containing the
	// flattened env vars
	err = p.uploadEnvVars(flattenedEnvVars)
	if err != nil {
		return err
	}
	return
}
969191
func (s *Task) SetContainerInstanceArn(v string) *Task {
	s.ContainerInstanceArn = &v
	return s
}
946569
func (daemon *Daemon) createContainerOSSpecificSettings(container *container.Container, config *containertypes.Config, hostConfig *containertypes.HostConfig) error {

	if container.OS == runtime.GOOS {
		// Make sure the host config has the default daemon isolation if not specified by caller.
		if containertypes.Isolation.IsDefault(containertypes.Isolation(hostConfig.Isolation)) {
			hostConfig.Isolation = daemon.defaultIsolation
		}
	} else {
		// LCOW must be a Hyper-V container as you can't run a shared kernel when one
		// is a Windows kernel, the other is a Linux kernel.
		if containertypes.Isolation.IsProcess(containertypes.Isolation(hostConfig.Isolation)) {
			return fmt.Errorf("process isolation is invalid for Linux containers on Windows")
		}
		hostConfig.Isolation = "hyperv"
	}
	parser := volumemounts.NewParser(container.OS)
	for spec := range config.Volumes {

		mp, err := parser.ParseMountRaw(spec, hostConfig.VolumeDriver)
		if err != nil {
			return fmt.Errorf("Unrecognised volume spec: %v", err)
		}

		// If the mountpoint doesn't have a name, generate one.
		if len(mp.Name) == 0 {
			mp.Name = stringid.GenerateNonCryptoID()
		}

		// Skip volumes for which we already have something mounted on that
		// destination because of a --volume-from.
		if container.IsDestinationMounted(mp.Destination) {
			continue
		}

		volumeDriver := hostConfig.VolumeDriver

		// Create the volume in the volume driver. If it doesn't exist,
		// a new one will be created.
		v, err := daemon.volumes.Create(context.TODO(), mp.Name, volumeDriver, volumeopts.WithCreateReference(container.ID))
		if err != nil {
			return err
		}

		// FIXME Windows: This code block is present in the Linux version and
		// allows the contents to be copied to the container FS prior to it
		// being started. However, the function utilizes the FollowSymLinkInScope
		// path which does not cope with Windows volume-style file paths. There
		// is a separate effort to resolve this (@swernli), so this processing
		// is deferred for now. A case where this would be useful is when
		// a dockerfile includes a VOLUME statement, but something is created
		// in that directory during the dockerfile processing. What this means
		// on Windows for TP5 is that in that scenario, the contents will not
		// copied, but that's (somewhat) OK as HCS will bomb out soon after
		// at it doesn't support mapped directories which have contents in the
		// destination path anyway.
		//
		// Example for repro later:
		//   FROM windowsservercore
		//   RUN mkdir c:\myvol
		//   RUN copy c:\windows\system32\ntdll.dll c:\myvol
		//   VOLUME "c:\myvol"
		//
		// Then
		//   docker build -t vol .
		//   docker run -it --rm vol cmd  <-- This is where HCS will error out.
		//
		//	// never attempt to copy existing content in a container FS to a shared volume
		//	if v.DriverName() == volume.DefaultDriverName {
		//		if err := container.CopyImagePathContent(v, mp.Destination); err != nil {
		//			return err
		//		}
		//	}

		// Add it to container.MountPoints
		container.AddMountPointWithVolume(mp.Destination, &volumeWrapper{v: v, s: daemon.volumes}, mp.RW)
	}
	return nil
}
557905
func (p ManualProvider) PrepareConfig(args environs.PrepareConfigParams) (*config.Config, error) {
	if err := validateCloudSpec(args.Cloud); err != nil {
		return nil, errors.Trace(err)
	}
	envConfig, err := p.validate(args.Config, nil)
	if err != nil {
		return nil, err
	}
	return args.Config.Apply(envConfig.attrs)
}
816831
func (s *TransformJobDefinition) SetEnvironment(v map[string]*string) *TransformJobDefinition {
	s.Environment = v
	return s
}
135451
func (st *State) PrepareContainerInterfaceInfo(containerTag names.MachineTag) ([]network.InterfaceInfo, error) {
	return st.prepareOrGetContainerInterfaceInfo(containerTag, true)
}
923761
func toContainer(hostID int, idMap []IDMap) (int, error) {
	if idMap == nil {
		return hostID, nil
	}
	for _, m := range idMap {
		if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) {
			contID := m.ContainerID + (hostID - m.HostID)
			return contID, nil
		}
	}
	return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID)
}
1073506
func (env *environ) getContainerSpec(
	image lxd.SourcedImage, serverVersion string, args environs.StartInstanceParams,
) (lxd.ContainerSpec, error) {
	hostname, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		return lxd.ContainerSpec{}, errors.Trace(err)
	}
	cSpec := lxd.ContainerSpec{
		Name:     hostname,
		Profiles: append([]string{"default", env.profileName()}, args.CharmLXDProfiles...),
		Image:    image,
		Config:   make(map[string]string),
	}
	cSpec.ApplyConstraints(serverVersion, args.Constraints)

	cloudCfg, err := cloudinit.New(args.InstanceConfig.Series)
	if err != nil {
		return cSpec, errors.Trace(err)
	}

	// Check to see if there are any non-eth0 devices in the default profile.
	// If there are, we need cloud-init to configure them, and we need to
	// explicitly add them to the container spec.
	nics, err := env.server().GetNICsFromProfile("default")
	if err != nil {
		return cSpec, errors.Trace(err)
	}
	if !(len(nics) == 1 && nics["eth0"] != nil) {
		logger.Debugf("generating custom cloud-init networking")

		cSpec.Config[lxd.NetworkConfigKey] = cloudinit.CloudInitNetworkConfigDisabled

		info, err := lxd.InterfaceInfoFromDevices(nics)
		if err != nil {
			return cSpec, errors.Trace(err)
		}
		if err := cloudCfg.AddNetworkConfig(info); err != nil {
			return cSpec, errors.Trace(err)
		}

		cSpec.Devices = nics
	}

	userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudCfg, lxdRenderer{})
	if err != nil {
		return cSpec, errors.Annotate(err, "composing user data")
	}
	logger.Debugf("LXD user data; %d bytes", len(userData))

	// TODO(ericsnow) Looks like LXD does not handle gzipped userdata
	// correctly.  It likely has to do with the HTTP transport, much
	// as we have to b64encode the userdata for GCE.  Until that is
	// resolved we simply pass the plain text.
	//cfg[lxd.UserDataKey] = utils.Gzip(userData)
	cSpec.Config[lxd.UserDataKey] = string(userData)

	for k, v := range args.InstanceConfig.Tags {
		if !strings.HasPrefix(k, tags.JujuTagPrefix) {
			// Since some metadata is interpreted by LXD, we cannot allow
			// arbitrary tags to be passed in by the user.
			// We currently only pass through Juju-defined tags.
			logger.Debugf("ignoring non-juju tag: %s=%s", k, v)
			continue
		}
		cSpec.Config[lxd.UserNamespacePrefix+k] = v
	}

	return cSpec, nil
}
1277991
func (s *CreateAppInput) SetEnvironment(v []*EnvironmentVariable) *CreateAppInput {
	s.Environment = v
	return s
}
690918
func (s *DeregisterContainerInstanceOutput) SetContainerInstance(v *ContainerInstance) *DeregisterContainerInstanceOutput {
	s.ContainerInstance = v
	return s
}
248077
func (s *RegisterContainerInstanceInput) SetContainerInstanceArn(v string) *RegisterContainerInstanceInput {
	s.ContainerInstanceArn = &v
	return s
}
359602
func PrepareEnvironmentAndRunCommand(userConfig config.UserConfigModel, cmdName string, cmdArgs ...string) (int, error) {
	projectConfig, err := config.LoadProjectConfigFromFile()
	if err != nil {
		log.Info("Run " + colorstring.Green("gows init") + " to initialize a workspace & gows config for this project")
		return 0, fmt.Errorf("Failed to read Project Config: %s", err)
	}

	gowsConfig, err := config.LoadGOWSConfigFromFile()
	if err != nil {
		return 0, fmt.Errorf("Failed to read gows configs: %s", err)
	}
	currWorkDir, err := os.Getwd()
	if err != nil {
		return 0, fmt.Errorf("[PrepareEnvironmentAndRunCommand] Failed to get current working directory: %s", err)
	}

	wsConfig, isFound := gowsConfig.WorkspaceForProjectLocation(currWorkDir)
	if !isFound {
		log.Debugln("No initialized workspace dir found for this project, initializing one ...")
		if err := initWorkspaceForProjectPath(currWorkDir, false); err != nil {
			return 0, fmt.Errorf("[PrepareEnvironmentAndRunCommand] Failed to initialize Workspace for Project: %s", err)
		}
		log.Debugln("[DONE] workspace dir initialized - continue running ...")

		// reload config
		gowsConfig, err := config.LoadGOWSConfigFromFile()
		if err != nil {
			return 0, fmt.Errorf("Failed to read gows configs: %s", err)
		}
		wsConfig, isFound = gowsConfig.WorkspaceForProjectLocation(currWorkDir)
	}
	if !isFound {
		log.Info("Run " + colorstring.Green("gows init") + " to initialize a workspace & gows config for this project")
		return 0, fmt.Errorf("No Workspace configuration found for the current project / working directory: %s", currWorkDir)
	}

	origGOPATH := os.Getenv("GOPATH")
	if origGOPATH == "" {
		// since Go 1.8 GOPATH is no longer required, it defaults to $HOME/go if not set:
		// https://golang.org/doc/go1.8#gopath
		p, err := pathutil.AbsPath("$HOME/go")
		if err != nil {
			return 0, errors.Wrap(err, "No GOPATH environment variable specified, and failed to get Abs path of default $HOME/go dir")
		}
		origGOPATH = p
	}

	if err := pathutil.EnsureDirExist(origGOPATH); err != nil {
		return 0, errors.Wrapf(err, "Failed to ensure that GOPATH exists at path: %s", origGOPATH)
	}

	if wsConfig.WorkspaceRootPath == "" {
		return 0, fmt.Errorf("No gows Workspace root path found for the current project / working directory: %s", currWorkDir)
	}
	if projectConfig.PackageName == "" {
		return 0, errors.New("No Package Name specified - make sure you initialized the workspace (with: gows init)")
	}

	if err := pathutil.EnsureDirExist(wsConfig.WorkspaceRootPath); err != nil {
		return 0, fmt.Errorf("Failed to create workspace root directory (path: %s), error: %s", wsConfig.WorkspaceRootPath, err)
	}

	if err := gows.CreateGopathBinSymlink(origGOPATH, wsConfig.WorkspaceRootPath); err != nil {
		return 0, fmt.Errorf("Failed to create GOPATH/bin symlink, error: %s", err)
	}

	fullPackageWorkspacePath := filepath.Join(wsConfig.WorkspaceRootPath, "src", projectConfig.PackageName)

	userConfigSyncMode := userConfig.SyncMode
	if userConfigSyncMode == "" {
		userConfigSyncMode = config.DefaultSyncMode
	}
	log.Debug("[PrepareEnvironmentAndRunCommand] specified Sync Mode : ", userConfigSyncMode)

	// --- prepare ---
	{
		fullPackageWorkspacePathFileInfo, fullPackageWorkspaceIsExists, err := pathutil.PathCheckAndInfos(fullPackageWorkspacePath)
		if err != nil {
			return 0, fmt.Errorf("Failed to check Symlink status (at: %s), error: %s", fullPackageWorkspacePath, err)
		}

		switch userConfigSyncMode {
		case config.SyncModeSymlink:
			// create symlink for Project->Workspace
			if fullPackageWorkspaceIsExists && fullPackageWorkspacePathFileInfo.Mode()&os.ModeSymlink == 0 {
				// directory (non symlink) exists - remove it
				log.Warningf("Directory exists (at: %s)", fullPackageWorkspacePath)
				log.Warning("Removing it ...")
				if err := os.RemoveAll(fullPackageWorkspacePath); err != nil {
					return 0, fmt.Errorf("Failed to remove Directory (at: %s), error: %s", fullPackageWorkspacePath, err)
				}
			}

			log.Debugf("=> Creating Symlink: (%s) -> (%s)", currWorkDir, fullPackageWorkspacePath)
			if err := gows.CreateOrUpdateSymlink(currWorkDir, fullPackageWorkspacePath); err != nil {
				return 0, fmt.Errorf("Failed to create Project->Workspace symlink, error: %s", err)
			}
			log.Debugf(" [DONE] Symlink is in place")
		case config.SyncModeCopy:
			// Sync project into workspace
			if fullPackageWorkspaceIsExists && fullPackageWorkspacePathFileInfo.Mode()&os.ModeSymlink != 0 {
				// symlink exists - remove it
				log.Warningf("Symlink exists (at: %s)", fullPackageWorkspacePath)
				log.Warning("Removing it ...")
				if err := os.Remove(fullPackageWorkspacePath); err != nil {
					return 0, fmt.Errorf("Failed to remove Symlink (at: %s), error: %s", fullPackageWorkspacePath, err)
				}
			}

			log.Debugf("=> Sync project content into workspace: (%s) -> (%s)", currWorkDir, fullPackageWorkspacePath)
			if err := syncDirWithDir(currWorkDir, fullPackageWorkspacePath); err != nil {
				return 0, fmt.Errorf("Failed to sync the project path / workdir into the Workspace, error: %s", err)
			}
			if err := writeGowsCopySyncActiveFileToPath(gowsCopyModeActiveFilePath, fullPackageWorkspacePath, currWorkDir); err != nil {
				log.Warningf(" [!] Failed to write gows-copy-mode-active file to path: %s", gowsCopyModeActiveFilePath)
			}
			log.Debugf(" [DONE] Sync project content into workspace")
		default:
			return 0, fmt.Errorf("Unsupported Sync Mode: %s", userConfigSyncMode)
		}
	}

	// Run the command, in the prepared Workspace
	exitCode, cmdErr := runCommand(fullPackageWorkspacePath, wsConfig, cmdName, cmdArgs...)

	// cleanup / finishing
	{
		switch userConfigSyncMode {
		case config.SyncModeSymlink:
			// nothing to do
		case config.SyncModeCopy:
			// Sync back from workspace into project
			log.Debugf("=> Sync workspace content into project: (%s) -> (%s)", fullPackageWorkspacePath, currWorkDir)
			if err := syncDirWithDir(fullPackageWorkspacePath, currWorkDir); err != nil {
				// we should return the command's exit code and error (if any)
				// maybe if the exitCode==0 and cmdErr==nil only then we could return an error here ...
				// for now we'll just print an error log, but it won't change the "output" of this function
				log.Errorf("Failed to sync back the project content from the Workspace, error: %s", err)
			} else {
				log.Debugf(" [DONE] Sync back project content from workspace")
			}
		default:
			return 0, fmt.Errorf("Unsupported Sync Mode: %s", userConfigSyncMode)
		}
	}

	return exitCode, cmdErr
}
1270899
func (m *MockAPICalls) PrepareContainerInterfaceInfo(arg0 names_v2.MachineTag) ([]network.InterfaceInfo, error) {
	ret := m.ctrl.Call(m, "PrepareContainerInterfaceInfo", arg0)
	ret0, _ := ret[0].([]network.InterfaceInfo)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}