// Run executes the Report.
//
// Calling Run with print set to true emits data about each file to the report's
// Stdout fd as it is generated.
320389
func (r *Report) Run(print bool) (*ReportSummary, error) {
	if r.Stderr == nil {
		r.Stderr = os.Stderr
	}
	if r.Stdout == nil {
		r.Stdout = os.Stdout
	}

	if !print {
		r.Stderr, r.Stdout = ioutil.Discard, ioutil.Discard
	}

	newCounterFn := newHLLCounter
	estTitle := " (est)"
	if r.Exact {
		estTitle = ""
		newCounterFn = newExactCounter
	}

	fi, err := os.Stat(r.Dir)
	if err != nil {
		return nil, err
	} else if !fi.IsDir() {
		return nil, errors.New("data directory not valid")
	}

	totalSeries := newCounterFn()               // The exact or estimated unique set of series keys across all files.
	orgCardinalities := map[string]counter{}    // The exact or estimated unique set of series keys segmented by org.
	bucketCardinalities := map[string]counter{} // The exact or estimated unique set of series keys segmented by bucket.

	// These are calculated when the detailed flag is in use.
	mCardinalities := map[string]counter{} // The exact or estimated unique set of series keys segmented by the measurement tag.
	fCardinalities := map[string]counter{} // The exact or estimated unique set of series keys segmented by the field tag.
	tCardinalities := map[string]counter{} // The exact or estimated unique set of series keys segmented by tag keys.

	start := time.Now()

	tw := tabwriter.NewWriter(r.Stdout, 8, 2, 1, ' ', 0)
	fmt.Fprintln(tw, strings.Join([]string{"File", "Series", "New" + estTitle, "Min Time", "Max Time", "Load Time"}, "\t"))

	minTime, maxTime := int64(math.MaxInt64), int64(math.MinInt64)

	files, err := filepath.Glob(filepath.Join(r.Dir, "*.tsm"))
	if err != nil {
		panic(err) // Only error would be a bad pattern; not runtime related.
	}
	var processedFiles int

	var tagBuf models.Tags // Buffer that can be re-used when parsing keys.
	for _, path := range files {
		if r.Pattern != "" && strings.Contains(path, r.Pattern) {
			continue
		}

		file, err := os.OpenFile(path, os.O_RDONLY, 0600)
		if err != nil {
			fmt.Fprintf(r.Stderr, "error: %s: %v. Exiting.\n", path, err)
			return nil, err
		}

		loadStart := time.Now()
		reader, err := NewTSMReader(file)
		if err != nil {
			fmt.Fprintf(r.Stderr, "error: %s: %v. Skipping file.\n", file.Name(), err)
			continue
		}
		loadTime := time.Since(loadStart)
		processedFiles++

		// Tracks the current total, so it's possible to know how many new series this file adds.
		currentTotalCount := totalSeries.Count()

		seriesCount := reader.KeyCount()
		itr := reader.Iterator(nil)
		if itr == nil {
			return nil, errors.New("invalid TSM file, no index iterator")
		}

		for itr.Next() {
			key := itr.Key()

			var a [16]byte // TODO(edd) if this shows up we can use a different API to DecodeName.
			copy(a[:], key[:16])
			org, bucket := tsdb.DecodeName(a)
			if r.OrgID != nil && *r.OrgID != org { // If filtering on single org or bucket then skip if no match
				// org does not match.
				continue
			} else if r.BucketID != nil && *r.BucketID != bucket {
				// bucket does not match.
				continue
			}

			totalSeries.Add(key) // Update total cardinality.

			// Update org cardinality
			orgCount := orgCardinalities[org.String()]
			if orgCount == nil {
				orgCount = newCounterFn()
				orgCardinalities[org.String()] = orgCount
			}
			orgCount.Add(key)

			// Update bucket cardinality.
			bucketCount := bucketCardinalities[bucket.String()]
			if bucketCount == nil {
				bucketCount = newCounterFn()
				bucketCardinalities[bucket.String()] = bucketCount
			}
			bucketCount.Add(key)

			// Update tag cardinalities.
			if r.Detailed {
				sep := bytes.Index(key, KeyFieldSeparatorBytes)
				seriesKey := key[:sep] // Snip the tsm1 field key off.
				_, tagBuf = models.ParseKeyBytesWithTags(seriesKey, tagBuf)

				for _, t := range tagBuf {
					tk := string(t.Key)
					switch tk {
					case models.MeasurementTagKey:
						mname := string(t.Value)
						// Total series cardinality segmented by measurement name.
						mCount := mCardinalities[mname] // measurement name.
						if mCount == nil {
							mCount = newCounterFn()
							mCardinalities[mname] = mCount
						}
						mCount.Add(key) // full series keys associated with measurement name.
					case models.FieldKeyTagKey:
						mname := tagBuf.GetString(models.MeasurementTagKey)
						fCount := fCardinalities[mname]
						if fCount == nil {
							fCount = newCounterFn()
							fCardinalities[mname] = fCount
						}
						fCount.Add(t.Value) // field keys associated with measurement name.
					default:
						tagCount := tCardinalities[tk]
						if tagCount == nil {
							tagCount = newCounterFn()
							tCardinalities[tk] = tagCount
						}
						tagCount.Add(t.Value)
					}
				}
			}
		}

		minT, maxT := reader.TimeRange()
		if minT < minTime {
			minTime = minT
		}
		if maxT > maxTime {
			maxTime = maxT
		}

		if err := reader.Close(); err != nil {
			return nil, fmt.Errorf("error: %s: %v. Exiting", path, err)
		}

		fmt.Fprintln(tw, strings.Join([]string{
			filepath.Base(file.Name()),
			strconv.FormatInt(int64(seriesCount), 10),
			strconv.FormatInt(int64(totalSeries.Count()-currentTotalCount), 10),
			time.Unix(0, minT).UTC().Format(time.RFC3339Nano),
			time.Unix(0, maxT).UTC().Format(time.RFC3339Nano),
			loadTime.String(),
		}, "\t"))
		if r.Detailed {
			if err := tw.Flush(); err != nil {
				return nil, err
			}
		}
	}

	if err := tw.Flush(); err != nil {
		return nil, err
	}

	summary := newReportSummary()
	summary.Min = minTime
	summary.Max = maxTime
	summary.Total = totalSeries.Count()

	println()

	println("Summary:")
	fmt.Printf("  Files: %d (%d skipped)\n", processedFiles, len(files)-processedFiles)
	fmt.Printf("  Series Cardinality%s: %d\n", estTitle, totalSeries.Count())
	fmt.Printf("  Time Range: %s - %s\n",
		time.Unix(0, minTime).UTC().Format(time.RFC3339Nano),
		time.Unix(0, maxTime).UTC().Format(time.RFC3339Nano),
	)
	fmt.Printf("  Duration: %s \n", time.Unix(0, maxTime).Sub(time.Unix(0, minTime)))
	println()

	fmt.Printf("Statistics\n")
	fmt.Printf("  Organizations (%d):\n", len(orgCardinalities))
	for _, org := range sortKeys(orgCardinalities) {
		cardinality := orgCardinalities[org].Count()
		summary.Organizations[org] = cardinality
		fmt.Printf("     - %s: %d%s (%d%%)\n", org, cardinality, estTitle, int(float64(cardinality)/float64(totalSeries.Count())*100))
	}
	fmt.Printf("  Total%s: %d\n", estTitle, totalSeries.Count())

	fmt.Printf(" \n Buckets (%d):\n", len(bucketCardinalities))
	for _, bucket := range sortKeys(bucketCardinalities) {
		cardinality := bucketCardinalities[bucket].Count()
		summary.Buckets[bucket] = cardinality
		fmt.Printf("     - %s: %d%s (%d%%)\n", bucket, cardinality, estTitle, int(float64(cardinality)/float64(totalSeries.Count())*100))
	}
	fmt.Printf("  Total%s: %d\n", estTitle, totalSeries.Count())

	if r.Detailed {
		fmt.Printf("\n  Series By Measurements (%d):\n", len(mCardinalities))
		for _, mname := range sortKeys(mCardinalities) {
			cardinality := mCardinalities[mname].Count()
			summary.Measurements[mname] = cardinality
			fmt.Printf("    - %v: %d%s (%d%%)\n", mname, cardinality, estTitle, int((float64(cardinality)/float64(totalSeries.Count()))*100))
		}

		fmt.Printf("\n  Fields By Measurements (%d):\n", len(fCardinalities))
		for _, mname := range sortKeys(fCardinalities) {
			cardinality := fCardinalities[mname].Count()
			summary.FieldKeys[mname] = cardinality
			fmt.Printf("    - %v: %d%s\n", mname, cardinality, estTitle)
		}

		fmt.Printf("\n  Tag Values By Tag Keys (%d):\n", len(tCardinalities))
		for _, tkey := range sortKeys(tCardinalities) {
			cardinality := tCardinalities[tkey].Count()
			summary.TagKeys[tkey] = cardinality
			fmt.Printf("    - %v: %d%s\n", tkey, cardinality, estTitle)
		}
	}

	fmt.Printf("\nCompleted in %s\n", time.Since(start))
	return summary, nil
}
1104757
func (c *CmdSimpleFSPs) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ops, err := cli.SimpleFSGetOps(context.TODO())

	c.output(ops)

	return err
}
465667
func (cmd *PagesCommand) Run(args ...string) error {
	// Parse flags.
	fs := flag.NewFlagSet("", flag.ContinueOnError)
	help := fs.Bool("h", false, "")
	if err := fs.Parse(args); err != nil {
		return err
	} else if *help {
		fmt.Fprintln(cmd.Stderr, cmd.Usage())
		return ErrUsage
	}

	// Require database path.
	path := fs.Arg(0)
	if path == "" {
		return ErrPathRequired
	} else if _, err := os.Stat(path); os.IsNotExist(err) {
		return ErrFileNotFound
	}

	// Open database.
	db, err := bolt.Open(path, 0666, nil)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()

	// Write header.
	fmt.Fprintln(cmd.Stdout, "ID       TYPE       ITEMS  OVRFLW")
	fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======")

	return db.Update(func(tx *bolt.Tx) error {
		var id int
		for {
			p, err := tx.Page(id)
			if err != nil {
				return &PageError{ID: id, Err: err}
			} else if p == nil {
				break
			}

			// Only display count and overflow if this is a non-free page.
			var count, overflow string
			if p.Type != "free" {
				count = strconv.Itoa(p.Count)
				if p.OverflowCount > 0 {
					overflow = strconv.Itoa(p.OverflowCount)
				}
			}

			// Print table row.
			fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow)

			// Move to the next non-overflow page.
			id += 1
			if p.Type != "free" {
				id += p.OverflowCount
			}
		}
		return nil
	})
}
1115408
func Run(command string, args ...string) error {
	cmd := exec.Command(command, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return RunCommand(cmd, false)
}
906783
func (cmd *CheckCommand) Run(args ...string) error {
	// Parse flags.
	fs := flag.NewFlagSet("", flag.ContinueOnError)
	help := fs.Bool("h", false, "")
	if err := fs.Parse(args); err != nil {
		return err
	} else if *help {
		fmt.Fprintln(cmd.Stderr, cmd.Usage())
		return ErrUsage
	}

	// Require database path.
	path := fs.Arg(0)
	if path == "" {
		return ErrPathRequired
	} else if _, err := os.Stat(path); os.IsNotExist(err) {
		return ErrFileNotFound
	}

	// Open database.
	db, err := bolt.Open(path, 0666, nil)
	if err != nil {
		return err
	}
	defer db.Close()

	// Perform consistency check.
	return db.View(func(tx *bolt.Tx) error {
		var count int
		ch := tx.Check()
	loop:
		for {
			select {
			case err, ok := <-ch:
				if !ok {
					break loop
				}
				fmt.Fprintln(cmd.Stdout, err)
				count++
			}
		}

		// Print summary of errors.
		if count > 0 {
			fmt.Fprintf(cmd.Stdout, "%d errors found\n", count)
			return ErrCorrupt
		}

		// Notify user that database is valid.
		fmt.Fprintln(cmd.Stdout, "OK")
		return nil
	})
}
802638
func (e *CopyFile) Run(c *fi.Context) error {
	return fi.DefaultDeltaRunMethod(e, c)
}
82798
func run(stdout, stderr io.Writer, cmd string, args ...string) error {
	c := exec.Command(cmd, args...)
	c.Stdin = os.Stdin
	c.Stdout = stdout
	c.Stderr = stderr
	return c.Run()
}
901558
func (c *CmdSimpleFSKill) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	err = cli.SimpleFSClose(context.TODO(), c.opid)

	return err
}
1329161
func (cmd *Command) Run(args ...string) error {
	fs := flag.NewFlagSet("buildtsi", flag.ExitOnError)
	dataDir := fs.String("datadir", "", "data directory")
	walDir := fs.String("waldir", "", "WAL directory")
	fs.IntVar(&cmd.concurrency, "concurrency", runtime.GOMAXPROCS(0), "Number of workers to dedicate to shard index building. Defaults to GOMAXPROCS")
	fs.StringVar(&cmd.databaseFilter, "database", "", "optional: database name")
	fs.StringVar(&cmd.retentionFilter, "retention", "", "optional: retention policy")
	fs.StringVar(&cmd.shardFilter, "shard", "", "optional: shard id")
	fs.Int64Var(&cmd.maxLogFileSize, "max-log-file-size", tsi1.DefaultMaxIndexLogFileSize, "optional: maximum log file size")
	fs.Uint64Var(&cmd.maxCacheSize, "max-cache-size", tsm1.DefaultCacheMaxMemorySize, "optional: maximum cache size")
	fs.IntVar(&cmd.batchSize, "batch-size", defaultBatchSize, "optional: set the size of the batches we write to the index. Setting this can have adverse affects on performance and heap requirements")
	fs.BoolVar(&cmd.Verbose, "v", false, "verbose")
	fs.SetOutput(cmd.Stdout)
	if err := fs.Parse(args); err != nil {
		return err
	} else if fs.NArg() > 0 || *dataDir == "" || *walDir == "" {
		fs.Usage()
		return nil
	}
	cmd.Logger = logger.New(cmd.Stderr)

	return cmd.run(*dataDir, *walDir)
}
643613
func (f *CLI) Run() bool {
	err := f.validate()
	if err != nil {
		os.Stderr.WriteString(err.Error() + "\n")
		os.Exit(1)
	}

	switch {
	case f.install:
		f.prompt()
		err = install.Install(f.Name)
	case f.uninstall:
		f.prompt()
		err = install.Uninstall(f.Name)
	default:
		// non of the action flags matched,
		// returning false should make the real program execute
		return false
	}

	if err != nil {
		fmt.Printf("%s failed! %s\n", f.action(), err)
		os.Exit(3)
	}
	fmt.Println("Done!")
	return true
}
1085065
func (c *dumpCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return err
	}
	defer client.Close()

	_, modelDetails, err := c.ModelCommandBase.ModelDetails()
	if err != nil {
		return errors.Annotate(err, "getting model details")
	}

	modelTag := names.NewModelTag(modelDetails.ModelUUID)
	results, err := client.DumpModel(modelTag, c.simplified)
	if err != nil {
		return err
	}

	return c.out.Write(ctx, results)
}
1007132
func Run(t *testing.T, text string, f func(*testing.T, G, S), opts ...Option) bool {
	t.Helper()
	cfg := options(opts).apply()
	n := &node{
		text:  []string{text},
		seed:  defaultZero64(cfg.seed, time.Now().Unix()),
		order: cfg.order.or(orderSequential),
		scope: cfg.scope.or(scopeLocal),
		nest:  cfg.nest.or(nestOff),
		pend:  cfg.pend,
		focus: cfg.focus,
	}
	report := cfg.report
	plan := n.parse(f)

	var specs chan Spec
	if report != nil {
		report.Start(t, plan)
		specs = make(chan Spec, plan.Total)
		done := make(chan struct{})
		defer func() {
			close(specs)
			<-done
		}()
		go func() {
			report.Specs(t, specs)
			close(done)
		}()
	}

	return n.run(t, func(t *testing.T, n node) {
		t.Helper()
		buffer := &bytes.Buffer{}
		defer func() {
			if specs == nil {
				return
			}
			specs <- Spec{
				Text:     n.text,
				Failed:   t.Failed(),
				Skipped:  t.Skipped(),
				Focused:  n.focus,
				Parallel: n.order == orderParallel,
				Out:      buffer,
			}
		}()
		switch {
		case n.pend, plan.HasFocus && !n.focus:
			t.SkipNow()
		case n.order == orderParallel:
			t.Parallel()
		}
		var (
			spec, group   func()
			before, after []func()
			afterIdx      int
		)
		group = func() {}

		f(t, func(_ string, f func(), _ ...Option) {
			switch {
			case len(n.loc) == 1, n.loc[0] > 0:
				n.loc[0]--
			case n.loc[0] == 0:
				group = func() {
					n.loc = n.loc[1:]
					afterIdx = 0
					group = func() {}
					f()
					group()
				}
				n.loc[0]--
			}
		}, func(_ string, f func(), opts ...Option) {
			cfg := options(opts).apply()
			switch {
			case cfg.out != nil:
				cfg.out(buffer)
			case cfg.before:
				before = append(before, f)
			case cfg.after:
				after = insert(after, f, afterIdx)
				afterIdx++
			case spec != nil:
			case len(n.loc) > 1, n.loc[0] > 0:
				n.loc[0]--
			default:
				spec = f
			}
		})
		group()

		if spec == nil {
			t.Fatal("Failed to locate spec.")
		}
		run(t, before...)
		defer run(t, after...)
		run(t, spec)
	})
}
236765
func (c *connectionBenchmark) run() *result {
	var err error
	if c.requestRate == 0 {
		c.elapsed, err = c.runFullThrottle()
	} else {
		c.elapsed, err = c.runRateLimited()
	}
	return &result{summary: c.summarize(), err: err}
}
1266554
func run(dir, command string, args ...string) (string, error) {
	logger.Debugf("(%s) %s %v", dir, command, args)

	cmd := exec.Command(command, args...)
	if dir != "" {
		cmd.Dir = dir
	}

	out, err := cmd.CombinedOutput()
	output := string(out)

	logger.Debugf("output: %v", output)
	return output, err
}
1130710
func (c *CmdSimpleFSStat) Run() (err error) {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ui := c.G().UI.GetTerminalUI()
	ui.Printf("%v\n", c.path)
	ctx := context.TODO()

	if c.spanType != nil {
		opid, err := cli.SimpleFSMakeOpid(ctx)
		if err != nil {
			return err
		}
		defer func() {
			closeErr := cli.SimpleFSClose(ctx, opid)
			if err == nil {
				err = closeErr
			}
		}()
		err = cli.SimpleFSGetRevisions(ctx, keybase1.SimpleFSGetRevisionsArg{
			OpID:     opid,
			Path:     c.path,
			SpanType: *c.spanType,
		})
		if err != nil {
			return err
		}
		err = cli.SimpleFSWait(ctx, opid)
		if err != nil {
			return err
		}
		res, err := cli.SimpleFSReadRevisions(ctx, opid)
		if err != nil {
			return err
		}

		for _, r := range res.Revisions {
			e := r.Entry
			ui.Printf("%d)\t%s\t%s\t%d\t%s\t%s\t%s\n",
				r.Revision, keybase1.FormatTime(e.Time),
				keybase1.DirentTypeRevMap[e.DirentType],
				e.Size, e.Name, e.LastWriterUnverified.Username,
				prefetchStatusString(e))
		}
	} else {
		e, err := cli.SimpleFSStat(ctx, keybase1.SimpleFSStatArg{Path: c.path})
		if err != nil {
			return err
		}

		ui.Printf("%s\t%s\t%d\t%s\t%s\t%s\n",
			keybase1.FormatTime(e.Time),
			keybase1.DirentTypeRevMap[e.DirentType],
			e.Size, e.Name, e.LastWriterUnverified.Username,
			prefetchStatusString(e))
	}

	return nil
}
918699
func (s *Service) Run(c context.Context, f func(context.Context) error) {
	// Log to Stdout using JSON log lines.
	c = teelogger.Use(c, gkelogger.GetFactory(os.Stdout))

	// If a service name isn't specified, default to the base of the current
	// executable.
	if s.Name == "" {
		s.Name = filepath.Base(os.Args[0])
	}
	s.useDatastoreConfig = true // If available, use datastore config.

	rc := 0
	if err := s.runImpl(c, f); err != nil {
		log.WithError(err).Errorf(c, "Application exiting with error.")
		rc = 1
	}
	os.Exit(rc)
}
514832
func Run(ctx context.Context, buildOpts *provision.BuildOptions, containerOpts *provision.ContainerOptions) (stdout string, stderr string, err error) {
	var client *docker.Client
	var container *docker.Container
	var machine *iaas.Machine
	done := make(chan struct{})
	go func(ctx context.Context, done chan struct{}) {
		client, err = provision.FnClient("", "")
		if err != nil {
			done <- struct{}{}
			return
		}

		if buildOpts.Iaas != nil {
			client, machine, err = ProvideMachine(ctx, buildOpts.Iaas)
			if err != nil {
				done <- struct{}{}
				return
			}
		}

		container, err = PrepareContainer(ctx, client, buildOpts, containerOpts)
		if err != nil {
			done <- struct{}{}
			return
		}

		var buffout *bytes.Buffer
		var bufferr *bytes.Buffer

		buffout, bufferr, err = provision.FnRun(client, container.ID, buildOpts.StdIN)
		stdout = buffout.String()
		stderr = bufferr.String()
		done <- struct{}{}
	}(ctx, done)
	select {
	case <-ctx.Done():
		log.Errorf("trying to destroy container %v\n", ctx.Err())
	case <-done:
		log.Debugln("trying to destroy container process done")
	}
	if machine != nil {
		log.Debugf("trying to delete machine ID:%v\n", machine.ID)
		deleteErr := buildOpts.Iaas.DeleteMachine()
		if deleteErr != nil {
			err = fmt.Errorf("error trying to delete machine %v", deleteErr)
		}
		return
	}
	if client != nil && container != nil {
		for killAttempt := 0; killAttempt < 3; killAttempt++ {
			if killAttempt > 0 {
				<-time.After(time.Duration(3) * time.Second)
			}
			_, err = provision.FnFindContainerByID(client, container.ID)
			if err != nil {
				if err == provision.ErrContainerNotFound {
					err = nil
				}
				return
			}
			if container.State.Running {
				log.Debugf("destroying container ID:%v, attempt:%v\n", container.ID, killAttempt+1)
				err = client.KillContainer(docker.KillContainerOptions{ID: container.ID})
				if err != nil {
					log.Errorf("error trying to kill container %v, %v, attempt:%v\n", container.ID, err.Error(), killAttempt+1)
				}
			}
			err = client.RemoveContainer(docker.RemoveContainerOptions{
				ID:    container.ID,
				Force: true,
			})
			if err != nil {
				log.Errorf("error trying to remove container %v, %v, attempt:%v\n", container.ID, err.Error(), killAttempt+1)
			}
		}
		err = fmt.Errorf("unable to kill container %v", container.ID)
	}
	return
}