// runPreCompilationSteps runs all of the regeneration steps that are necessary
// right before compiling the BPF for the given endpoint.
// The endpoint mutex must not be held.
492934
func (e *Endpoint) runPreCompilationSteps(owner Owner, regenContext *regenerationContext) (preCompilationError error) {
	stats := &regenContext.Stats
	datapathRegenCtxt := regenContext.datapathRegenerationContext

	stats.waitingForLock.Start()
	err := e.LockAlive()
	stats.waitingForLock.End(err == nil)
	if err != nil {
		return err
	}

	defer e.Unlock()

	currentDir := datapathRegenCtxt.currentDir
	nextDir := datapathRegenCtxt.nextDir

	// In the first ever regeneration of the endpoint, the conntrack table
	// is cleaned from the new endpoint IPs as it is guaranteed that any
	// pre-existing connections using that IP are now invalid.
	if !e.ctCleaned {
		go func() {
			if !option.Config.DryMode {
				ipv4 := option.Config.EnableIPv4
				ipv6 := option.Config.EnableIPv6
				created := ctmap.Exists(nil, ipv4, ipv6)
				if e.ConntrackLocal() {
					created = ctmap.Exists(e, ipv4, ipv6)
				}
				if created {
					e.scrubIPsInConntrackTable()
				}
			}
			close(datapathRegenCtxt.ctCleaned)
		}()
	} else {
		close(datapathRegenCtxt.ctCleaned)
	}

	if e.realizedPolicy == nil {
		e.realizedPolicy = &policy.EndpointPolicy{}
	}

	// If dry mode is enabled, no further changes to BPF maps are performed
	if option.Config.DryMode {

		// Compute policy for this endpoint.
		if err = e.regeneratePolicy(owner); err != nil {
			return fmt.Errorf("Unable to regenerate policy: %s", err)
		}

		_ = e.updateAndOverrideEndpointOptions(nil)

		// Dry mode needs Network Policy Updates, but the proxy wait group must
		// not be initialized, as there is no proxy ACKing the changes.
		if err, _ = e.updateNetworkPolicy(owner, nil); err != nil {
			return err
		}

		if err = e.writeHeaderfile(nextDir, owner); err != nil {
			return fmt.Errorf("Unable to write header file: %s", err)
		}

		log.WithField(logfields.EndpointID, e.ID).Debug("Skipping bpf updates due to dry mode")
		return nil
	}

	if e.PolicyMap == nil {
		e.PolicyMap, _, err = policymap.OpenOrCreate(e.PolicyMapPathLocked())
		if err != nil {
			return err
		}
		// Clean up map contents
		e.getLogger().Debug("flushing old PolicyMap")
		err = e.PolicyMap.DeleteAll()
		if err != nil {
			return err
		}

		// Also reset the in-memory state of the realized state as the
		// BPF map content is guaranteed to be empty right now.
		e.realizedPolicy.PolicyMapState = make(policy.MapState)
	}

	if e.bpfConfigMap == nil {
		e.bpfConfigMap, _, err = bpfconfig.OpenMapWithName(e.BPFConfigMapPath())
		if err != nil {
			return err
		}
		// Also reset the in-memory state of the realized state as the
		// BPF map content is guaranteed to be empty right now.
		e.realizedBPFConfig = &bpfconfig.EndpointConfig{}
	}

	// Only generate & populate policy map if a security identity is set up for
	// this endpoint.
	if e.SecurityIdentity != nil {
		stats.policyCalculation.Start()
		err = e.regeneratePolicy(owner)
		stats.policyCalculation.End(err == nil)
		if err != nil {
			return fmt.Errorf("unable to regenerate policy for '%s': %s", e.PolicyMap.String(), err)
		}

		_ = e.updateAndOverrideEndpointOptions(nil)

		// realizedBPFConfig may be updated at any point after we figure out
		// whether ingress/egress policy is enabled.
		e.desiredBPFConfig = bpfconfig.GetConfig(e)

		// Synchronously try to update PolicyMap for this endpoint. If any
		// part of updating the PolicyMap fails, bail out and do not generate
		// BPF. Unfortunately, this means that the map will be in an inconsistent
		// state with the current program (if it exists) for this endpoint.
		// GH-3897 would fix this by creating a new map to do an atomic swap
		// with the old one.
		stats.mapSync.Start()
		err := e.syncPolicyMap()
		stats.mapSync.End(err == nil)
		if err != nil {
			return fmt.Errorf("unable to regenerate policy because PolicyMap synchronization failed: %s", err)
		}

		// Synchronously update the BPF ConfigMap for this endpoint.
		// This is unlikely to fail, but will have the same
		// inconsistency issues as above if there is a failure. Long
		// term the solution to this is to templatize this map in the
		// ELF file, but there's no solution to this just yet.
		if err = e.bpfConfigMap.Update(e.desiredBPFConfig); err != nil {
			e.getLogger().WithError(err).Error("unable to update BPF config map")
			return err
		}

		datapathRegenCtxt.revertStack.Push(func() error {
			return e.bpfConfigMap.Update(e.realizedBPFConfig)
		})

		// Configure the new network policy with the proxies.
		stats.proxyPolicyCalculation.Start()
		var networkPolicyRevertFunc revert.RevertFunc
		err, networkPolicyRevertFunc = e.updateNetworkPolicy(owner, datapathRegenCtxt.proxyWaitGroup)
		stats.proxyPolicyCalculation.End(err == nil)
		if err != nil {
			return err
		}

		datapathRegenCtxt.revertStack.Push(networkPolicyRevertFunc)
	}

	stats.proxyConfiguration.Start()
	var finalizeFunc revert.FinalizeFunc
	var revertFunc revert.RevertFunc
	// Walk the L4Policy to add new redirects and update the desired policy map
	// state to set the newly allocated proxy ports.
	var desiredRedirects map[string]bool
	if e.desiredPolicy != nil && e.desiredPolicy.L4Policy != nil {
		desiredRedirects, err, finalizeFunc, revertFunc = e.addNewRedirects(owner, e.desiredPolicy.L4Policy, datapathRegenCtxt.proxyWaitGroup)
		if err != nil {
			stats.proxyConfiguration.End(false)
			return err
		}
		datapathRegenCtxt.finalizeList.Append(finalizeFunc)
		datapathRegenCtxt.revertStack.Push(revertFunc)
	}

	// At this point, traffic is no longer redirected to the proxy for
	// now-obsolete redirects, since we synced the updated policy map above.
	// It's now safe to remove the redirects from the proxy's configuration.
	finalizeFunc, revertFunc = e.removeOldRedirects(owner, desiredRedirects, datapathRegenCtxt.proxyWaitGroup)
	datapathRegenCtxt.finalizeList.Append(finalizeFunc)
	datapathRegenCtxt.revertStack.Push(revertFunc)
	stats.proxyConfiguration.End(true)

	stats.prepareBuild.Start()
	defer func() {
		stats.prepareBuild.End(preCompilationError == nil)
	}()

	// Generate header file specific to this endpoint for use in compiling
	// BPF programs for this endpoint.
	if err = e.writeHeaderfile(nextDir, owner); err != nil {
		return fmt.Errorf("unable to write header file: %s", err)
	}

	// Avoid BPF program compilation and installation if the headerfile for the endpoint
	// or the node have not changed.
	datapathRegenCtxt.bpfHeaderfilesHash, err = loader.EndpointHash(e)
	if err != nil {
		e.getLogger().WithError(err).Warn("Unable to hash header file")
		datapathRegenCtxt.bpfHeaderfilesHash = ""
		datapathRegenCtxt.regenerationLevel = RegenerateWithDatapathRewrite
	} else {
		changed := (datapathRegenCtxt.bpfHeaderfilesHash != e.bpfHeaderfileHash)
		if changed {
			datapathRegenCtxt.regenerationLevel = RegenerateWithDatapathRewrite
		}
		e.getLogger().WithField(logfields.BPFHeaderfileHash, datapathRegenCtxt.bpfHeaderfilesHash).
			Debugf("BPF header file hashed (was: %q)", e.bpfHeaderfileHash)
	}

	// Cache endpoint information so that we can release the endpoint lock.
	if datapathRegenCtxt.regenerationLevel >= RegenerateWithDatapathRewrite {
		datapathRegenCtxt.epInfoCache = e.createEpInfoCache(nextDir)
	} else {
		datapathRegenCtxt.epInfoCache = e.createEpInfoCache(currentDir)
	}
	if datapathRegenCtxt.epInfoCache == nil {
		return fmt.Errorf("Unable to cache endpoint information")
	}

	return nil
}
441606
func (t *WaitForFilteredReplicationTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) {
	keyspaceAndShard := topoproto.KeyspaceShardString(parameters["keyspace"], parameters["shard"])
	output, err := ExecuteVtctl(context.TODO(), parameters["vtctld_endpoint"],
		[]string{"WaitForFilteredReplication", "-max_delay", parameters["max_delay"], keyspaceAndShard})
	return nil, output, err
}
33630
func (c *ListCharmResourcesCommand) Run(ctx *cmd.Context) error {
	ctx.Warningf(DeprecatedSince)
	return c.baseRun(ctx)
}
1255557
func (as *Step) AddStep(name string, legacy bool) *Step {
	return (&Step{}).initializeStep(as.s, as, name, legacy)
}
989217
func (pipeline *Pipeline) Run() error {
	endpoints := pipeline.source.Endpoints()
	// send a boot event
	pipeline.source.pipe.Event <- events.NewBootEvent(time.Now().UnixNano(), pipeline.version, endpoints)

	errors := make(chan error, 2)
	go func() {
		errors <- pipeline.startErrorListener()
	}()
	go func() {
		errors <- pipeline.source.Start()
	}()

	return <-errors
}
614098
func (step extraConfigUpgradeStep) Run(ctx context.ProviderCallContext) error {
	const (
		legacyControllerTag   = "juju_controller_uuid_key"
		legacyIsControllerTag = "juju_is_controller_key"
	)
	return step.env.withSession(ctx, func(env *sessionEnviron) error {
		vms, err := env.client.VirtualMachines(env.ctx, env.namespace.Prefix()+"*")
		if err != nil || len(vms) == 0 {
			HandleCredentialError(err, ctx)
			return err
		}
		for _, vm := range vms {
			update := false
			isController := false
			for _, opt := range vm.Config.ExtraConfig {
				value := opt.GetOptionValue()
				switch value.Key {
				case legacyControllerTag:
					update = true
				case legacyIsControllerTag:
					isController = true
				}
			}
			if !update {
				continue
			}
			metadata := map[string]string{
				tags.JujuController: step.controllerUUID,
				tags.JujuModel:      env.Config().UUID(),
			}
			if isController {
				metadata[tags.JujuIsController] = "true"
			}
			if err := env.client.UpdateVirtualMachineExtraConfig(
				env.ctx, vm, metadata,
			); err != nil {
				HandleCredentialError(err, ctx)
				return errors.Annotatef(err, "updating VM %s", vm.Name)
			}
		}
		return nil
	})
}
1196077
func (c *ReportingClient) RunStepsAdded(ctx context.Context, args RunStepsAddedArgs) error {
	return c.postJSON("runstepsadded", args)
}
761160
func RunTemplates(o *Config) error {
	Metrics = newMetrics()
	defer runCleanupHooks()
	// make sure config is sane
	o.defaults()
	ds := append(o.DataSources, o.Contexts...)
	d, err := data.NewData(ds, o.DataSourceHeaders)
	if err != nil {
		return err
	}
	addCleanupHook(d.Cleanup)
	nested, err := parseTemplateArgs(o.Templates)
	if err != nil {
		return err
	}
	c, err := createContext(o.Contexts, d)
	if err != nil {
		return err
	}
	g := newGomplate(d, o.LDelim, o.RDelim, nested, c)

	return g.runTemplates(o)
}
372398
func deleteESuffixPrecededByNonVowel(s []rune, r1 int) ([]rune, bool) {
	if i := len(s) - 1; i >= r1 && s[i] == 'e' && !isVowelAt(s, i-1) {
		s = s[:i]
		return s, true
	}
	return s, false
}
979051
func RunWithPrelude(vm *otto.Otto, prelude string) error {
	return RunWithOptions(vm, Options{
		Prelude: prelude,
	})
}
1068877
func (c *ReportingClient) RunStepFinished(ctx context.Context, args RunStepFinishedArgs) error {
	return c.postJSON("runstepfinished", args)
}
794727
func (ar *allocRunner) prerun() error {
	if ar.logger.IsTrace() {
		start := time.Now()
		ar.logger.Trace("running pre-run hooks", "start", start)
		defer func() {
			end := time.Now()
			ar.logger.Trace("finished pre-run hooks", "end", end, "duration", end.Sub(start))
		}()
	}

	for _, hook := range ar.runnerHooks {
		pre, ok := hook.(interfaces.RunnerPrerunHook)
		if !ok {
			continue
		}

		name := pre.Name()
		var start time.Time
		if ar.logger.IsTrace() {
			start = time.Now()
			ar.logger.Trace("running pre-run hook", "name", name, "start", start)
		}

		if err := pre.Prerun(); err != nil {
			return fmt.Errorf("pre-run hook %q failed: %v", name, err)
		}

		if ar.logger.IsTrace() {
			end := time.Now()
			ar.logger.Trace("finished pre-run hook", "name", name, "end", end, "duration", end.Sub(start))
		}
	}

	return nil
}
523645
func buildOnPremTagFilters(configured []interface{}) []*codedeploy.TagFilter {
	filters := make([]*codedeploy.TagFilter, 0)
	for _, raw := range configured {
		var filter codedeploy.TagFilter
		m := raw.(map[string]interface{})

		if v, ok := m["key"]; ok {
			filter.Key = aws.String(v.(string))
		}
		if v, ok := m["type"]; ok {
			filter.Type = aws.String(v.(string))
		}
		if v, ok := m["value"]; ok {
			filter.Value = aws.String(v.(string))
		}

		filters = append(filters, &filter)
	}

	return filters
}
771389
func RunKustomizeBuild(out io.Writer, fSys fs.FileSystem, path string) error {
	f := k8sdeps.NewFactory()
	o := build.NewOptions(path, "")
	return o.RunBuild(out, fSys, f.ResmapF, f.TransformerF)
}
1071416
func Preprocess(ctx sessionctx.Context, node ast.Node, is infoschema.InfoSchema, preprocessOpt ...PreprocessOpt) error {
	v := preprocessor{is: is, ctx: ctx, tableAliasInJoin: make([]map[string]interface{}, 0)}
	for _, optFn := range preprocessOpt {
		optFn(&v)
	}
	node.Accept(&v)
	return errors.Trace(v.err)
}
31410
func (service *Service) EvaluateRunsTemplate(gs GetService, fc FindChildService) (err error) {
	for key, value := range service.Runs {
		err, result := service.evaluateTemplate(gs, fc, 0, value)
		if err != nil {
			return err
		}
		if result != "" {
			service.Runs[key] = result
		}
	}
	for key, value := range service.Commands {
		err, result := service.evaluateTemplate(gs, fc, 0, value.Command)
		if err != nil {
			return err
		}
		if result != "" {
			value.Command = result
			service.Commands[key] = value
		}
	}
	return
}
26712
func (h *HTTPExtender) ProcessPreemption(
	pod *v1.Pod,
	nodeToVictims map[*v1.Node]*schedulerapi.Victims,
	nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
) (map[*v1.Node]*schedulerapi.Victims, error) {
	var (
		result schedulerapi.ExtenderPreemptionResult
		args   *schedulerapi.ExtenderPreemptionArgs
	)

	if !h.SupportsPreemption() {
		return nil, fmt.Errorf("preempt verb is not defined for extender %v but run into ProcessPreemption", h.extenderURL)
	}

	if h.nodeCacheCapable {
		// If extender has cached node info, pass NodeNameToMetaVictims in args.
		nodeNameToMetaVictims := convertToNodeNameToMetaVictims(nodeToVictims)
		args = &schedulerapi.ExtenderPreemptionArgs{
			Pod:                   pod,
			NodeNameToMetaVictims: nodeNameToMetaVictims,
		}
	} else {
		nodeNameToVictims := convertToNodeNameToVictims(nodeToVictims)
		args = &schedulerapi.ExtenderPreemptionArgs{
			Pod:               pod,
			NodeNameToVictims: nodeNameToVictims,
		}
	}

	if err := h.send(h.preemptVerb, args, &result); err != nil {
		return nil, err
	}

	// Extender will always return NodeNameToMetaVictims.
	// So let's convert it to NodeToVictims by using NodeNameToInfo.
	newNodeToVictims, err := h.convertToNodeToVictims(result.NodeNameToMetaVictims, nodeNameToInfo)
	if err != nil {
		return nil, err
	}
	// Do not override nodeToVictims
	return newNodeToVictims, nil
}