// Prepare performs basic validation on a TargetImageConfig struct.
545726
func (c *TargetImageConfig) Prepare(ctx *interpolate.Context) []error {
	var errs []error

	if c.ImageName == "" {
		errs = append(errs, fmt.Errorf("An image_name must be specified"))
	}

	if c.ImageVersion == "" {
		errs = append(errs, fmt.Errorf("An image_version must be specified"))
	}

	if len(errs) > 0 {
		return errs
	}

	return nil
}
863451
func (m *qlbConn) Prepare(query string) (driver.Stmt, error) {
	return nil, expr.ErrNotImplemented
}
184260
func (c *cmd) prepare() (version string, err error) {
	// Ensure realistic duration and intervals exists
	if c.validateTiming {
		if c.duration < debugMinDuration {
			return "", fmt.Errorf("duration must be longer than %s", debugMinDuration)
		}

		if c.interval < debugMinInterval {
			return "", fmt.Errorf("interval must be longer than %s", debugMinDuration)
		}

		if c.duration < c.interval {
			return "", fmt.Errorf("duration (%s) must be longer than interval (%s)", c.duration, c.interval)
		}
	}

	// Retrieve and process agent information necessary to validate
	self, err := c.client.Agent().Self()
	if err != nil {
		return "", fmt.Errorf("error querying target agent: %s. verify connectivity and agent address", err)
	}

	version, ok := self["Config"]["Version"].(string)
	if !ok {
		return "", fmt.Errorf("agent response did not contain version key")
	}

	debugEnabled, ok := self["DebugConfig"]["EnableDebug"].(bool)
	if !ok {
		return version, fmt.Errorf("agent response did not contain debug key")
	}

	// If none are specified we will collect information from
	// all by default
	if len(c.capture) == 0 {
		c.capture = c.defaultTargets()
	}

	if !debugEnabled && c.configuredTarget("pprof") {
		cs := c.capture
		for i := 0; i < len(cs); i++ {
			if cs[i] == "pprof" {
				c.capture = append(cs[:i], cs[i+1:]...)
				i--
			}
		}
		c.UI.Warn("[WARN] Unable to capture pprof. Set enable_debug to true on target agent to enable profiling.")
	}

	for _, t := range c.capture {
		if !c.allowedTarget(t) {
			return version, fmt.Errorf("target not found: %s", t)
		}
	}

	if _, err := os.Stat(c.output); os.IsNotExist(err) {
		err := os.MkdirAll(c.output, 0755)
		if err != nil {
			return version, fmt.Errorf("could not create output directory: %s", err)
		}
	} else {
		return version, fmt.Errorf("output directory already exists: %s", c.output)
	}

	return version, nil
}
128186
func (s *BlockingSender) Prepare(ctx context.Context, plaintext chat1.MessagePlaintext,
	membersType chat1.ConversationMembersType, conv *chat1.Conversation, inopts *chat1.SenderPrepareOptions) (res types.SenderPrepareResult, err error) {
	if plaintext.ClientHeader.MessageType == chat1.MessageType_NONE {
		return res, fmt.Errorf("cannot send message without type")
	}
	// set default options unless some are given to us
	var opts chat1.SenderPrepareOptions
	if inopts != nil {
		opts = *inopts
	}

	msg, uid, err := s.addSenderToMessage(plaintext)
	if err != nil {
		return res, err
	}

	// Make sure our delete message gets everything it should
	var pendingAssetDeletes []chat1.Asset
	if conv != nil {
		convID := (*conv).GetConvID()
		msg.ClientHeader.Conv = conv.Metadata.IdTriple
		s.Debug(ctx, "Prepare: performing convID based checks")

		// Check for outboxID based edits
		if err = s.resolveOutboxIDEdit(ctx, uid, convID, &msg); err != nil {
			s.Debug(ctx, "Prepare: error resolving outboxID edit: %s", err)
			return res, err
		}

		// Add and check prev pointers
		msg, err = s.addPrevPointersAndCheckConvID(ctx, msg, *conv)
		if err != nil {
			s.Debug(ctx, "Prepare: error adding prev pointers: %s", err)
			return res, err
		}

		// First process the reactionMessage in case we convert it to a delete
		header, body, err := s.processReactionMessage(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error processing reactions: %s", err)
			return res, err
		}
		msg.ClientHeader = header
		msg.MessageBody = body

		// Handle reply to
		msg = s.handleReplyTo(ctx, msg, opts.ReplyTo)

		// Be careful not to shadow (msg, pendingAssetDeletes) with this assignment.
		msg, pendingAssetDeletes, err = s.getAllDeletedEdits(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error getting deleted edits: %s", err)
			return res, err
		}

		// If no ephemeral data set, then let's double check to make sure no exploding policy
		// or Gregor state should set it
		if msg.EphemeralMetadata() == nil && chat1.IsEphemeralNonSupersederType(msg.ClientHeader.MessageType) {
			s.Debug(ctx, "Prepare: attempting to set ephemeral policy from conversation")
			elf, err := utils.EphemeralLifetimeFromConv(ctx, s.G(), *conv)
			if err != nil {
				s.Debug(ctx, "Prepare: failed to get ephemeral lifetime from conv: %s", err)
				elf = nil
			}
			if elf != nil {
				s.Debug(ctx, "Prepare: setting ephemeral lifetime from conv: %v", *elf)
				msg.ClientHeader.EphemeralMetadata = &chat1.MsgEphemeralMetadata{
					Lifetime: *elf,
				}
			}
		}

		metadata, err := s.getSupersederEphemeralMetadata(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error getting superseder ephemeral metadata: %s", err)
			return res, err
		}
		msg.ClientHeader.EphemeralMetadata = metadata
	}

	// Make sure it is a proper length
	if err := msgchecker.CheckMessagePlaintext(msg); err != nil {
		return res, err
	}

	// Get topic name state if this is a METADATA message, so that we avoid any races to the
	// server
	var topicNameState *chat1.TopicNameState
	if !opts.SkipTopicNameState {
		if topicNameState, err = s.checkTopicNameAndGetState(ctx, msg, membersType); err != nil {
			s.Debug(ctx, "Prepare: error checking topic name state: %s", err)
			return res, err
		}
	}

	// encrypt the message
	skp, err := s.getSigningKeyPair(ctx)
	if err != nil {
		s.Debug(ctx, "Prepare: error getting signing key pair: %s", err)
		return res, err
	}

	// Function to check that the header and body types match.
	// Call this before accessing the body.
	// Do not call this for TLFNAME which has no body.
	checkHeaderBodyTypeMatch := func() error {
		bodyType, err := plaintext.MessageBody.MessageType()
		if err != nil {
			return err
		}
		if plaintext.ClientHeader.MessageType != bodyType {
			return fmt.Errorf("cannot send message with mismatched header/body types: %v != %v",
				plaintext.ClientHeader.MessageType, bodyType)
		}
		return nil
	}

	// find @ mentions
	var atMentions []gregor1.UID
	chanMention := chat1.ChannelMention_NONE
	if msg.ClientHeader.Conv.TopicType == chat1.TopicType_CHAT {
		switch plaintext.ClientHeader.MessageType {
		case chat1.MessageType_TEXT:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.GetTextAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Text(), &s.DebugLabeler)
		case chat1.MessageType_FLIP:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Flip().Text)
		case chat1.MessageType_EDIT:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Edit().Body)
		case chat1.MessageType_SYSTEM:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, chanMention = utils.SystemMessageMentions(ctx, plaintext.MessageBody.System(),
				s.G().GetUPAKLoader())
		}
	}

	// If we are sending a message, and we think the conversation is a KBFS conversation, then set a label
	// on the client header in case this conversation gets upgrade to impteam.
	msg.ClientHeader.KbfsCryptKeysUsed = new(bool)
	if membersType == chat1.ConversationMembersType_KBFS {
		s.Debug(ctx, "setting KBFS crypt keys used flag")
		*msg.ClientHeader.KbfsCryptKeysUsed = true
	} else {
		*msg.ClientHeader.KbfsCryptKeysUsed = false
	}

	encInfo, err := s.boxer.GetEncryptionInfo(ctx, &msg, membersType, skp)
	if err != nil {
		return res, err
	}
	boxed, err := s.boxer.BoxMessage(ctx, msg, membersType, skp, &encInfo)
	if err != nil {
		return res, err
	}
	return types.SenderPrepareResult{
		Boxed:               boxed,
		EncryptionInfo:      encInfo,
		PendingAssetDeletes: pendingAssetDeletes,
		AtMentions:          atMentions,
		ChannelMention:      chanMention,
		TopicNameState:      topicNameState,
	}, nil
}
84077
func (t *bruteForceMatchTree) prepare(doc uint32) {
	t.docID = doc
	t.firstDone = true
}
56968
func (p Profile) Prepare(s string) (string, error) {
	// Optimistically, assume output will be same length as input
	temp := make([]rune, 0, len(s))

	// Apply maps
	for _, r := range s {
		rs, ok := p.applyMaps(r)
		if ok {
			temp = append(temp, rs...)
		} else {
			temp = append(temp, r)
		}
	}

	// Normalize
	var out string
	if p.Normalize {
		out = norm.NFKC.String(string(temp))
	} else {
		out = string(temp)
	}

	// Check prohibited
	for _, r := range out {
		if p.runeIsProhibited(r) {
			return "", Error{Msg: errProhibited, Rune: r}
		}
	}

	// Check BiDi allowed
	if p.CheckBiDi {
		if err := passesBiDiRules(out); err != nil {
			return "", err
		}
	}

	return out, nil
}
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
}
681032
func (op *triageOp) prepare(c context.Context) error {
	op.started = clock.Now(c).UTC() // used to derive relative time in the debug log
	op.debugInfoLog(c, "Starting")

	op.finishedSet = recentlyFinishedSet(c, op.jobID)
	op.triggersSet = pendingTriggersSet(c, op.jobID)

	wg := sync.WaitGroup{}
	wg.Add(2)

	// Grab all pending triggers to decided what to do with them.
	var triggersErr error
	go func() {
		defer wg.Done()
		op.triggersList, op.readyTriggers, triggersErr = op.triggersSet.Triggers(c)
		if triggersErr != nil {
			op.debugErrLog(c, triggersErr, "Failed to grab pending triggers")
		} else {
			sortTriggers(op.readyTriggers)
		}
	}()

	// Grab a list of recently finished invocations to remove them from
	// ActiveInvocations list.
	var finishedErr error
	go func() {
		defer wg.Done()
		op.finishedList, finishedErr = op.finishedSet.List(c)
		if finishedErr != nil {
			op.debugErrLog(c, finishedErr, "Failed to grab recently finished invocations")
		}
	}()

	wg.Wait()
	if triggersErr != nil || finishedErr != nil {
		return errTriagePrepareFail // the original error is already logged
	}

	op.debugInfoLog(c, "Pending triggers set:  %d items, %d garbage", len(op.triggersList.Items), len(op.triggersList.Garbage))
	op.debugInfoLog(c, "Recently finished set: %d items, %d garbage", len(op.finishedList.Items), len(op.finishedList.Garbage))

	// Remove old tombstones to keep the set tidy. We fail hard here on errors to
	// make sure progress stops if garbage can't be cleaned up for some reason.
	// It is better to fail early rather than silently accumulate tons of garbage
	// until everything grinds to a halt.
	if err := dsset.CleanupGarbage(c, op.triggersList.Garbage, op.finishedList.Garbage); err != nil {
		op.debugErrLog(c, err, "Failed to cleanup dsset garbage")
		return err
	}

	// Log something mostly to capture the timestamp.
	op.debugInfoLog(c, "The preparation is finished")
	return nil
}
608229
func (c *Option) prepare() (opts *js.Object) {
	if len(c.coms) > 0 {
		c.Set("components", c.coms)
	}
	if len(c.props) > 0 {
		c.Set("props", c.props)
	}
	if len(c.mixins) > 0 {
		c.Set("mixins", c.mixins)
	}
	return c.Object
}
416286
func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) {
	return pf(r)
}
34431
func (al *acceptLeadership) Prepare(state State) (*State, error) {
	if err := al.checkState(state); err != nil {
		return nil, err
	}
	return nil, ErrSkipExecute
}
14893
func (s *Scratch) prepare(in []byte) (*Scratch, error) {
	if s == nil {
		s = &Scratch{}
	}
	if s.MaxSymbolValue == 0 {
		s.MaxSymbolValue = 255
	}
	if s.TableLog == 0 {
		s.TableLog = defaultTablelog
	}
	if s.TableLog > maxTableLog {
		return nil, fmt.Errorf("tableLog (%d) > maxTableLog (%d)", s.TableLog, maxTableLog)
	}
	if cap(s.Out) == 0 {
		s.Out = make([]byte, 0, len(in))
	}
	if s.clearCount && s.maxCount == 0 {
		for i := range s.count {
			s.count[i] = 0
		}
		s.clearCount = false
	}
	s.br.init(in)
	if s.DecompressLimit == 0 {
		// Max size 2GB.
		s.DecompressLimit = 2 << 30
	}

	return s, nil
}
203109
func Prepare(edits []NotificationMessage) (string, error) {
	buf, err := json.Marshal(edits)
	if err != nil {
		return "", err
	}
	return string(buf), nil
}
571028
func (c *ToolsConfig) Prepare(ctx *interpolate.Context) []error {
	if c.ParallelsToolsMode == "" {
		c.ParallelsToolsMode = ParallelsToolsModeUpload
	}

	if c.ParallelsToolsGuestPath == "" {
		c.ParallelsToolsGuestPath = "prl-tools-{{.Flavor}}.iso"
	}

	validMode := false
	validModes := []string{
		ParallelsToolsModeDisable,
		ParallelsToolsModeAttach,
		ParallelsToolsModeUpload,
	}

	for _, mode := range validModes {
		if c.ParallelsToolsMode == mode {
			validMode = true
			break
		}
	}

	var errs []error
	if !validMode {
		errs = append(errs,
			fmt.Errorf("parallels_tools_mode is invalid. Must be one of: %v",
				validModes))
	}

	if c.ParallelsToolsFlavor == "" {
		if c.ParallelsToolsMode != ParallelsToolsModeDisable {
			errs = append(errs, errors.New("parallels_tools_flavor must be specified"))
		}
	}

	return errs
}
1064081
func (s *Snapshotter) Prepare(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) {
	log.G(ctx).WithFields(logrus.Fields{"key": key, "parent": parent}).Debug("prepare")

	var (
		mounts []mount.Mount
		err    error
	)

	err = s.withTransaction(ctx, true, func(ctx context.Context) error {
		mounts, err = s.createSnapshot(ctx, snapshots.KindActive, key, parent, opts...)
		return err
	})

	return mounts, err
}
206553
func (e EnvironProvider) PrepareConfig(args environs.PrepareConfigParams) (*config.Config, error) {
	if err := validateCloudSpec(args.Cloud); err != nil {
		return nil, errors.Annotate(err, "validating cloud spec")
	}
	// TODO(gsamfira): Set default block storage backend
	return args.Config, nil
}
1139799
func (p *Pinger) prepare() error {
	change := mgo.Change{
		Update:    bson.D{{"$inc", bson.D{{"seq", int64(1)}}}},
		Upsert:    true,
		ReturnNew: true,
	}
	session := p.base.Database.Session.Copy()
	defer session.Close()
	base := p.base.With(session)
	seqs := seqsC(base)
	var seq struct{ Seq int64 }
	seqID := docIDStr(p.modelUUID, "beings")
	if _, err := seqs.FindId(seqID).Apply(change, &seq); err != nil {
		return errors.Trace(err)
	}
	p.beingSeq = seq.Seq
	p.fieldKey = fmt.Sprintf("%x", p.beingSeq/63)
	p.fieldBit = 1 << uint64(p.beingSeq%63)
	p.lastSlot = 0
	beings := beingsC(base)
	return errors.Trace(beings.Insert(
		beingInfo{
			DocID: docIDInt64(p.modelUUID, p.beingSeq),
			Seq:   p.beingSeq,
			Key:   p.beingKey,
		},
	))
}