// trackPanic monitors the given reader for a panic. If a panic is detected,
// it is outputted on the result channel. This will close the channel once
// it is complete.
429025
func trackPanic(r io.Reader, w io.Writer, dur time.Duration, result chan<- string) {
	defer close(result)

	var panicTimer <-chan time.Time
	panicBuf := new(bytes.Buffer)
	panicHeaders := [][]byte{
		[]byte("panic:"),
		[]byte("fatal error: fault"),
	}
	panicType := -1

	tempBuf := make([]byte, 2048)
	for {
		var buf []byte
		var n int

		if panicTimer == nil && panicBuf.Len() > 0 {
			// We're not tracking a panic but the buffer length is
			// greater than 0. We need to clear out that buffer, but
			// look for another panic along the way.

			// First, remove the previous panic header so we don't loop
			w.Write(panicBuf.Next(len(panicHeaders[panicType])))

			// Next, assume that this is our new buffer to inspect
			n = panicBuf.Len()
			buf = make([]byte, n)
			copy(buf, panicBuf.Bytes())
			panicBuf.Reset()
		} else {
			var err error
			buf = tempBuf
			n, err = r.Read(buf)
			if n <= 0 && err == io.EOF {
				if panicBuf.Len() > 0 {
					// We were tracking a panic, assume it was a panic
					// and return that as the result.
					result <- panicBuf.String()
				}

				return
			}
		}

		if panicTimer != nil {
			// We're tracking what we think is a panic right now.
			// If the timer ended, then it is not a panic.
			isPanic := true
			select {
			case <-panicTimer:
				isPanic = false
			default:
			}

			// No matter what, buffer the text some more.
			panicBuf.Write(buf[0:n])

			if !isPanic {
				// It isn't a panic, stop tracking. Clean-up will happen
				// on the next iteration.
				panicTimer = nil
			}

			continue
		}

		panicType = -1
		flushIdx := n
		for i, header := range panicHeaders {
			idx := bytes.Index(buf[0:n], header)
			if idx >= 0 {
				panicType = i
				flushIdx = idx
				break
			}
		}

		// Flush to stderr what isn't a panic
		w.Write(buf[0:flushIdx])

		if panicType == -1 {
			// Not a panic so just continue along
			continue
		}

		// We have a panic header. Write we assume is a panic os far.
		panicBuf.Write(buf[flushIdx:n])
		panicTimer = time.After(dur)
	}
}
519471
func TrackMetrics(successes, failures *expvar.Int, timing *expvar.Float) MessageHandlerDecorator {
	ema := movingaverage.New(5 * time.Second)

	return func(fn sqsconsumer.MessageHandlerFunc) sqsconsumer.MessageHandlerFunc {
		return func(ctx context.Context, msg string) error {
			start := time.Now()
			defer func() {
				v := ema.Update(time.Since(start).Seconds() * 1000)
				timing.Set(v)
			}()

			err := fn(ctx, msg)
			if err != nil {
				failures.Add(1)
			} else {
				successes.Add(1)
			}
			return err
		}
	}
}
1048159
func (l *DefaultLogger) LogPanic(_ context.Context, value interface{}) {
	const size = 64 << 10
	buf := make([]byte, size)
	buf = buf[:runtime.Stack(buf, false)]
	log.Printf("graphql: panic occurred: %v\n%s", value, buf)
}
502028
func parseIOStatWatcher(r io.Reader, c chan<- map[string]DeviceUtilizationReport, qCh <-chan interface{}) {
	// Custom bufio.Split() function to split tokens by 2 new lines
	atTwoNewLines := func(data []byte, atEOF bool) (int, []byte, error) {
		advance := 0
		var token []byte
		var prev byte

		for _, b := range data {
			// consume the newline by advancing passed it
			if string(b) == "\n" && string(prev) == "\n" {
				advance++
				return advance, token, nil
			}
			token = append(token, b)
			advance++
			prev = b
		}
		return 0, nil, nil
	}

	scanner := bufio.NewScanner(r)
	scanner.Split(atTwoNewLines)
	for scanned := true; scanned; {
		scanc := make(chan struct{})
		go func() {
			defer close(scanc)
			scanned = scanner.Scan()
		}()

		select {
		case <-qCh:
			return
		case <-scanc:
			if scanned {
				out := scanner.Text()
				parseReader := strings.NewReader(out)
				report, err := ParseIOStat(parseReader)
				if err != nil {
					plog.WithError(err).Error("Failed to parse iostat output, exiting")
					return
				} else if len(report) == 0 {
					plog.Warn("Got an empty report from iostat")
					continue
				}
				select {
				case <-qCh:
					return
				case c <- report:
				}
			}
		}
	}
	plog.Warn("parseIOStatWatcher exiting")
	if err := scanner.Err(); err != nil {
		plog.WithError(err).Error("Error reading iostat")
	}
}
417246
func (val *Validation) CheckAndPanic() *Validation {
	if val == nil || len(val.Errors) <= 0 {
		return val
	}

	panic(val.constructErrorMessage())
}
21981
func TrackConsumptionRate(log Logger, period time.Duration, format string) MessageHandlerDecorator {
	var count int64

	go func() {
		for {
			<-time.After(period)
			c := atomic.SwapInt64(&count, 0)
			log.Printf(format, c)
		}
	}()

	return func(fn sqsconsumer.MessageHandlerFunc) sqsconsumer.MessageHandlerFunc {
		return func(ctx context.Context, msg string) error {
			atomic.AddInt64(&count, 1)

			return fn(ctx, msg)
		}
	}
}
946662
func HandlePanic(component string, err *error) {
	if x := recover(); x != nil {
		// gRPC 0.13 chokes when you return a streaming error that contains newlines.
		*err = fmt.Errorf("uncaught %v panic: %v, %s", component, x,
			strings.Replace(string(tb.Stack(4)), "\n", ";", -1))
	}
}
1198582
func (r *runner) trackPeekN(i int) int {
	return r.runtrack[r.runtrackpos-i-1]
}
352904
func parsePanicFrame(name string, line string, createdBy bool) (*StackFrame, error) {
	idx := strings.LastIndex(name, "(")
	if idx == -1 && !createdBy {
		return nil, Errorf("bugsnag.panicParser: Invalid line (no call): %s", name)
	}
	if idx != -1 {
		name = name[:idx]
	}
	pkg := ""

	if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 {
		pkg += name[:lastslash] + "/"
		name = name[lastslash+1:]
	}
	if period := strings.Index(name, "."); period >= 0 {
		pkg += name[:period]
		name = name[period+1:]
	}

	name = strings.Replace(name, "·", ".", -1)

	if !strings.HasPrefix(line, "\t") {
		return nil, Errorf("bugsnag.panicParser: Invalid line (no tab): %s", line)
	}

	idx = strings.LastIndex(line, ":")
	if idx == -1 {
		return nil, Errorf("bugsnag.panicParser: Invalid line (no line number): %s", line)
	}
	file := line[1:idx]

	number := line[idx+1:]
	if idx = strings.Index(number, " +"); idx > -1 {
		number = number[:idx]
	}

	lno, err := strconv.ParseInt(number, 10, 32)
	if err != nil {
		return nil, Errorf("bugsnag.panicParser: Invalid line (bad line number): %s", line)
	}

	return &StackFrame{
		File:       file,
		LineNumber: int(lno),
		Package:    pkg,
		Name:       name,
	}, nil
}
1306290
func parseOrPanic(simplify bool, pattern string) *syntax.Regexp {
	regexp, err := syntax.Parse(pattern, 0)
	if err != nil {
		panic(err)
	}
	if simplify {
		regexp = regexp.Simplify()
	}
	return regexp
}
1059275
func (bld *builder) maybePanic() {
	if len(bld.results) == 0 {
		return
	}
	res := bld.results[len(bld.results)-1]
	if res == nil {
		return
	}
	for _, f := range res.List {
		for _, id := range f.Names {
			bld.use(id)
		}
	}
}
169191
func NewPanicCheck(healthcheck *threading.SharedBoolean, logger logger.Logger) negroni.Handler {
	return &panicCheck{
		heartbeatOK: healthcheck,
		logger:      logger,
	}
}
1313012
func DetectPanic(t *testing.T, templateName string) {
	if n := recover(); n != nil {
		t.Errorf("Test for %s failed!", templateName)
	}
}
1044025
func ParsePanic(text string) (*Error, error) {
	lines := strings.Split(text, "\n")

	state := "start"

	var message string
	var stack []StackFrame

	for i := 0; i < len(lines); i++ {
		line := lines[i]

		if state == "start" {
			if strings.HasPrefix(line, "panic: ") {
				message = strings.TrimPrefix(line, "panic: ")
				state = "seek"
			} else {
				return nil, Errorf("bugsnag.panicParser: Invalid line (no prefix): %s", line)
			}

		} else if state == "seek" {
			if strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "[running]:") {
				state = "parsing"
			}

		} else if state == "parsing" {
			if line == "" {
				state = "done"
				break
			}
			createdBy := false
			if strings.HasPrefix(line, "created by ") {
				line = strings.TrimPrefix(line, "created by ")
				createdBy = true
			}

			i++

			if i >= len(lines) {
				return nil, Errorf("bugsnag.panicParser: Invalid line (unpaired): %s", line)
			}

			frame, err := parsePanicFrame(line, lines[i], createdBy)
			if err != nil {
				return nil, err
			}

			stack = append(stack, *frame)
			if createdBy {
				state = "done"
				break
			}
		}
	}

	if state == "done" || state == "parsing" {
		return &Error{Err: uncaughtPanic{message}, frames: stack}, nil
	}
	return nil, Errorf("could not parse panic: %v", text)
}
327128
func panicWithTraceback(L *LState) {
	err := newApiError(ApiErrorRun, L.Get(-1))
	err.StackTrace = L.stackTrace(0)
	panic(err)
}
571524
func (plugin *ExamplePlugin) showPanicLog() {
	defer func() {
		if err := recover(); err != nil {
			plugin.Log.Info("Recovered from panic")
		}
	}()
	plugin.Log.Panic("Panic log: calls panic() after log, will be recovered") //calls panic() after logging
}
300950
func SetOrPanic(s Setter) func(v string) {
	return func(v string) {
		err := s.Set(v)
		if err != nil {
			panic(err)
		}
	}
}