// Run is a part of workflow.Workflow interface. This is the main entrance point of the schema swap workflow.
485102
func (schemaSwap *Swap) Run(ctx context.Context, manager *workflow.Manager, workflowInfo *topo.WorkflowInfo) error {
	schemaSwap.ctx = ctx
	schemaSwap.workflowManager = manager
	schemaSwap.topoServer = manager.TopoServer()
	schemaSwap.tabletClient = tmclient.NewTabletManagerClient()

	log.Infof("Starting schema swap on keyspace %v with the following SQL: %v", schemaSwap.keyspace, schemaSwap.sql)

	for {
		err := schemaSwap.executeSwap()
		if err == nil {
			return nil
		}
		// If context is cancelled then return right away, otherwise move on to allow
		// user to retry.
		select {
		case <-schemaSwap.ctx.Done():
			schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err))
			return err
		default:
		}

		schemaSwap.retryMutex.Lock()
		retryAction := &workflow.Action{
			Name:  "Retry",
			State: workflow.ActionStateEnabled,
			Style: workflow.ActionStyleWaiting,
		}
		schemaSwap.rootUINode.Actions = []*workflow.Action{retryAction}
		schemaSwap.rootUINode.Listener = schemaSwap
		schemaSwap.retryChannel = make(chan struct{})
		schemaSwap.retryMutex.Unlock()
		// setUIMessage broadcasts changes to rootUINode.
		schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err))

		select {
		case <-schemaSwap.retryChannel:
			schemaSwap.setUIMessage("Retrying schema swap after an error")
			continue
		case <-schemaSwap.ctx.Done():
			schemaSwap.closeRetryChannel()
			return schemaSwap.ctx.Err()
		}
	}
}
1320246
func (c *runner) Run(name string, arg ...string) error {
	return c.RunWithOptions(CommandOpts{}, name, arg...)
}
1123248
func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error) {
	opts := map[string]interface{}{}
	var ctx context.Context = nil // if it's nil connection will form context from connection opts
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
		ctx = optArgs[0].Context
	}

	if s == nil || !s.IsConnected() {
		return nil, ErrConnectionClosed
	}

	q, err := s.newQuery(t, opts)
	if err != nil {
		return nil, err
	}

	return s.Query(ctx, q)
}
1305966
func (t *CopySchemaShardTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) {
	args := []string{"CopySchemaShard"}
	if tables := parameters["tables"]; tables != "" {
		args = append(args, "--tables="+tables)
	}
	if excludeTables := parameters["exclude_tables"]; excludeTables != "" {
		args = append(args, "--exclude_tables="+excludeTables)
	}
	args = append(args, parameters["source_keyspace_and_shard"], parameters["dest_keyspace_and_shard"])
	output, err := ExecuteVtctl(context.TODO(), parameters["vtctld_endpoint"], args)
	return nil, output, err
}
432593
func (m *Main) Run() error {
	src, err := NewJSONSource(WithAddr(m.Bind))
	if err != nil {
		return errors.Wrap(err, "getting json source")
	}

	if m.TranslatorDir == "" {
		m.TranslatorDir, err = ioutil.TempDir("", "pdk")
		if err != nil {
			return errors.Wrap(err, "creating temp directory")
		}
	}

	log.Println("listening on", src.Addr())

	translateColumns := true
	parser := pdk.NewDefaultGenericParser()
	if len(m.SubjectPath) == 0 {
		parser.Subjecter = pdk.BlankSubjecter{}
		translateColumns = false
	} else {
		parser.EntitySubjecter = pdk.SubjectPath(m.SubjectPath)
	}

	mapper := pdk.NewCollapsingMapper()
	mapper.Translator, err = leveldb.NewTranslator(m.TranslatorDir)
	if err != nil {
		return errors.Wrap(err, "creating translator")
	}
	mapper.Framer = &m.Framer
	if translateColumns {
		log.Println("translating columns")
		mapper.ColTranslator, err = leveldb.NewFieldTranslator(m.TranslatorDir, "__columns")
		if err != nil {
			return errors.Wrap(err, "creating column translator")
		}
	} else {
		log.Println("not translating columns")
	}

	indexer, err := pdk.SetupPilosa(m.PilosaHosts, m.Index, nil, m.BatchSize)
	if err != nil {
		return errors.Wrap(err, "setting up Pilosa")
	}

	ingester := pdk.NewIngester(src, parser, mapper, indexer)
	if len(m.AllowedFields) > 0 {
		ingester.AllowedFields = make(map[string]bool)
		for _, fram := range m.AllowedFields {
			ingester.AllowedFields[fram] = true
		}
	}
	m.proxy = http.Server{
		Addr:    m.Proxy,
		Handler: pdk.NewPilosaForwarder(m.PilosaHosts[0], mapper.Translator, mapper.ColTranslator),
	}
	go func() {
		err := m.proxy.ListenAndServe()
		if err != nil {
			log.Printf("proxy closed: %v", err)
		}
	}()
	return errors.Wrap(ingester.Run(), "running ingester")
}
719010
func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
	}
	if len(req.files) > 0 && !c.useMultipartForm {
		return errors.New("cannot send files with PostFields option")
	}
	if c.useMultipartForm {
		return c.runWithPostFields(ctx, req, resp)
	}
	return c.runWithJSON(ctx, req, resp)
}
484180
func (m *Main) Run() error {
	if m.Seed == -1 {
		m.Seed = time.Now().UnixNano()
	}

	schema := gopilosa.NewSchema()
	idx := schema.Index(m.Index)
	idx.Field(m.Field, gopilosa.OptFieldTypeSet(gopilosa.CacheTypeRanked, 50000))
	indexer, err := pdk.SetupPilosa(m.PilosaHosts, m.Index, schema, m.BatchSize)
	if err != nil {
		return errors.Wrap(err, "setting up Pilosa")
	}

	ug := newUserGetter(m.Seed)

	for i := uint64(0); i < m.Num; i++ {
		indexer.AddColumn(m.Field, i, ug.ID())
	}

	return errors.Wrap(indexer.Close(), "closing indexer")
}
646371
func (k8s *Kubernetes) Run(qorJob worker.QorJobInterface) error {
	job := qorJob.GetJob()

	if job.Handler != nil {
		return job.Handler(qorJob.GetSerializableArgument(qorJob), qorJob)
	}

	return errors.New("no handler found for job " + job.Name)
}
772900
func (p *Prove) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("ProofEngine.Run", func() error { return err })()

	stage := func(s string) {
		m.Debug("| ProofEngine.Run() %s", s)
	}

	stage("GetServiceType")
	if err = p.getServiceType(m); err != nil {
		return err
	}
	stage("LoadMe")
	if err = p.loadMe(m); err != nil {
		return err
	}
	stage("CheckExists1")
	if err = p.checkExists1(m); err != nil {
		return err
	}
	stage("PromptRemoteName")
	if err = p.promptRemoteName(m); err != nil {
		return err
	}
	stage("CheckExists2")
	if err = p.checkExists2(m); err != nil {
		return err
	}
	stage("DoPrechecks")
	if err = p.doPrechecks(m); err != nil {
		return err
	}
	stage("DoWarnings")
	if err = p.doWarnings(m); err != nil {
		return err
	}
	m.G().LocalSigchainGuard().Set(m.Ctx(), "Prove")
	defer m.G().LocalSigchainGuard().Clear(m.Ctx(), "Prove")
	stage("GenerateProof")
	if err = p.generateProof(m); err != nil {
		return err
	}
	stage("PostProofToServer")
	if err = p.postProofToServer(m); err != nil {
		return err
	}
	m.G().LocalSigchainGuard().Clear(m.Ctx(), "Prove")
	stage("CheckProofText")
	if err = p.checkProofText(m); err != nil {
		return err
	}
	stage("InstructAction")
	if err = p.instructAction(m); err != nil {
		return err
	}

	if !p.arg.PromptPosted {
		m.Debug("PromptPosted not set, prove run finished")
		return nil
	}

	stage("CheckStart")
	if p.serviceParameters == nil {
		stage("PromptPostedLoop")
		if err = p.promptPostedLoop(m); err != nil {
			return err
		}
	} else {
		stage("VerifyLoop")
		if err = p.verifyLoop(m); err != nil {
			return err
		}
	}
	m.UIs().LogUI.Notice("Success!")
	return nil
}
496263
func (ec *ServiceManager) Run() (err error) {

	// Launch services
	for _, s := range ec.services {
		ec.wg.Add(1)
		go ec.execute(s)
	}

	// Start event loop
	go ec.eventLoop()

	return nil
}
1299409
func (e *MirrorKeystore) Run(c *fi.Context) error {
	return fi.DefaultDeltaRunMethod(e, c)
}
1068675
func (c *Copier) Run() {
	for src, w := range c.srcs {
		c.copyJobs.Add(1)
		go c.copySrc(src, w)
	}
}
791881
func (u *Updater) Run(ctx context.Context, slots []orchestrator.Slot) {
	defer close(u.doneChan)

	service := u.newService

	// If the update is in a PAUSED state, we should not do anything.
	if service.UpdateStatus != nil &&
		(service.UpdateStatus.State == api.UpdateStatus_PAUSED ||
			service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_PAUSED) {
		return
	}

	var dirtySlots []orchestrator.Slot
	for _, slot := range slots {
		if u.isSlotDirty(slot) {
			dirtySlots = append(dirtySlots, slot)
		}
	}
	// Abort immediately if all tasks are clean.
	if len(dirtySlots) == 0 {
		if service.UpdateStatus == nil {
			if u.annotationsUpdated(service) {
				// Annotation-only update; mark the update as completed
				u.completeUpdate(ctx, service.ID, true)
			}
			return
		}
		if service.UpdateStatus.State == api.UpdateStatus_UPDATING || service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
			// Update or rollback was started, and is now complete
			u.completeUpdate(ctx, service.ID, true)
			return
		}
		return
	}

	// If there's no update in progress, we are starting one.
	if service.UpdateStatus == nil {
		u.startUpdate(ctx, service.ID)
	}

	var (
		monitoringPeriod time.Duration
		updateConfig     *api.UpdateConfig
	)

	if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
		monitoringPeriod, _ = gogotypes.DurationFromProto(defaults.Service.Rollback.Monitor)
		updateConfig = service.Spec.Rollback
		if updateConfig == nil {
			updateConfig = defaults.Service.Rollback
		}
	} else {
		monitoringPeriod, _ = gogotypes.DurationFromProto(defaults.Service.Update.Monitor)
		updateConfig = service.Spec.Update
		if updateConfig == nil {
			updateConfig = defaults.Service.Update
		}
	}

	parallelism := int(updateConfig.Parallelism)
	if updateConfig.Monitor != nil {
		newMonitoringPeriod, err := gogotypes.DurationFromProto(updateConfig.Monitor)
		if err == nil {
			monitoringPeriod = newMonitoringPeriod
		}
	}

	if parallelism == 0 {
		// TODO(aluzzardi): We could try to optimize unlimited parallelism by performing updates in a single
		// goroutine using a batch transaction.
		parallelism = len(dirtySlots)
	}

	// Start the workers.
	slotQueue := make(chan orchestrator.Slot)
	wg := sync.WaitGroup{}
	wg.Add(parallelism)
	for i := 0; i < parallelism; i++ {
		go func() {
			u.worker(ctx, slotQueue, updateConfig)
			wg.Done()
		}()
	}

	var failedTaskWatch chan events.Event

	if updateConfig.FailureAction != api.UpdateConfig_CONTINUE {
		var cancelWatch func()
		failedTaskWatch, cancelWatch = state.Watch(
			u.store.WatchQueue(),
			api.EventUpdateTask{
				Task:   &api.Task{ServiceID: service.ID, Status: api.TaskStatus{State: api.TaskStateRunning}},
				Checks: []api.TaskCheckFunc{api.TaskCheckServiceID, state.TaskCheckStateGreaterThan},
			},
		)
		defer cancelWatch()
	}

	stopped := false
	failedTasks := make(map[string]struct{})
	totalFailures := 0

	failureTriggersAction := func(failedTask *api.Task) bool {
		// Ignore tasks we have already seen as failures.
		if _, found := failedTasks[failedTask.ID]; found {
			return false
		}

		// If this failed/completed task is one that we
		// created as part of this update, we should
		// follow the failure action.
		u.updatedTasksMu.Lock()
		startedAt, found := u.updatedTasks[failedTask.ID]
		u.updatedTasksMu.Unlock()

		if found && (startedAt.IsZero() || time.Since(startedAt) <= monitoringPeriod) {
			failedTasks[failedTask.ID] = struct{}{}
			totalFailures++
			if float32(totalFailures)/float32(len(dirtySlots)) > updateConfig.MaxFailureRatio {
				switch updateConfig.FailureAction {
				case api.UpdateConfig_PAUSE:
					stopped = true
					message := fmt.Sprintf("update paused due to failure or early termination of task %s", failedTask.ID)
					u.pauseUpdate(ctx, service.ID, message)
					return true
				case api.UpdateConfig_ROLLBACK:
					// Never roll back a rollback
					if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
						message := fmt.Sprintf("rollback paused due to failure or early termination of task %s", failedTask.ID)
						u.pauseUpdate(ctx, service.ID, message)
						return true
					}
					stopped = true
					message := fmt.Sprintf("update rolled back due to failure or early termination of task %s", failedTask.ID)
					u.rollbackUpdate(ctx, service.ID, message)
					return true
				}
			}
		}

		return false
	}

