// Function to load the currently deployed container for the environment
// specified in the prefix. If history is empty the ErrorLaunchConfigNotFound
// error type will be returned.
493246
func LoadCurrentLaunchConfig(s3c *s3.Client, bucket, prefix string) (*LaunchConfig, error) {
	lc := new(LaunchConfig)
	return lc, lc.load(s3c, bucket, prefix, "current.json")
}
228081
func (opts *ClientOptions) LoadFromEnv(getEnv func(string) string) error {
	if opts.CacheDir == "" {
		if v := getEnv(EnvCacheDir); v != "" {
			if !filepath.IsAbs(v) {
				return fmt.Errorf("bad %s: not an absolute path - %s", EnvCacheDir, v)
			}
			opts.CacheDir = v
		}
	}
	if opts.UserAgent == "" {
		if v := getEnv(EnvHTTPUserAgentPrefix); v != "" {
			opts.UserAgent = fmt.Sprintf("%s/%s", v, UserAgent)
		}
	}
	return nil
}
31689
func ContainerExecStart(id string) error {
	return mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		opts := types.ExecStartCheck{
			Detach: false,
			Tty:    true,
		}
		return cli.ContainerExecStart(ctx, id, opts)
	})
}
1219020
func Load(file string) (config Project, err error) {
	f, err := os.Open(file) // #nosec
	if err != nil {
		return
	}
	log.WithField("file", file).Info("loading config file")
	return LoadReader(f)
}
116403
func (e *Error) Load() error {
	v := e.v.Load()
	if v == nil {
		return nil
	}

	eh := v.(errorHolder)
	return eh.err
}
507831
func LoadMap(envMap map[string]string, overload bool) {
	currentEnv := make(map[string]bool)
	for _, rawEnvLine := range os.Environ() {
		currentEnv[strings.Split(rawEnvLine, "=")[0]] = true
	}

	for key, value := range envMap {
		if !currentEnv[key] || overload {
			os.Setenv(key, value)
		}
	}
}
679125
func LoadConfig(path string) (*DefaultConfig, error) {
	if path == "" {
		path = DefaultConfigPath
	}
	if v := os.Getenv(ConfigPathEnv); v != "" {
		path = v
	}

	// NOTE: requires HOME env var to be set
	path, err := homedir.Expand(path)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("error expanding config path %q: {{err}}", path), err)
	}

	contents, err := ioutil.ReadFile(path)
	if err != nil && !os.IsNotExist(err) {
		return nil, err
	}

	conf, err := ParseConfig(string(contents))
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("error parsing config file at %q: {{err}}; ensure that the file is valid; Ansible Vault is known to conflict with it.", path), err)
	}

	return conf, nil
}
1141409
func (client *Client) GetApplicationEnvironment(appGUID string) (Environment, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		URIParams:   internal.Params{"app_guid": appGUID},
		RequestName: internal.GetApplicationEnvRequest,
	})
	if err != nil {
		return Environment{}, nil, err
	}

	var responseEnvVars Environment
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &responseEnvVars,
	}
	err = client.connection.Make(request, &response)
	return responseEnvVars, response.Warnings, err
}
693811
func GetConfigRoot(env cmds.Environment) (string, error) {
	ctx, ok := env.(*commands.Context)
	if !ok {
		return "", fmt.Errorf("expected env to be of type %T, got %T", ctx, env)
	}

	return ctx.ConfigRoot, nil
}
496688
func (s *HandlebarsEngine) loadAssets() error {
	// register the global helpers
	if len(s.templateCache) == 0 && s.helpers != nil {
		raymond.RegisterHelpers(s.helpers)
	}

	virtualDirectory, virtualExtension := s.directory, s.extension
	assetFn, namesFn := s.assetFn, s.namesFn

	if len(virtualDirectory) > 0 {
		if virtualDirectory[0] == '.' { // first check for .wrong
			virtualDirectory = virtualDirectory[1:]
		}
		if virtualDirectory[0] == '/' || virtualDirectory[0] == os.PathSeparator { // second check for /something, (or ./something if we had dot on 0 it will be removed
			virtualDirectory = virtualDirectory[1:]
		}
	}
	var templateErr error

	names := namesFn()
	for _, path := range names {
		if !strings.HasPrefix(path, virtualDirectory) {
			continue
		}
		ext := filepath.Ext(path)
		if ext == virtualExtension {

			rel, err := filepath.Rel(virtualDirectory, path)
			if err != nil {
				templateErr = err
				return err
			}

			buf, err := assetFn(path)
			if err != nil {
				templateErr = err
				return err
			}
			contents := string(buf)
			name := filepath.ToSlash(rel)

			tmpl, err := raymond.Parse(contents)
			if err != nil {
				templateErr = err
				return err
			}
			s.templateCache[name] = tmpl

		}
	}
	return templateErr
}
878569
func LoadEnvironmentFile(filename string, stdin io.Reader) (Environment, error) {
	errorFilename := filename

	if filename == "-" && stdin != nil {
		//once https://github.com/joho/godotenv/pull/20 is merged we can get rid of using tempfile
		temp, err := ioutil.TempFile("", "origin-env-stdin")
		if err != nil {
			return nil, fmt.Errorf("Cannot create temporary file: %s", err)
		}

		filename = temp.Name()
		errorFilename = "stdin"
		defer os.Remove(filename)

		if _, err = io.Copy(temp, stdin); err != nil {
			return nil, fmt.Errorf("Cannot write to temporary file %q: %s", filename, err)
		}
		temp.Close()
	}

	// godotenv successfuly returns empty map when given path to a directory,
	// remove this once https://github.com/joho/godotenv/pull/22 is merged
	if info, err := os.Stat(filename); err == nil && info.IsDir() {
		return nil, fmt.Errorf("Cannot read variables from %q: is a directory", filename)
	} else if err != nil {
		return nil, fmt.Errorf("Cannot stat %q: %s", filename, err)
	}

	env, err := godotenv.Read(filename)
	if err != nil {
		return nil, fmt.Errorf("Cannot read variables from file %q: %s", errorFilename, err)
	}
	for k, v := range env {
		if err := validation.IsEnvVarName(k); len(err) != 0 {
			return nil, fmt.Errorf("invalid parameter assignment in %s=%s", k, v)
		}
	}
	return env, nil
}
99496
func (p *Project) Container(c *check.C, service string) types.ContainerJSON {
	container, err := p.project.Container(service)
	c.Assert(err, check.IsNil,
		check.Commentf("error while getting the container for service '%s'", service))
	return container
}
54221
func (m *Module) Init(c *service.Config) {
	c.Setup = func() error {
		m.configDefs = []reflect.Type{}
		switch {
		case m.ConfigPath != "":
		// do nothing
		case os.Getenv(ConfigEnv) != "":
			m.ConfigPath = os.Getenv(ConfigEnv)
		default:
			m.ConfigPath = "config.json"
		}

		err := m.LoadConfig(m.ConfigPath)
		// we only return an error if production, which
		// allows this to pass for env=test
		if err != nil {
			return errIfProduction(c, err)
		}
		return nil
	}
	c.SetupTest = func() {
		// this is a hack to have a safe default value
		// for m.Byte if we haven't loaded any config
		if len(m.Byte) == 0 {
			m.Byte = []byte(`{}`)
		}
		if m.TestConfigPath == "" {
			return
		}
		err := m.LoadConfig(m.TestConfigPath)
		if err != nil {
			panic(err)
		}
	}
}
1094762
func (d *DecisionTreeNode) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error {

	b, err := reader.GetBytesForKey(reader.Prefix(prefix, "tree"))
	if err != nil {
		return err
	}

	err = json.Unmarshal(b, d)
	if err != nil {
		return err
	}

	a, err := reader.GetAttributeForKey(reader.Prefix(prefix, "treeClassAttr"))
	if err != nil {
		return err
	}

	d.ClassAttr = a

	return nil
}
1237320
func (s *AmberEngine) loadAssets() error {
	virtualDirectory, virtualExtension := s.directory, s.extension
	assetFn, namesFn := s.assetFn, s.namesFn

	// prepare the global amber funcs
	funcs := template.FuncMap{}

	for k, v := range amber.FuncMap { // add the amber's default funcs
		funcs[k] = v
	}

	for k, v := range s.funcs {
		funcs[k] = v
	}

	if len(virtualDirectory) > 0 {
		if virtualDirectory[0] == '.' { // first check for .wrong
			virtualDirectory = virtualDirectory[1:]
		}
		if virtualDirectory[0] == '/' || virtualDirectory[0] == filepath.Separator { // second check for /something, (or ./something if we had dot on 0 it will be removed
			virtualDirectory = virtualDirectory[1:]
		}
	}
	amber.FuncMap = funcs //set the funcs

	names := namesFn()

	for _, path := range names {
		if !strings.HasPrefix(path, virtualDirectory) {
			continue
		}
		ext := filepath.Ext(path)
		if ext == virtualExtension {

			rel, err := filepath.Rel(virtualDirectory, path)
			if err != nil {
				return err
			}

			buf, err := assetFn(path)
			if err != nil {
				return err
			}

			name := filepath.ToSlash(rel)
			tmpl, err := amber.CompileData(buf, name, amber.DefaultOptions)

			if err != nil {
				return err
			}

			s.templateCache[name] = tmpl
		}
	}

	return nil
}
725885
func (cfg *Config) load(storage util.Storage) {
	if b, err := storage.Get("uuid"); err == nil && len(b) > 0 {
		cfg.id = string(b)
	}

	if b, err := storage.Get("version"); err == nil && len(b) > 0 {
		cfg.version = to.Int64(string(b))
	}

	if b, err := storage.Get("configHash"); err == nil && len(b) > 0 {
		cfg.configHash = b
	}
}
526606
func (daemon *Daemon) containerStart(container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
	start := time.Now()
	container.Lock()
	defer container.Unlock()

	if resetRestartManager && container.Running { // skip this check if already in restarting step and resetRestartManager==false
		return nil
	}

	if container.RemovalInProgress || container.Dead {
		return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
	}

	if checkpointDir != "" {
		// TODO(mlaventure): how would we support that?
		return errdefs.Forbidden(errors.New("custom checkpointdir is not supported"))
	}

	// if we encounter an error during start we need to ensure that any other
	// setup has been cleaned up properly
	defer func() {
		if err != nil {
			container.SetError(err)
			// if no one else has set it, make sure we don't leave it at zero
			if container.ExitCode() == 0 {
				container.SetExitCode(128)
			}
			if err := container.CheckpointTo(daemon.containersReplica); err != nil {
				logrus.Errorf("%s: failed saving state on start failure: %v", container.ID, err)
			}
			container.Reset(false)

			daemon.Cleanup(container)
			// if containers AutoRemove flag is set, remove it after clean up
			if container.HostConfig.AutoRemove {
				container.Unlock()
				if err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
					logrus.Errorf("can't remove container %s: %v", container.ID, err)
				}
				container.Lock()
			}
		}
	}()

	if err := daemon.conditionalMountOnStart(container); err != nil {
		return err
	}

	if err := daemon.initializeNetworking(container); err != nil {
		return err
	}

	spec, err := daemon.createSpec(container)
	if err != nil {
		return errdefs.System(err)
	}

	if resetRestartManager {
		container.ResetRestartManager(true)
		container.HasBeenManuallyStopped = false
	}

	if daemon.saveApparmorConfig(container); err != nil {
		return err
	}

	if checkpoint != "" {
		checkpointDir, err = getCheckpointDir(checkpointDir, checkpoint, container.Name, container.ID, container.CheckpointDir(), false)
		if err != nil {
			return err
		}
	}

	createOptions, err := daemon.getLibcontainerdCreateOptions(container)
	if err != nil {
		return err
	}

	ctx := context.TODO()

	err = daemon.containerd.Create(ctx, container.ID, spec, createOptions)
	if err != nil {
		if errdefs.IsConflict(err) {
			logrus.WithError(err).WithField("container", container.ID).Error("Container not cleaned up from containerd from previous run")
			// best effort to clean up old container object
			daemon.containerd.DeleteTask(ctx, container.ID)
			if err := daemon.containerd.Delete(ctx, container.ID); err != nil && !errdefs.IsNotFound(err) {
				logrus.WithError(err).WithField("container", container.ID).Error("Error cleaning up stale containerd container object")
			}
			err = daemon.containerd.Create(ctx, container.ID, spec, createOptions)
		}
		if err != nil {
			return translateContainerdStartErr(container.Path, container.SetExitCode, err)
		}
	}

	// TODO(mlaventure): we need to specify checkpoint options here
	pid, err := daemon.containerd.Start(context.Background(), container.ID, checkpointDir,
		container.StreamConfig.Stdin() != nil || container.Config.Tty,
		container.InitializeStdio)
	if err != nil {
		if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
			logrus.WithError(err).WithField("container", container.ID).
				Error("failed to delete failed start container")
		}
		return translateContainerdStartErr(container.Path, container.SetExitCode, err)
	}

	container.SetRunning(pid, true)
	container.HasBeenStartedBefore = true
	daemon.setStateCounter(container)

	daemon.initHealthMonitor(container)

	if err := container.CheckpointTo(daemon.containersReplica); err != nil {
		logrus.WithError(err).WithField("container", container.ID).
			Errorf("failed to store container")
	}

	daemon.LogContainerEvent(container, "start")
	containerActions.WithValues("start").UpdateSince(start)

	return nil
}