//--------------------------------------------------------
// replay messages interactively or all at once
// replay the wal file
551559
func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) {
	consensusState := newConsensusStateForReplay(config, csConfig)

	if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil {
		cmn.Exit(fmt.Sprintf("Error during consensus replay: %v", err))
	}
}
52521
func (m *Message) Copy() *Message {
	// Create a new message
	newMessage := &Message{}

	// Copy stuff from the old message
	*newMessage = *m

	// Copy any IRcv3 tags
	newMessage.Tags = m.Tags.Copy()

	// Copy the Prefix
	newMessage.Prefix = m.Prefix.Copy()

	// Copy the Params slice
	newMessage.Params = append(make([]string, 0, len(m.Params)), m.Params...)

	// Similar to parsing, if Params is empty, set it to nil
	if len(newMessage.Params) == 0 {
		newMessage.Params = nil
	}

	return newMessage
}
623011
func (m *message) Copy(x Message) error {
	var mc MessageCodec
	bytes, err := mc.Encode(x, nil)
	if err == nil {
		err = mc.Decode(m, bytes)
	}
	return err
}
84853
func main() {
	logger.Level = golog.INFO

	app.Version("1.0.2")

	// install dependencies
	outputCmd("go", []string{"get", "github.com/ivpusic/rerun"})

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case run.FullCommand():
		handleRunCommand()
	case newCmd.FullCommand():
		handleNewCommand()
	default:
		app.Usage(os.Stdout)
	}
}
148721
func (vp *vplayer) play(ctx context.Context) error {
	if !vp.stopPos.IsZero() && vp.startPos.AtLeast(vp.stopPos) {
		if vp.saveStop {
			return vp.vr.setState(binlogplayer.BlpStopped, fmt.Sprintf("Stop position %v already reached: %v", vp.startPos, vp.stopPos))
		}
		return nil
	}

	plan, err := buildReplicatorPlan(vp.vr.source.Filter, vp.vr.tableKeys, vp.copyState)
	if err != nil {
		return err
	}
	vp.replicatorPlan = plan

	if err := vp.fetchAndApply(ctx); err != nil {
		msg := err.Error()
		vp.vr.stats.History.Add(&binlogplayer.StatsHistoryRecord{
			Time:    time.Now(),
			Message: msg,
		})
		if err := vp.vr.setMessage(msg); err != nil {
			log.Errorf("Failed to set error state: %v", err)
		}
		return err
	}
	return nil
}
169951
func (l *WAL) Open(ctx context.Context) error {
	l.mu.Lock()
	defer l.mu.Unlock()

	if !l.enabled {
		return nil
	}

	span, _ := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	span.LogKV("segment_size", l.SegmentSize,
		"path", l.path)

	// Initialise metrics for trackers.
	mmu.Lock()
	if wms == nil {
		wms = newWALMetrics(l.defaultMetricLabels)
	}
	mmu.Unlock()

	// Set the shared metrics for the tracker
	l.tracker = newWALTracker(wms, l.defaultMetricLabels)

	if err := os.MkdirAll(l.path, 0777); err != nil {
		return err
	}

	segments, err := SegmentFileNames(l.path)
	if err != nil {
		return err
	}
	l.tracker.SetSegments(uint64(len(segments)))

	if len(segments) > 0 {
		lastSegment := segments[len(segments)-1]
		id, err := idFromFileName(lastSegment)
		if err != nil {
			return err
		}

		l.currentSegmentID = id
		stat, err := os.Stat(lastSegment)
		if err != nil {
			return err
		}

		if stat.Size() == 0 {
			os.Remove(lastSegment)
			segments = segments[:len(segments)-1]
			l.tracker.DecSegments()
		} else {
			fd, err := os.OpenFile(lastSegment, os.O_RDWR, 0666)
			if err != nil {
				return err
			}
			if _, err := fd.Seek(0, io.SeekEnd); err != nil {
				return err
			}
			l.currentSegmentWriter = NewWALSegmentWriter(fd)

			// Reset the current segment size stat
			l.tracker.SetCurrentSegmentSize(uint64(stat.Size()))
		}
	}

	var totalOldDiskSize int64
	for _, seg := range segments {
		stat, err := os.Stat(seg)
		if err != nil {
			return err
		}

		if stat.Size() > 0 {
			totalOldDiskSize += stat.Size()
			if stat.ModTime().After(l.lastWriteTime) {
				l.lastWriteTime = stat.ModTime().UTC()
			}
		}
	}
	l.tracker.SetOldSegmentSize(uint64(totalOldDiskSize))

	l.closing = make(chan struct{})

	return nil
}
1038497
func (wal *baseWAL) WriteSync(msg WALMessage) {
	if wal == nil {
		return
	}

	wal.Write(msg)
	if err := wal.FlushAndSync(); err != nil {
		panic(fmt.Sprintf("Error flushing consensus wal buf to file. Error: %v \n", err))
	}
}
355046
func (r *replayer) Put(key, value []byte) {
	// If the replay already failed, stop executing ops
	if r.failure != nil {
		return
	}
	r.failure = r.writer.Put(key, value)
}
1374688
func (l *WAL) Close() error {
	l.mu.Lock()
	defer l.mu.Unlock()

	l.once.Do(func() {
		// Close, but don't set to nil so future goroutines can still be signaled
		l.traceLogger.Info("Closing WAL file", zap.String("path", l.path))
		close(l.closing)

		if l.currentSegmentWriter != nil {
			l.sync()
			l.currentSegmentWriter.close()
			l.currentSegmentWriter = nil
		}
	})

	return nil
}
451580
func (b *batch) Replay(w ethdb.Writer) error {
	return b.b.Replay(&replayer{writer: w})
}
413920
func ReplayOplog(r io.Reader, controller ratecontroller.Controller, alwaysUpsert bool, host string) error {
	done := make(chan struct{})
	defer close(done)

	session, err := mgo.Dial(host)
	if err != nil {
		return err
	}
	defer session.Close()

	log.Println("Parsing BSON...")
	ops, parseErrors := parseBSON(done, r)
	timedOps := controlRate(done, ops, controller)
	batchedOps := batchOps(done, timedOps)

	applyOps := getApplyOpsFunc(session, alwaysUpsert)
	log.Println("Begin replaying...")

	if err := oplogReplay(batchedOps, applyOps); err != nil {
		return err
	}
	if err := <-parseErrors; err != nil {
		return err
	}
	return nil
}
177718
func (w *WAL) Log(recs ...[]byte) error {
	w.mtx.Lock()
	defer w.mtx.Unlock()
	// Callers could just implement their own list record format but adding
	// a bit of extra logic here frees them from that overhead.
	for i, r := range recs {
		if err := w.log(r, i == len(recs)-1); err != nil {
			return err
		}
	}
	return nil
}
176673
func (pb *Pushbullet) PostPushesFile(f *requests.File) (*responses.File, error) {
	res, err := pb.postPushes(f)
	if err != nil {
		return nil, err
	}

	var fileRes *responses.File
	decoder := json.NewDecoder(res.Body)
	if err := decoder.Decode(&fileRes); err != nil {
		return nil, err
	}

	return fileRes, err
}
627746
func (pb *playback) replayConsoleLoop() int {
	for {
		fmt.Printf("> ")
		bufReader := bufio.NewReader(os.Stdin)
		line, more, err := bufReader.ReadLine()
		if more {
			cmn.Exit("input is too long")
		} else if err != nil {
			cmn.Exit(err.Error())
		}

		tokens := strings.Split(string(line), " ")
		if len(tokens) == 0 {
			continue
		}

		switch tokens[0] {
		case "next":
			// "next" -> replay next message
			// "next N" -> replay next N messages

			if len(tokens) == 1 {
				return 0
			}
			i, err := strconv.Atoi(tokens[1])
			if err != nil {
				fmt.Println("next takes an integer argument")
			} else {
				return i
			}

		case "back":
			// "back" -> go back one message
			// "back N" -> go back N messages

			// NOTE: "back" is not supported in the state machine design,
			// so we restart and replay up to

			ctx := context.Background()
			// ensure all new step events are regenerated as expected

			newStepSub, err := pb.cs.eventBus.Subscribe(ctx, subscriber, types.EventQueryNewRoundStep)
			if err != nil {
				cmn.Exit(fmt.Sprintf("failed to subscribe %s to %v", subscriber, types.EventQueryNewRoundStep))
			}
			defer pb.cs.eventBus.Unsubscribe(ctx, subscriber, types.EventQueryNewRoundStep)

			if len(tokens) == 1 {
				if err := pb.replayReset(1, newStepSub); err != nil {
					pb.cs.Logger.Error("Replay reset error", "err", err)
				}
			} else {
				i, err := strconv.Atoi(tokens[1])
				if err != nil {
					fmt.Println("back takes an integer argument")
				} else if i > pb.count {
					fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
				} else {
					if err := pb.replayReset(i, newStepSub); err != nil {
						pb.cs.Logger.Error("Replay reset error", "err", err)
					}
				}
			}

		case "rs":
			// "rs" -> print entire round state
			// "rs short" -> print height/round/step
			// "rs <field>" -> print another field of the round state

			rs := pb.cs.RoundState
			if len(tokens) == 1 {
				fmt.Println(rs)
			} else {
				switch tokens[1] {
				case "short":
					fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step)
				case "validators":
					fmt.Println(rs.Validators)
				case "proposal":
					fmt.Println(rs.Proposal)
				case "proposal_block":
					fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort())
				case "locked_round":
					fmt.Println(rs.LockedRound)
				case "locked_block":
					fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort())
				case "votes":
					fmt.Println(rs.Votes.StringIndented("  "))

				default:
					fmt.Println("Unknown option", tokens[1])
				}
			}
		case "n":
			fmt.Println(pb.count)
		}
	}
}
1272255
func NewReplayXHRArgs(requestID RequestID) *ReplayXHRArgs {
	args := new(ReplayXHRArgs)
	args.RequestID = requestID
	return args
}
856155
func repeat(a *Automaton) *Automaton {
	if isEmpty(a) {
		return a
	}

	b := newAutomatonBuilder()
	b.createState()
	b.setAccept(0, true)
	b.copy(a)

	t := newTransition()
	count := a.initTransition(0, t)
	for i := 0; i < count; i++ {
		a.nextTransition(t)
		b.addTransitionRange(0, t.dest+1, t.min, t.max)
	}

	numStates := a.numStates()
	for s := 0; s < numStates; s++ {
		if a.IsAccept(s) {
			count = a.initTransition(0, t)
			for i := 0; i < count; i++ {
				a.nextTransition(t)
				b.addTransitionRange(s+1, t.dest+1, t.min, t.max)
			}
		}
	}

	return b.finish()
}
1258543
func (mt *messageTracer) Dump(comment string) {
	if mt.msg.streamID == LogInternalStreamID || mt.msg.streamID == TraceInternalStreamID {
		return
	}

	var err error
	msgDump := mt.newMessageDump(mt.msg, comment)

	if StreamRegistry.IsStreamRegistered(TraceInternalStreamID) {
		err = mt.routeToTraceStream(msgDump)

	} else {
		err = mt.printMessageTrace(msgDump)
	}

	if err != nil {
		logrus.Error(err)
	}
}