slotsLoop:
	for _, slot := range dirtySlots {
	retryLoop:
		for {
			// Wait for a worker to pick up the task or abort the update, whichever comes first.
			select {
			case <-u.stopChan:
				stopped = true
				break slotsLoop
			case ev := <-failedTaskWatch:
				if failureTriggersAction(ev.(api.EventUpdateTask).Task) {
					break slotsLoop
				}
			case slotQueue <- slot:
				break retryLoop
			}
		}
	}

	close(slotQueue)
	wg.Wait()

	if !stopped {
		// Keep watching for task failures for one more monitoringPeriod,
		// before declaring the update complete.
		doneMonitoring := time.After(monitoringPeriod)
	monitorLoop:
		for {
			select {
			case <-u.stopChan:
				stopped = true
				break monitorLoop
			case <-doneMonitoring:
				break monitorLoop
			case ev := <-failedTaskWatch:
				if failureTriggersAction(ev.(api.EventUpdateTask).Task) {
					break monitorLoop
				}
			}
		}
	}

	// TODO(aaronl): Potentially roll back the service if not enough tasks
	// have reached RUNNING by this point.

	if !stopped {
		u.completeUpdate(ctx, service.ID, false)
	}
}
810148
func (e *PerUserKeyUpkeep) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("PerUserKeyUpkeep", func() error { return err })()
	return e.inner(m)
}
318375
func (b *Work) Run() {
	b.Init()
	b.start = now()
	b.report = newReport(b.writer(), b.results, b.Output, b.N)
	// Run the reporter first, it polls the result channel until it is closed.
	go func() {
		runReporter(b.report)
	}()
	b.runWorkers()
	b.Finish()
}
1036634
func (o *RequestProjectOptions) Run() error {
	if err := o.Client.RESTClient().Get().Resource("projectrequests").Do().Into(&metav1.Status{}); err != nil {
		return err
	}

	projectRequest := &projectv1.ProjectRequest{}
	projectRequest.Name = o.ProjectName
	projectRequest.DisplayName = o.DisplayName
	projectRequest.Description = o.Description
	projectRequest.Annotations = make(map[string]string)

	project, err := o.Client.ProjectRequests().Create(projectRequest)
	if err != nil {
		return err
	}

	if o.ProjectOptions != nil {
		o.ProjectOptions.ProjectName = project.Name
		o.ProjectOptions.ProjectOnly = true
		o.ProjectOptions.SkipAccessValidation = true
		o.ProjectOptions.IOStreams = o.IOStreams
		if err := o.ProjectOptions.Run(); err != nil {
			return err
		}

		fmt.Fprintf(o.Out, requestProjectNewAppOutput, o.Name)
	} else {
		fmt.Fprintf(o.Out, requestProjectSwitchProjectOutput, o.Name, o.ProjectName, o.Server)
	}

	return nil
}
1119589
func (p *Pipeline) Run(ctx context.Context) (err error) {
	if pdebug.Enabled {
		g := pdebug.Marker("Pipeline.Run (%s)", ctx.Value("query")).BindError(&err)
		defer g.End()
	}
	p.mutex.Lock()
	defer p.mutex.Unlock()
	defer close(p.done)

	if p.src == nil {
		return errors.New("source must be non-nil")
	}

	if p.dst == nil {
		return errors.New("destination must be non-nil")
	}

	// Reset is called on the source/destination to effectively reset
	// any state changes that may have happened in the end of
	// the previous call to Run()
	p.src.Reset()
	p.dst.Reset()

	// Setup the Acceptors, effectively chaining all nodes
	// starting from the destination, working all the way
	// up to the Source
	var prevCh ChanOutput = ChanOutput(make(chan interface{}))
	go p.dst.Accept(ctx, prevCh, nil)

	for i := len(p.nodes) - 1; i >= 0; i-- {
		cur := p.nodes[i]
		ch := make(chan interface{}) //
		go cur.Accept(ctx, ch, prevCh)
		prevCh = ChanOutput(ch)
	}

	// And now tell the Source to send the values so data chugs
	// through the pipeline
	go p.src.Start(ctx, prevCh)

	// Wait till we're done
	<-p.dst.Done()

	return nil
}