// Prepare applies changes to the host machine that are necessary to create
// the requested container.
19066
func (hp *HostPreparer) Prepare(containerTag names.MachineTag) error {
	devicesToBridge, reconfigureDelay, err := hp.api.HostChangesForContainer(containerTag)
	if err != nil {
		return errors.Annotate(err, "unable to setup network")
	}

	if len(devicesToBridge) == 0 {
		hp.logger.Debugf("container %q requires no additional bridges", containerTag)
		return nil
	}

	bridger, err := hp.createBridger()
	if err != nil {
		return errors.Trace(err)
	}

	hp.logger.Debugf("bridging %+v devices on host %q for container %q with delay=%v",
		devicesToBridge, hp.machineTag.String(), containerTag.String(), reconfigureDelay)
	releaser, err := hp.acquireLockFunc("bridging devices", hp.abortChan)
	if err != nil {
		return errors.Annotatef(err, "failed to acquire machine lock for bridging")
	}
	defer releaser()
	// TODO(jam): 2017-02-15 bridger.Bridge should probably also take AbortChan
	// if it is going to have reconfigureDelay
	err = bridger.Bridge(devicesToBridge, reconfigureDelay)
	if err != nil {
		return errors.Annotate(err, "failed to bridge devices")
	}

	// We just changed the hosts' network setup so discover new
	// interfaces/devices and propagate to state.
	observedConfig, err := hp.observeNetworkFunc()
	if err != nil {
		return errors.Annotate(err, "cannot discover observed network config")
	}

	if len(observedConfig) > 0 {
		hp.logger.Debugf("updating observed network config for %q to %#v", hp.machineTag.String(), observedConfig)
		err := hp.api.SetHostMachineNetworkConfig(hp.machineTag, observedConfig)
		if err != nil {
			return errors.Trace(err)
		}
	}

	return nil
}
1330521
func (m *MySQLBackend) prepare(name, query string) error {
	stmt, err := m.client.Prepare(query)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err)
	}
	m.statements[name] = stmt
	return nil
}
921101
func (change relationSettingsCleanupChange) Prepare(db Database) ([]txn.Op, error) {
	settings, closer := db.GetCollection(settingsC)
	defer closer()
	sel := bson.D{{"_id", bson.D{{"$regex", "^" + change.Prefix}}}}
	var docs []struct {
		DocID string `bson:"_id"`
	}
	err := settings.Find(sel).Select(bson.D{{"_id", 1}}).All(&docs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(docs) == 0 {
		return nil, ErrChangeComplete
	}

	ops := make([]txn.Op, len(docs))
	for i, doc := range docs {
		ops[i] = txn.Op{
			C:      settingsC,
			Id:     doc.DocID,
			Remove: true,
		}
	}
	return ops, nil

}
501095
func Prepare(schema Schema) Schema {
	job := prepareJob{
		seen: make(map[Schema]Schema),
	}
	return job.prepare(schema)
}
561644
func (p *Controller) Prepare(ctx context.Context) (err error) {
	p.logger.Debug("Prepare")

	remote, err := reference.ParseNormalizedNamed(p.spec.Remote)
	if err != nil {
		return errors.Wrapf(err, "error parsing remote reference %q", p.spec.Remote)
	}

	if p.spec.Name == "" {
		p.spec.Name = remote.String()
	}

	var authConfig enginetypes.AuthConfig
	privs := convertPrivileges(p.spec.Privileges)

	pl, err := p.backend.Get(p.spec.Name)

	defer func() {
		if pl != nil && err == nil {
			pl.Acquire()
		}
	}()

	if err == nil && pl != nil {
		if pl.SwarmServiceID != p.serviceID {
			return errors.Errorf("plugin already exists: %s", p.spec.Name)
		}
		if pl.IsEnabled() {
			if err := p.backend.Disable(pl.GetID(), &enginetypes.PluginDisableConfig{ForceDisable: true}); err != nil {
				p.logger.WithError(err).Debug("could not disable plugin before running upgrade")
			}
		}
		p.pluginID = pl.GetID()
		return p.backend.Upgrade(ctx, remote, p.spec.Name, nil, &authConfig, privs, ioutil.Discard)
	}

	if err := p.backend.Pull(ctx, remote, p.spec.Name, nil, &authConfig, privs, ioutil.Discard, plugin.WithSwarmService(p.serviceID)); err != nil {
		return err
	}
	pl, err = p.backend.Get(p.spec.Name)
	if err != nil {
		return err
	}
	p.pluginID = pl.GetID()

	return nil
}
586198
func (rh *runHook) Prepare(state State) (*State, error) {
	name, err := rh.callbacks.PrepareHook(rh.info)
	if err != nil {
		return nil, err
	}
	rnr, err := rh.runnerFactory.NewHookRunner(rh.info)
	if err != nil {
		return nil, err
	}

	if hooks.Kind(name) == hooks.LeaderElected {
		// Check if leadership has changed between queueing of the hook and
		// Actual execution. Skip execution if we are no longer the leader.
		isLeader := false
		isLeader, err = rnr.Context().IsLeader()
		if err == nil && !isLeader {
			logger.Infof("unit is no longer the leader; skipping %q execution", name)
			return nil, ErrSkipExecute
		}
		if err != nil {
			return nil, err
		}
	}

	err = rnr.Context().Prepare()
	if err != nil {
		return nil, errors.Trace(err)
	}
	rh.name = name
	rh.runner = rnr

	return stateChange{
		Kind: RunHook,
		Step: Pending,
		Hook: &rh.info,
	}.apply(state), nil
}
1050563
func (s Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	ism := obj.(*imageapi.ImageStreamMapping)
	if len(ism.Image.DockerImageReference) == 0 {
		internalRegistry, ok := s.registryHostRetriever.InternalRegistryHostname()
		if ok {
			ism.Image.DockerImageReference = imageapi.DockerImageReference{
				Registry:  internalRegistry,
				Namespace: ism.Namespace,
				Name:      ism.Name,
				ID:        ism.Image.Name,
			}.Exact()
		}
	}

	// signatures can be added using "images" or "imagesignatures" resources
	ism.Image.Signatures = nil
}
203109
func Prepare(edits []NotificationMessage) (string, error) {
	buf, err := json.Marshal(edits)
	if err != nil {
		return "", err
	}
	return string(buf), nil
}
786862
func (c *CrateDriver) Prepare(query string) (driver.Stmt, error) {
	stmt := &CrateStmt{
		stmt:   query,
		driver: c,
	}

	return stmt, nil
}
349720
func (builder *Dockerfile) Prepare(config *api.Config) error {
	var err error

	if len(config.WorkingDir) == 0 {
		if config.WorkingDir, err = builder.fs.CreateWorkingDirectory(); err != nil {
			builder.setFailureReason(utilstatus.ReasonFSOperationFailed, utilstatus.ReasonMessageFSOperationFailed)
			return err
		}
	}

	builder.result.WorkingDir = config.WorkingDir

	// Setup working directories
	for _, v := range workingDirs {
		if err = builder.fs.MkdirAllWithPermissions(filepath.Join(config.WorkingDir, v), 0755); err != nil {
			builder.setFailureReason(utilstatus.ReasonFSOperationFailed, utilstatus.ReasonMessageFSOperationFailed)
			return err
		}
	}

	// Default - install scripts specified by image metadata.
	// Typically this will point to an image:// URL, and no scripts are downloaded.
	// However, this is not guaranteed.
	builder.installScripts(config.ImageScriptsURL, config)

	// Fetch sources, since their .s2i/bin might contain s2i scripts which override defaults.
	if config.Source != nil {
		downloader, err := scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy)
		if err != nil {
			builder.setFailureReason(utilstatus.ReasonFetchSourceFailed, utilstatus.ReasonMessageFetchSourceFailed)
			return err
		}
		if builder.sourceInfo, err = downloader.Download(config); err != nil {
			builder.setFailureReason(utilstatus.ReasonFetchSourceFailed, utilstatus.ReasonMessageFetchSourceFailed)
			switch err.(type) {
			case file.RecursiveCopyError:
				return fmt.Errorf("input source directory contains the target directory for the build, check that your Dockerfile output path does not reside within your input source path: %v", err)
			}
			return err
		}
		if config.SourceInfo != nil {
			builder.sourceInfo = config.SourceInfo
		}
	}

	// Install scripts provided by user, overriding all others.
	// This _could_ be an image:// URL, which would override any scripts above.
	urlScripts := builder.installScripts(config.ScriptsURL, config)
	// If a ScriptsURL was specified, but no scripts were downloaded from it, throw an error
	if len(config.ScriptsURL) > 0 {
		failedCount := 0
		for _, result := range urlScripts {
			if util.Includes(result.FailedSources, scripts.ScriptURLHandler) {
				failedCount++
			}
		}
		if failedCount == len(urlScripts) {
			builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason(
				utilstatus.ReasonScriptsFetchFailed,
				utilstatus.ReasonMessageScriptsFetchFailed,
			)
			return fmt.Errorf("could not download any scripts from URL %v", config.ScriptsURL)
		}
	}

	// Stage any injection(secrets) content into the working dir so the dockerfile can reference it.
	for i, injection := range config.Injections {
		// strip the C: from windows paths because it's not valid in the middle of a path
		// like upload/injections/C:/tempdir/injection1
		trimmedSrc := strings.TrimPrefix(injection.Source, filepath.VolumeName(injection.Source))
		dst := filepath.Join(config.WorkingDir, constants.Injections, trimmedSrc)
		glog.V(4).Infof("Copying injection content from %s to %s", injection.Source, dst)
		if err := builder.fs.CopyContents(injection.Source, dst); err != nil {
			builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed)
			return err
		}
		config.Injections[i].Source = trimmedSrc
	}

	// see if there is a .s2iignore file, and if so, read in the patterns and then
	// search and delete on them.
	err = builder.ignorer.Ignore(config)
	if err != nil {
		builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed)
		return err
	}
	return nil
}
242744
func (c *OutputConfig) Prepare(ctx *interpolate.Context, pc *common.PackerConfig) []error {
	if c.OutputDir == "" {
		c.OutputDir = fmt.Sprintf("output-%s", pc.PackerBuildName)
	}

	var errs []error

	if path.IsAbs(c.OutputDir) {
		c.OutputDir = path.Clean(c.OutputDir)
	} else {
		wd, err := os.Getwd()
		if err != nil {
			errs = append(errs, err)
		}
		c.OutputDir = path.Clean(path.Join(wd, c.OutputDir))
	}

	if !pc.PackerForce {
		if _, err := os.Stat(c.OutputDir); err == nil {
			errs = append(errs, fmt.Errorf(
				"Output directory '%s' already exists. It must not exist.", c.OutputDir))
		}
	}

	return errs
}
719175
func PrepareContainer(ctx context.Context, client *docker.Client, buildOpts *provision.BuildOptions, containerOpts *provision.ContainerOptions) (container *docker.Container, err error) {
	img, err := provision.FnFindImage(client, buildOpts.GetImageName())
	if err != nil && err != provision.ErrImageNotFound {
		return
	}

	var image string
	if img.ID == "" {
		image, _, err = provision.FnImageBuild(client, buildOpts)
		if err != nil {
			return
		}
	} else {
		image = buildOpts.GetImageName()
	}

	if containerOpts == nil {
		containerOpts = &provision.ContainerOptions{}
	}
	containerOpts.Image = image
	container, err = provision.FnContainer(client, *containerOpts)
	return
}
1116349
func (w *writer) prepare() error {
	if w.prepared {
		return nil
	}
	req, err := http.NewRequest("POST", w.o.url("?uploads"), nil)
	if err != nil {
		return err
	}

	// detect mime type
	ext := filepath.Ext(w.o.key)
	contentType := "application/octet-stream"
	if v, ok := mimeTypes[ext]; ok {
		contentType = v
	}
	req.Header.Set(`Content-Type`, contentType)

	// sign and send
	w.o.s3.signRequest(req)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if c := resp.StatusCode; c != 200 {
		return newS3Error(resp, "could not create multipart upload: %d", c)
	}

	var result struct {
		UploadId string
	}
	err = xml.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return err
	}

	w.uploadId = result.UploadId
	w.prepared = true

	return nil
}
1229180
func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
	if parent == nil {
		return consensus.ErrUnknownAncestor
	}
	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
	return nil
}
606911
func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) {
	if r == nil {
		return nil, NewError("autorest", "Prepare", "Invoked without an http.Request")
	}
	return CreatePreparer(decorators...).Prepare(r)
}
686670
func (change payloadTrackChange) Prepare(db Database) ([]txn.Op, error) {

	unit := change.Doc.UnitID
	units, closer := db.GetCollection(unitsC)
	defer closer()
	unitOp, err := nsLife.notDeadOp(units, unit)
	if errors.Cause(err) == errDeadOrGone {
		return nil, errors.Errorf("unit %q no longer available", unit)
	} else if err != nil {
		return nil, errors.Trace(err)
	}

	payloads, closer := db.GetCollection(payloadsC)
	defer closer()
	payloadOp, err := nsPayloads.trackOp(payloads, change.Doc)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return []txn.Op{unitOp, payloadOp}, nil
}
1367711
func (c *ShutdownConfig) Prepare(ctx *interpolate.Context) []error {
	if c.RawShutdownTimeout == "" {
		c.RawShutdownTimeout = "5m"
	}

	var errs []error
	var err error
	c.ShutdownTimeout, err = time.ParseDuration(c.RawShutdownTimeout)
	if err != nil {
		errs = append(errs, fmt.Errorf("Failed parsing shutdown_timeout: %s", err))
	}

	return errs
}