// RunUndo performs the execution of 'rollout undo' sub command
190477
func (o *UndoOptions) RunUndo() error {
	r := o.Builder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		NamespaceParam(o.Namespace).DefaultNamespace().
		FilenameParam(o.EnforceNamespace, &o.FilenameOptions).
		ResourceTypeOrNameArgs(true, o.Resources...).
		ContinueOnError().
		Latest().
		Flatten().
		Do()
	if err := r.Err(); err != nil {
		return err
	}

	err := r.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			return err
		}
		rollbacker, err := polymorphichelpers.RollbackerFn(o.RESTClientGetter, info.ResourceMapping())
		if err != nil {
			return err
		}

		result, err := rollbacker.Rollback(info.Object, nil, o.ToRevision, o.DryRun)
		if err != nil {
			return err
		}

		printer, err := o.ToPrinter(result)
		if err != nil {
			return err
		}

		return printer.PrintObj(info.Object, o.Out)
	})

	return err
}
1242617
func (tio *Timeout) RunSimple(preserveStatus bool) int {
	cmd := tio.getCmd()
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	ch, err := tio.RunCommand()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return getExitCodeFromErr(err)
	}

	exitSt := <-ch
	if preserveStatus {
		return exitSt.GetChildExitCode()
	}
	return exitSt.GetExitCode()
}
442271
func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) {
	go wait.Until(func() {
		if err := m.RegenerateMappings(); err != nil {
			klog.Errorf("error regenerating REST mappings from discovery: %v", err)
		}
	}, m.refreshInterval, stop)
}
620844
func (m *MockRunner) RunTransaction(arg0 *txn.Transaction) error {
	ret := m.ctrl.Call(m, "RunTransaction", arg0)
	ret0, _ := ret[0].(error)
	return ret0
}
136120
func (b *storageDBWrapper) runTransaction(ops []txn.Op) error {
	err := b.txnRunner.RunTransaction(&jujutxn.Transaction{Ops: ops})
	return errors.Trace(err)
}
1110692
func (c *ServicedCli) cmdSnapshotRollback(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "rollback")
		return
	}

	if err := c.driver.Rollback(args[0], ctx.Bool("force-restart")); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	} else {
		fmt.Println(args[0])
	}
}
110843
func (r *runner) RestartRun(qr QueuedRun) bool {
	if !atomic.CompareAndSwapUint32(r.state, runnerIdle, runnerWorking) {
		// already working
		return false
	}
	// create a QueuedRun because we cant stm.CreateNextRun
	runLogger := r.logger.With(zap.String("run_id", qr.RunID.String()), zap.Int64("now", qr.Now))
	r.wg.Add(1)
	r.ts.runningMu.Lock()
	rCtx, ok := r.ts.running[qr.RunID]
	if !ok {
		ctx, cancel := context.WithCancel(context.TODO())
		rCtx = runCtx{Context: ctx, CancelFunc: cancel}
		r.ts.running[qr.RunID] = rCtx
	}
	r.ts.runningMu.Unlock()
	go r.executeAndWait(rCtx.Context, qr, runLogger)

	r.updateRunState(qr, RunStarted, runLogger)
	return true
}
652255
func NewRolloutUndoOptions(streams genericclioptions.IOStreams) *UndoOptions {
	return &UndoOptions{
		PrintFlags: genericclioptions.NewPrintFlags("rolled back").WithTypeSetter(scheme.Scheme),
		IOStreams:  streams,
		ToRevision: int64(0),
	}
}
1108837
func (f *Facade) Rollback(ctx datastore.Context, snapshotID string, force bool) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.Rollback"))
	// Do not DFSLock here, ControlPlaneDao does that
	logger := plog.WithField("snapshotid", snapshotID)
	logger.Infof("Started rollback of snapshot")
	info, err := f.dfs.Info(snapshotID)
	if err != nil {
		logger.WithError(err).Debug("Could not get info for snapshot")
		return err
	}
	logger = logger.WithField("tenantid", info.TenantID)
	if err := f.lockTenant(ctx, info.TenantID); err != nil {
		logger.WithError(err).Debug("Could not lock tenant")
		return err
	}
	defer f.retryUnlockTenant(ctx, info.TenantID, nil, time.Second)
	logger.Info("Got tenant lock")
	svcs, err := f.GetServices(ctx, dao.ServiceRequest{TenantID: info.TenantID})
	if err != nil {
		logger.WithError(err).Debug("Could not get services under tenant")
		return err
	}
	serviceids := make([]string, len(svcs))
	servicesToStop := []*service.Service{}
	var stoppedServiceIds []string
	for i, _ := range svcs {
		svc := &svcs[i]
		if svc.DesiredState == int(service.SVCRun) {
			servicesToStop = append(servicesToStop, svc)
			stoppedServiceIds = append(stoppedServiceIds, svc.ID)
			if !force {
				logger.WithFields(logrus.Fields{
					"servicename": svc.Name,
					"serviceid":   svc.ID,
				}).Debug("Could not rollback to snapshot; service is running")
				return errors.New("service is running")
			}
		}
		serviceids[i] = svc.ID
	}

	// Stop the services that need stopping in a batch
	if _, err := scheduleServices(f, servicesToStop, ctx, info.TenantID, service.SVCStop, false); err != nil {
		logger.WithError(err).Debug("Could not stop services for rollback")
		return err
	}

	defer func() {
		// Refresh service objects in case something has changed (like current state)
		servicesToStop = f.GetServicesForScheduling(ctx, stoppedServiceIds)
		scheduleServices(f, servicesToStop, ctx, info.TenantID, service.SVCRun, false)
	}()

	if err := f.WaitService(ctx, service.SVCStop, f.dfs.Timeout(), false, serviceids...); err != nil {
		logger.WithError(err).Debug("Could not wait for services to stop during rollback of snapshot")
		return err
	}
	logger.Info("Services are all stopped")
	if err := f.RestoreServices(ctx, info.TenantID, info.Services); err != nil {
		logger.WithError(err).Debug("Could not restore services")
		return err
	}
	logger.Infof("Service data is rolled back")
	if err := f.dfs.Rollback(snapshotID); err != nil {
		logger.WithError(err).Debug("Could not rollback snapshot")
		return err
	}
	logger.Info("Successfully restored application data from snapshot")
	return nil
}
83548
func (s *Service) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error {
	err := s.kv.Update(ctx, func(tx Tx) error {
		err := s.cancelRun(ctx, tx, taskID, runID)
		if err != nil {
			return err
		}
		return nil
	})
	return err
}
1365562
func (check StatusChecker) RunCheck() Status {
	statusChannel := make(chan Status, 1)
	go func() {
		status := check()
		if status.GoodToGo {
			status.Message = "OK"
		}
		statusChannel <- status
	}()
	select {
	case status := <-statusChannel:
		return status
	case <-time.After(time.Second * time.Duration(timeout)):
		return Status{GoodToGo: false, Message: timeoutMessage}
	}
}
385469
func (j *janitorRunner) runCleaning() {
	dead, err := j.detector.Detect()
	if err != nil {
		j.errs <- err
		return
	}

	var wg sync.WaitGroup
	wg.Add(len(dead))

	for _, worker := range dead {
		go func(worker string) {
			defer wg.Done()

			err := j.handleDeath(worker)
			if err != nil && err != redsync.ErrFailed {
				j.errs <- err
			}
		}(worker)
	}

	wg.Wait()
}
533410
func (m *collection) runMerger() {
	defer func() {
		close(m.doneMergerCh)

		atomic.AddUint64(&m.stats.TotMergerEnd, 1)
	}()

	maxPreMergerBatches := m.options.MaxPreMergerBatches
	if maxPreMergerBatches <= 0 {
		maxPreMergerBatches =
			DefaultCollectionOptions.MaxPreMergerBatches
	}

	if maxPreMergerBatches >= math.MaxInt32 {
		return // Way to disable merger.
	}

	pings := []ping{}

	defer func() {
		replyToPings(pings)
		pings = pings[0:0]
	}()

	go m.idleMergerWaker()

OUTER:
	for {
		atomic.AddUint64(&m.stats.TotMergerLoop, 1)

		// ---------------------------------------------
		// Notify ping'ers from the previous loop.

		replyToPings(pings)
		pings = pings[0:0]

		// ---------------------------------------------
		// Wait for new stackDirtyTop entries and/or pings.

		var stopped, mergeAll bool
		stopped, mergeAll, pings = m.mergerWaitForWork(pings)
		if stopped {
			return
		}

		// ---------------------------------------------
		// Atomically ingest stackDirtyTop into stackDirtyMid.

		var stackDirtyTopPrev *segmentStack
		var stackDirtyMidPrev *segmentStack
		var stackDirtyBase *segmentStack

		stackDirtyMid, _, _, _, _ :=
			m.snapshot(snapshotSkipClean|snapshotSkipDirtyBase,
				func(ss *segmentStack) {
					m.invalidateLatestSnapshotLOCKED()

					// m.stackDirtyMid takes 1 refs, and
					// stackDirtyMid takes 1 refs.
					ss.refs++

					stackDirtyTopPrev = m.stackDirtyTop
					m.stackDirtyTop = nil

					stackDirtyMidPrev = m.stackDirtyMid
					m.stackDirtyMid = ss

					stackDirtyBase = m.stackDirtyBase
					if stackDirtyBase != nil {
						// While waiting for persistence, might as well do
						mergeAll = true // a full merge to optimize reads.

						stackDirtyBase.addRef()
					}

					// Awake writers waiting for space in stackDirtyTop.
					m.stackDirtyTopCond.Broadcast()
				},
				false) // The collection level lock needs to be acquired.

		stackDirtyTopPrev.Close()
		stackDirtyMidPrev.Close()

		// ---------------------------------------------
		// Merge multiple stackDirtyMid layers.

		startTime := time.Now()

		mergerWasOk := m.mergerMain(stackDirtyMid, stackDirtyBase, mergeAll)
		if !mergerWasOk {
			continue OUTER
		}

		m.histograms["MergerUsecs"].Add(
			uint64(time.Since(startTime).Nanoseconds()/1000), 1)

		// ---------------------------------------------
		// Notify persister.

		m.mergerNotifyPersister()

		// ---------------------------------------------

		atomic.AddUint64(&m.stats.TotMergerLoopRepeat, 1)

		m.fireEvent(EventKindMergerProgress, time.Now().Sub(startTime))
	}

	// TODO: Concurrent merging of disjoint slices of stackDirtyMid
	// instead of the current, single-threaded merger?
	//
	// TODO: A busy merger means no feeding of the persister?
	//
	// TODO: Delay merger until lots of deletion tombstones?
	//
	// TODO: The base layer is likely the largest, so instead of heap
	// merging the base layer entries, treat the base layer with
	// special case to binary search to find better start points?
	//
	// TODO: Dynamically calc'ed soft max dirty top height, for
	// read-heavy (favor lower) versus write-heavy (favor higher)
	// situations?
}
331241
func runcgo2(pkg *Package, dynout, ofile string) error {
	cgo := cgotool(pkg.Context)
	workdir := cgoworkdir(pkg)

	args := []string{
		"-objdir", workdir,
	}
	switch {
	case version.Version > 1.5:
		args = append(args,
			"-dynpackage", pkg.Name,
			"-dynimport", ofile,
			"-dynout", dynout,
		)
	default:
		return errors.Errorf("unsuppored Go version: %v", runtime.Version())
	}
	var buf bytes.Buffer
	err := runOut(&buf, pkg.Dir, nil, cgo, args...)
	if err != nil {
		fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
		io.Copy(os.Stderr, &buf)
	}
	return err
}
496715
func (ctx *workflowContext) rollback() {
	defer recordDuration(time.Now(), "Rollback", ctx)

	// Run each cleanup function concurrently.  If there's an error
	// all we're going to do is log it as a warning, since at this
	// point there's nothing to do...
	ctx.logger.Info("Invoking rollback functions")
	var wg sync.WaitGroup
	wg.Add(len(ctx.transaction.rollbackFunctions))
	rollbackErr := callRollbackHook(ctx, &wg)
	if rollbackErr != nil {
		ctx.logger.WithFields(logrus.Fields{
			"Error": rollbackErr,
		}).Warning("Rollback Hook failed to execute")
	}
	for _, eachCleanup := range ctx.transaction.rollbackFunctions {
		go func(cleanupFunc spartaS3.RollbackFunction, goLogger *logrus.Logger) {
			// Decrement the counter when the goroutine completes.
			defer wg.Done()
			// Fetch the URL.
			err := cleanupFunc(goLogger)
			if nil != err {
				ctx.logger.WithFields(logrus.Fields{
					"Error": err,
				}).Warning("Failed to cleanup resource")
			}
		}(eachCleanup, ctx.logger)
	}
	wg.Wait()
}
866447
func (rh *RPCHandler) DeleteRepo(
	ctx context.Context, arg keybase1.DeleteRepoArg) (err error) {
	rh.log.CDebugf(ctx, "Deleting repo %s from folder %s/%s",
		arg.Name, arg.Folder.FolderType, arg.Folder.Name)
	defer func() {
		rh.log.CDebugf(ctx, "Done deleting repo: %+v", err)
	}()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	ctx, gitConfig, tlfHandle, tempDir, err := rh.getHandleAndConfig(
		ctx, arg.Folder)
	if err != nil {
		return err
	}
	defer func() {
		rmErr := os.RemoveAll(tempDir)
		if rmErr != nil {
			rh.log.CDebugf(
				ctx, "Error cleaning storage dir %s: %+v\n", tempDir, rmErr)
		}
	}()
	defer gitConfig.Shutdown(ctx)

	err = DeleteRepo(ctx, gitConfig, tlfHandle, string(arg.Name))
	if err != nil {
		return err
	}

	err = rh.waitForJournal(ctx, gitConfig, tlfHandle)
	if err != nil {
		return err
	}

	rh.scheduleCleaning(arg.Folder)
	return nil
}
974751
func (s *serviceConfigWatch) runWatch() {
	firstRun := true
	for {
		select {
		case <-s.ctx.Done():
			return
		case event := <-s.updateCh:
			if err := s.handleUpdate(event, false, firstRun); err != nil {
				s.agent.logger.Printf("[ERR] agent.manager: error handling service update: %v", err)
			}
			firstRun = false
		}
	}
}