github.com/criteo-forks/consul@v1.4.5-criteonogrpc/agent/consul/fsm/fsm.go (about)

     1  package fsm
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"log"
     7  	"sync"
     8  	"time"
     9  
    10  	"github.com/hashicorp/consul/agent/consul/state"
    11  	"github.com/hashicorp/consul/agent/structs"
    12  	"github.com/hashicorp/go-msgpack/codec"
    13  	"github.com/hashicorp/raft"
    14  )
    15  
    16  const (
    17  	testWatchLimit = 1024
    18  )
    19  
    20  // msgpackHandle is a shared handle for encoding/decoding msgpack payloads
    21  var msgpackHandle = &codec.MsgpackHandle{
    22  	RawToString: true,
    23  }
    24  
    25  // command is a command method on the FSM.
    26  type command func(buf []byte, index uint64) interface{}
    27  
    28  // unboundCommand is a command method on the FSM, not yet bound to an FSM
    29  // instance.
    30  type unboundCommand func(c *FSM, buf []byte, index uint64) interface{}
    31  
    32  // commands is a map from message type to unbound command.
    33  var commands map[structs.MessageType]unboundCommand
    34  
    35  // registerCommand registers a new command with the FSM, which should be done
    36  // at package init() time.
    37  func registerCommand(msg structs.MessageType, fn unboundCommand) {
    38  	if commands == nil {
    39  		commands = make(map[structs.MessageType]unboundCommand)
    40  	}
    41  	if commands[msg] != nil {
    42  		panic(fmt.Errorf("Message %d is already registered", msg))
    43  	}
    44  	commands[msg] = fn
    45  }
    46  
    47  // FSM implements a finite state machine that is used
    48  // along with Raft to provide strong consistency. We implement
    49  // this outside the Server to avoid exposing this outside the package.
    50  type FSM struct {
    51  	logOutput io.Writer
    52  	logger    *log.Logger
    53  	path      string
    54  
    55  	// apply is built off the commands global and is used to route apply
    56  	// operations to their appropriate handlers.
    57  	apply map[structs.MessageType]command
    58  
    59  	// stateLock is only used to protect outside callers to State() from
    60  	// racing with Restore(), which is called by Raft (it puts in a totally
    61  	// new state store). Everything internal here is synchronized by the
    62  	// Raft side, so doesn't need to lock this.
    63  	stateLock sync.RWMutex
    64  	state     *state.Store
    65  
    66  	gc         *state.TombstoneGC
    67  	watchLimit int
    68  }
    69  
    70  // New is used to construct a new FSM with a blank state.
    71  func New(gc *state.TombstoneGC, watchLimit int, logOutput io.Writer) (*FSM, error) {
    72  	logger := log.New(logOutput, "", log.LstdFlags)
    73  
    74  	stateNew, err := state.NewStateStore(gc, watchLimit, logger)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  
    79  	fsm := &FSM{
    80  		logOutput:  logOutput,
    81  		logger:     logger,
    82  		apply:      make(map[structs.MessageType]command),
    83  		state:      stateNew,
    84  		gc:         gc,
    85  		watchLimit: watchLimit,
    86  	}
    87  
    88  	// Build out the apply dispatch table based on the registered commands.
    89  	for msg, fn := range commands {
    90  		thisFn := fn
    91  		fsm.apply[msg] = func(buf []byte, index uint64) interface{} {
    92  			return thisFn(fsm, buf, index)
    93  		}
    94  	}
    95  
    96  	return fsm, nil
    97  }
    98  
    99  // State is used to return a handle to the current state
   100  func (c *FSM) State() *state.Store {
   101  	c.stateLock.RLock()
   102  	defer c.stateLock.RUnlock()
   103  	return c.state
   104  }
   105  
   106  func (c *FSM) Apply(log *raft.Log) interface{} {
   107  	buf := log.Data
   108  	msgType := structs.MessageType(buf[0])
   109  
   110  	// Check if this message type should be ignored when unknown. This is
   111  	// used so that new commands can be added with developer control if older
   112  	// versions can safely ignore the command, or if they should crash.
   113  	ignoreUnknown := false
   114  	if msgType&structs.IgnoreUnknownTypeFlag == structs.IgnoreUnknownTypeFlag {
   115  		msgType &= ^structs.IgnoreUnknownTypeFlag
   116  		ignoreUnknown = true
   117  	}
   118  
   119  	// Apply based on the dispatch table, if possible.
   120  	if fn := c.apply[msgType]; fn != nil {
   121  		return fn(buf[1:], log.Index)
   122  	}
   123  
   124  	// Otherwise, see if it's safe to ignore. If not, we have to panic so
   125  	// that we crash and our state doesn't diverge.
   126  	if ignoreUnknown {
   127  		c.logger.Printf("[WARN] consul.fsm: ignoring unknown message type (%d), upgrade to newer version", msgType)
   128  		return nil
   129  	}
   130  	panic(fmt.Errorf("failed to apply request: %#v", buf))
   131  }
   132  
   133  func (c *FSM) Snapshot() (raft.FSMSnapshot, error) {
   134  	defer func(start time.Time) {
   135  		c.logger.Printf("[INFO] consul.fsm: snapshot created in %v", time.Since(start))
   136  	}(time.Now())
   137  
   138  	return &snapshot{c.state.Snapshot()}, nil
   139  }
   140  
   141  // Restore streams in the snapshot and replaces the current state store with a
   142  // new one based on the snapshot if all goes OK during the restore.
   143  func (c *FSM) Restore(old io.ReadCloser) error {
   144  	defer old.Close()
   145  
   146  	// Create a new state store.
   147  	stateNew, err := state.NewStateStore(c.gc, c.watchLimit, c.logger)
   148  	if err != nil {
   149  		return err
   150  	}
   151  
   152  	// Set up a new restore transaction
   153  	restore := stateNew.Restore()
   154  	defer restore.Abort()
   155  
   156  	// Create a decoder
   157  	dec := codec.NewDecoder(old, msgpackHandle)
   158  
   159  	// Read in the header
   160  	var header snapshotHeader
   161  	if err := dec.Decode(&header); err != nil {
   162  		return err
   163  	}
   164  
   165  	// Populate the new state
   166  	msgType := make([]byte, 1)
   167  	for {
   168  		// Read the message type
   169  		_, err := old.Read(msgType)
   170  		if err == io.EOF {
   171  			break
   172  		} else if err != nil {
   173  			return err
   174  		}
   175  
   176  		// Decode
   177  		msg := structs.MessageType(msgType[0])
   178  		if fn := restorers[msg]; fn != nil {
   179  			if err := fn(&header, restore, dec); err != nil {
   180  				return err
   181  			}
   182  		} else {
   183  			return fmt.Errorf("Unrecognized msg type %d", msg)
   184  		}
   185  	}
   186  	restore.Commit()
   187  
   188  	// External code might be calling State(), so we need to synchronize
   189  	// here to make sure we swap in the new state store atomically.
   190  	c.stateLock.Lock()
   191  	stateOld := c.state
   192  	c.state = stateNew
   193  	c.stateLock.Unlock()
   194  
   195  	// Signal that the old state store has been abandoned. This is required
   196  	// because we don't operate on it any more, we just throw it away, so
   197  	// blocking queries won't see any changes and need to be woken up.
   198  	stateOld.Abandon()
   199  	return nil
   200  }