func (s *Store) WaitForFSMIndex(idx uint64, timeout time.Duration) (uint64, error) {
	tck := time.NewTicker(appliedWaitDelay)
	defer tck.Stop()
	tmr := time.NewTimer(timeout)
	defer tmr.Stop()
	var fsmIdx uint64
	for {
		select {
		case <-tck.C:
			s.fsmIndexMu.RLock()
			fsmIdx = s.fsmIndex
			s.fsmIndexMu.RUnlock()
			if fsmIdx >= idx {
				return fsmIdx, nil
			}
		case <-tmr.C:
			return 0, fmt.Errorf("timeout expired")
		}
	}
}
WaitForFSMIndex blocks until a given log index has been applied to the
state machine or the timeout expires.
package store
import (
	"bytes"
	"compress/gzip"
	"encoding/binary"
	"errors"
	"expvar"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"sync"
	"time"
	"unsafe"
	"github.com/hashicorp/raft"
	"github.com/rqlite/rqlite/command"
	sql "github.com/rqlite/rqlite/db"
	rlog "github.com/rqlite/rqlite/log"
)
var (
	ErrNotLeader = errors.New("not leader")
	ErrStaleRead = errors.New("stale read")
	ErrOpenTimeout = errors.New("timeout waiting for initial logs application")
	ErrInvalidBackupFormat = errors.New("invalid backup format")
)
const (
	raftDBPath          = "raft.db"  
	peersPath           = "raft/peers.json"
	peersInfoPath       = "raft/peers.info"
	retainSnapshotCount = 2
	applyTimeout        = 10 * time.Second
	openTimeout         = 120 * time.Second
	sqliteFile          = "db.sqlite"
	leaderWaitDelay     = 100 * time.Millisecond
	appliedWaitDelay    = 100 * time.Millisecond
	connectionPoolCount = 5
	connectionTimeout   = 10 * time.Second
	raftLogCacheSize    = 512
	trailingScale       = 1.25
)
const (
	numSnaphots              = "num_snapshots"
	numBackups               = "num_backups"
	numRestores              = "num_restores"
	numRecoveries            = "num_recoveries"
	numUncompressedCommands  = "num_uncompressed_commands"
	numCompressedCommands    = "num_compressed_commands"
	numJoins                 = "num_joins"
	numIgnoredJoins          = "num_ignored_joins"
	numRemovedBeforeJoins    = "num_removed_before_joins"
	snapshotCreateDuration   = "snapshot_create_duration"
	snapshotPersistDuration  = "snapshot_persist_duration"
	snapshotDBSerializedSize = "snapshot_db_serialized_size"
	snapshotDBOnDiskSize     = "snapshot_db_ondisk_size"
)
type BackupFormat int
const (
	BackupSQL BackupFormat = iota
	BackupBinary
)
var stats *expvar.Map
func init() {
	stats = expvar.NewMap("store")
	stats.Add(numSnaphots, 0)
	stats.Add(numBackups, 0)
	stats.Add(numRestores, 0)
	stats.Add(numRecoveries, 0)
	stats.Add(numUncompressedCommands, 0)
	stats.Add(numCompressedCommands, 0)
	stats.Add(numJoins, 0)
	stats.Add(numIgnoredJoins, 0)
	stats.Add(numRemovedBeforeJoins, 0)
	stats.Add(snapshotCreateDuration, 0)
	stats.Add(snapshotPersistDuration, 0)
	stats.Add(snapshotDBSerializedSize, 0)
	stats.Add(snapshotDBOnDiskSize, 0)
}
type ClusterState int
const (
	Leader ClusterState = iota
	Follower
	Candidate
	Shutdown
	Unknown
)
type Store struct {
	raftDir       string
	peersPath     string
	peersInfoPath string
	raft   *raft.Raft  
	ln     Listener
	raftTn *raft.NetworkTransport
	raftID string     
	dbConf *DBConfig  
	dbPath string     
	db     *sql.DB    
	queryTxMu sync.RWMutex
	dbAppliedIndexMu sync.RWMutex
	dbAppliedIndex   uint64
	fsmIndex   uint64
	fsmIndexMu sync.RWMutex
	reqMarshaller *command.RequestMarshaler  
	raftLog       raft.LogStore              
	raftStable    raft.StableStore           
	boltStore     *rlog.Log                  
	onDiskCreated        bool       
	snapsExistOnOpen     bool       
	firstIdxOnOpen       uint64     
	lastIdxOnOpen        uint64     
	lastCommandIdxOnOpen uint64     
	firstLogAppliedT     time.Time  
	appliedOnOpen        uint64     
	openT                time.Time  
	logger *log.Logger
	ShutdownOnRemove   bool
	SnapshotThreshold  uint64
	SnapshotInterval   time.Duration
	LeaderLeaseTimeout time.Duration
	HeartbeatTimeout   time.Duration
	ElectionTimeout    time.Duration
	ApplyTimeout       time.Duration
	RaftLogLevel       string
	numTrailingLogs uint64
	numNoops       int
	numSnapshotsMu sync.Mutex
	numSnapshots   int
}
func IsNewNode(raftDir string) bool {
	return !pathExists(filepath.Join(raftDir, raftDBPath))
}
type Config struct {
	DBConf *DBConfig    
	Dir    string       
	Tn     Transport    
	ID     string       
	Logger *log.Logger  
}
func New(ln Listener, c *Config) *Store {
	logger := c.Logger
	if logger == nil {
		logger = log.New(os.Stderr, "[store] ", log.LstdFlags)
	}
	dbPath := filepath.Join(c.Dir, sqliteFile)
	if c.DBConf.OnDiskPath != "" {
		dbPath = c.DBConf.OnDiskPath
	}
	return &Store{
		ln:            ln,
		raftDir:       c.Dir,
		peersPath:     filepath.Join(c.Dir, peersPath),
		peersInfoPath: filepath.Join(c.Dir, peersInfoPath),
		raftID:        c.ID,
		dbConf:        c.DBConf,
		dbPath:        dbPath,
		reqMarshaller: command.NewRequestMarshaler(),
		logger:        logger,
		ApplyTimeout:  applyTimeout,
	}
}
func (s *Store) Open(enableBootstrap bool) error {
	s.openT = time.Now()
	s.logger.Printf("opening store with node ID %s", s.raftID)
	if !s.dbConf.Memory {
		s.logger.Printf("configured for an on-disk database at %s", s.dbPath)
		parentDir := filepath.Dir(s.dbPath)
		s.logger.Printf("ensuring directory at %s exists", parentDir)
		err := os.MkdirAll(parentDir, 0755)
		if err != nil {
			return err
		}
	} else {
		s.logger.Printf("configured for an in-memory database")
	}
	s.logger.Printf("ensuring directory at %s exists", s.raftDir)
	err := os.MkdirAll(filepath.Dir(s.peersPath), 0755)
	if err != nil {
		return err
	}
	s.raftTn = raft.NewNetworkTransport(NewTransport(s.ln), connectionPoolCount, connectionTimeout, nil)
	s.numTrailingLogs = uint64(float64(s.SnapshotThreshold) * trailingScale)
	config := s.raftConfig()
	config.LocalID = raft.ServerID(s.raftID)
	snapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)
	if err != nil {
		return fmt.Errorf("file snapshot store: %s", err)
	}
	snaps, err := snapshots.List()
	if err != nil {
		return fmt.Errorf("list snapshots: %s", err)
	}
	s.logger.Printf("%d preexisting snapshots present", len(snaps))
	s.snapsExistOnOpen = len(snaps) > 0
	s.boltStore, err = rlog.NewLog(filepath.Join(s.raftDir, raftDBPath))
	if err != nil {
		return fmt.Errorf("new log store: %s", err)
	}
	s.raftStable = s.boltStore
	s.raftLog, err = raft.NewLogCache(raftLogCacheSize, s.boltStore)
	if err != nil {
		return fmt.Errorf("new cached store: %s", err)
	}
	if pathExists(s.peersPath) {
		s.logger.Printf("attempting node recovery using %s", s.peersPath)
		config, err := raft.ReadConfigJSON(s.peersPath)
		if err != nil {
			return fmt.Errorf("failed to read peers file: %s", err.Error())
		}
		if err = RecoverNode(s.raftDir, s.logger, s.raftLog, s.raftStable, snapshots, s.raftTn, config); err != nil {
			return fmt.Errorf("failed to recover node: %s", err.Error())
		}
		if err := os.Rename(s.peersPath, s.peersInfoPath); err != nil {
			return fmt.Errorf("failed to move %s after recovery: %s", s.peersPath, err.Error())
		}
		s.logger.Printf("node recovered successfully using %s", s.peersPath)
		stats.Add(numRecoveries, 1)
	}
	if err := s.setLogInfo(); err != nil {
		return fmt.Errorf("set log info: %s", err)
	}
	s.logger.Printf("first log index: %d, last log index: %d, last command log index: %d:",
		s.firstIdxOnOpen, s.lastIdxOnOpen, s.lastCommandIdxOnOpen)
	if !s.dbConf.Memory && !s.snapsExistOnOpen && s.lastCommandIdxOnOpen == 0 {
		s.db, err = s.createOnDisk(nil)
		if err != nil {
			return fmt.Errorf("failed to create on-disk database")
		}
		s.onDiskCreated = true
		s.logger.Printf("created on-disk database at open")
	} else {
		s.db, err = s.createInMemory(nil)
		if err != nil {
			return fmt.Errorf("failed to create in-memory database")
		}
		s.logger.Printf("created in-memory database at open")
	}
	ra, err := raft.NewRaft(config, s, s.raftLog, s.raftStable, snapshots, s.raftTn)
	if err != nil {
		return fmt.Errorf("new raft: %s", err)
	}
	if enableBootstrap {
		s.logger.Printf("executing new cluster bootstrap")
		configuration := raft.Configuration{
			Servers: []raft.Server{
				{
					ID:      config.LocalID,
					Address: s.raftTn.LocalAddr(),
				},
			},
		}
		ra.BootstrapCluster(configuration)
	} else {
		s.logger.Printf("no cluster bootstrap requested")
	}
	s.raft = ra
	return nil
}
func (s *Store) Close(wait bool) error {
	f := s.raft.Shutdown()
	if wait {
		if e := f.(raft.Future); e.Error() != nil {
			return e.Error()
		}
	}
	if err := s.db.Close(); err != nil {
		return err
	}
	if err := s.boltStore.Close(); err != nil {
		return err
	}
	return nil
}
func (s *Store) WaitForAppliedFSM(timeout time.Duration) (uint64, error) {
	if timeout == 0 {
		return 0, nil
	}
	return s.WaitForFSMIndex(s.raft.AppliedIndex(), timeout)
}
func (s *Store) WaitForInitialLogs(timeout time.Duration) error {
	if timeout == 0 {
		return nil
	}
	s.logger.Printf("waiting for up to %s for application of initial logs (lcIdx=%d)",
		timeout, s.lastCommandIdxOnOpen)
	return s.WaitForApplied(timeout)
}
func (s *Store) WaitForApplied(timeout time.Duration) error {
	if timeout == 0 {
		return nil
	}
	return s.WaitForAppliedIndex(s.raft.LastIndex(), timeout)
}
func (s *Store) WaitForAppliedIndex(idx uint64, timeout time.Duration) error {
	tck := time.NewTicker(appliedWaitDelay)
	defer tck.Stop()
	tmr := time.NewTimer(timeout)
	defer tmr.Stop()
	for {
		select {
		case <-tck.C:
			if s.raft.AppliedIndex() >= idx {
				return nil
			}
		case <-tmr.C:
			return fmt.Errorf("timeout expired")
		}
	}
}
func (s *Store) IsLeader() bool {
	return s.raft.State() == raft.Leader
}
func (s *Store) State() ClusterState {
	state := s.raft.State()
	switch state {
	case raft.Leader:
		return Leader
	case raft.Candidate:
		return Candidate
	case raft.Follower:
		return Follower
	case raft.Shutdown:
		return Shutdown
	default:
		return Unknown
	}
}
func (s *Store) Path() string {
	return s.raftDir
}
func (s *Store) Addr() string {
	return string(s.raftTn.LocalAddr())
}
func (s *Store) ID() string {
	return s.raftID
}
func (s *Store) LeaderAddr() (string, error) {
	return string(s.raft.Leader()), nil
}
func (s *Store) LeaderID() (string, error) {
	addr, err := s.LeaderAddr()
	if err != nil {
		return "", nil
	}
	configFuture := s.raft.GetConfiguration()
	if err := configFuture.Error(); err != nil {
		s.logger.Printf("failed to get raft configuration: %v", err)
		return "", err
	}
	for _, srv := range configFuture.Configuration().Servers {
		if srv.Address == raft.ServerAddress(addr) {
			return string(srv.ID), nil
		}
	}
	return "", nil
}
func (s *Store) Nodes() ([]*Server, error) {
	f := s.raft.GetConfiguration()
	if f.Error() != nil {
		return nil, f.Error()
	}
	rs := f.Configuration().Servers
	servers := make([]*Server, len(rs))
	for i := range rs {
		servers[i] = &Server{
			ID:       string(rs[i].ID),
			Addr:     string(rs[i].Address),
			Suffrage: rs[i].Suffrage.String(),
		}
	}
	sort.Sort(Servers(servers))
	return servers, nil
}
func (s *Store) WaitForLeader(timeout time.Duration) (string, error) {
	tck := time.NewTicker(leaderWaitDelay)
	defer tck.Stop()
	tmr := time.NewTimer(timeout)
	defer tmr.Stop()
	for {
		select {
		case <-tck.C:
			l, err := s.LeaderAddr()
			if err != nil {
				return "", nil
			}
			if l != "" {
				return l, nil
			}
		case <-tmr.C:
			return "", fmt.Errorf("timeout expired")
		}
	}
}
func (s *Store) SetRequestCompression(batch, size int) {
	s.reqMarshaller.BatchThreshold = batch
	s.reqMarshaller.SizeThreshold = size
}