Documentation ¶
Index ¶
- Constants
- Variables
- func CheckMethod(m string, f ServeHTTPFn, w http.ResponseWriter, r *http.Request)
- func CheckMethodE(m string, f ServeHTTPFnE, w http.ResponseWriter, r *http.Request)
- func CloneMap(m map[string]string) map[string]string
- func EmptyThen(s, t string) string
- func EqualsThen(s, e, t string) string
- func FormatTime(t time.Time) string
- func GetJSON(addr string, v interface{}) (string, error)
- func HasPrefix(s string, p ...string) bool
- func If(i bool, s, t string) string
- func IsRelativeForward(statusCode int, locationHeader string) bool
- func Join(logger LevelLogger, joinAddr, raftAddr string, nodeID NodeID) error
- func Jsonify(v interface{}) string
- func Jsonify4Print(v interface{}) string
- func JsonifyBytes(v interface{}) []byte
- func ParseIps(host string) []string
- func ParseJSON(v string) (m interface{}, err error)
- func ParseSuffrage(s string) raft.ServerSuffrage
- func ParseTime(s string) (time.Time, error)
- func PathExists(p string) bool
- func PostJSON(addr string, body, v interface{}) (int, string, error)
- func ReadBytes(object io.ReadCloser) []byte
- func ReadPeersJSON(path string) (raft.Configuration, error)
- func ReadString(object io.ReadCloser) string
- func ReverseProxy(targetHost, targetPath string, timeout time.Duration) *httputil.ReverseProxy
- func TryParseJSON(v string) interface{}
- func WaitInterrupt()
- func WriteAsJSON(m interface{}, w http.ResponseWriter)
- func WriteAsText(s string, w http.ResponseWriter)
- type ApplyInterceptor
- type Arg
- type BindAddr
- type Command
- type ConfigEntry
- type Dealer
- type DealerMap
- type Dialer
- type DistributedApplier
- type Distributor
- type FlagNames
- type FlagOptionFn
- func FlagHaddr(name string) FlagOptionFn
- func FlagHadv(name string) FlagOptionFn
- func FlagIface(name string) FlagOptionFn
- func FlagRaddr(name string) FlagOptionFn
- func FlagRadv(name string) FlagOptionFn
- func FlagRdir(name string) FlagOptionFn
- func FlagRjoin(name string) FlagOptionFn
- func FlagRmem(name string) FlagOptionFn
- type FlagProvider
- type Identifier
- type JobRsp
- type JoinRequest
- type LevelLogger
- type LevelLoggerAdapter
- func (l LevelLoggerAdapter) Debugf(format string, data ...interface{})
- func (l LevelLoggerAdapter) Errorf(format string, data ...interface{})
- func (l LevelLoggerAdapter) Infof(format string, data ...interface{})
- func (l LevelLoggerAdapter) Panicf(format string, data ...interface{})
- func (l LevelLoggerAdapter) Printf(format string, data ...interface{})
- func (l LevelLoggerAdapter) Warnf(format string, data ...interface{})
- type LogDealer
- type LogLevel
- type Logger
- type LoggerMore
- type LogrusAdapter
- type NodeID
- type NodeState
- type Peer
- type RaftCluster
- type RaftStore
- func (s *RaftStore) Apply(l *raft.Log) interface{}
- func (s *RaftStore) Cluster() (RaftCluster, error)
- func (s *RaftStore) Delete(key string) error
- func (s *RaftStore) Get(key string) (v string, ok bool)
- func (s *RaftStore) IsLeader() bool
- func (s *RaftStore) Join(nodeID, addr string) error
- func (s *RaftStore) LeadServer() (Peer, error)
- func (s *RaftStore) LeaderAddr() string
- func (s *RaftStore) LeaderCh() <-chan bool
- func (s *RaftStore) NodeState() string
- func (s *RaftStore) Open() error
- func (s *RaftStore) RaftStats() map[string]interface{}
- func (s *RaftStore) Remove(nodeID string) error
- func (s *RaftStore) Restore(rc io.ReadCloser) error
- func (s *RaftStore) Set(key, value string) error
- func (s *RaftStore) Snapshot() (raft.FSMSnapshot, error)
- func (s *RaftStore) WaitForApplied(timeout time.Duration) error
- func (s *RaftStore) WaitForAppliedIndex(idx uint64, timeout time.Duration) error
- func (s *RaftStore) WaitForLeader(timeout time.Duration) (string, error)
- type Rsp
- type SLogger
- type ServeHTTPFn
- type ServeHTTPFnE
- type Service
- func (s *Service) Addr() net.Addr
- func (s *Service) Close() error
- func (s *Service) GoStartHTTP() (err error)
- func (s *Service) IsLeader() bool
- func (s *Service) RaftCluster() (RaftCluster, error)
- func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Service) Set(k, v string) error
- func (s *Service) StartAll() error
- func (s *Service) StartRaft() error
- type StdLogger
- type Store
- type Ticker
- type ViperProvider
- type Writer
Constants ¶
const ( // RaftPath is the http prefix for raft apis RaftPath = "/hraftd/raft" // KeyPath is the http prefix for raft key operations KeyPath = "/hraftd/key" // DoJobPath is the http prefix for raft dojob operations DoJobPath = "/hraftd/dojob" )
const ContentTypeJSON = "application-type/json"
ContentTypeJSON is the JSON Content-Type.
const StateFollower = "Follower"
StateFollower is the state string for follower.
const StateLeader = "Leader"
StateLeader is the state string for leader.
const XOriginRemoteAddr = "X-Origin-RemoteAddr"
XOriginRemoteAddr is the const of header for original remote addr to real address sourcing.
Variables ¶
var ( // ErrDealerNoExists is the error for the dealer not exists. ErrDealerNoExists = errors.New("dealer does not exist") // ErrDealerContinue is the error for the dealer bypass and should continue ErrDealerContinue = errors.New("dealer bypass and should continue") )
var ( // ErrNotLeader is returned when a node attempts to execute a leader-only operation. ErrNotLeader = errors.New("not leader") // ErrOpenTimeout is returned when the Store does not apply its initial logs within the specified time. ErrOpenTimeout = errors.New("timeout waiting for initial logs application") )
var DefaultLogger = NewSLogger()
DefaultLogger is the default global logger. nolint
Functions ¶
func CheckMethod ¶
func CheckMethod(m string, f ServeHTTPFn, w http.ResponseWriter, r *http.Request)
CheckMethod checks the method and invoke f.
func CheckMethodE ¶
func CheckMethodE(m string, f ServeHTTPFnE, w http.ResponseWriter, r *http.Request)
CheckMethodE checks the method and invoke f.
func FormatTime ¶
FormatTime format time. FormatTime format time.
func IsRelativeForward ¶
IsRelativeForward tells the statusCode is 301/302 and locationHeader is relative.
func Join ¶
func Join(logger LevelLogger, joinAddr, raftAddr string, nodeID NodeID) error
Join joins current node (raftAddr and nodeID) to joinAddr.
func Jsonify4Print ¶
func Jsonify4Print(v interface{}) string
Jsonify4Print jsonifies v to JSON string for printing only.
func JsonifyBytes ¶
func JsonifyBytes(v interface{}) []byte
JsonifyBytes jsonifies v to JSON []byte.
func ParseSuffrage ¶
func ParseSuffrage(s string) raft.ServerSuffrage
ParseSuffrage parses s to raft.ServerSuffrage.
func ReadPeersJSON ¶
func ReadPeersJSON(path string) (raft.Configuration, error)
ReadPeersJSON consumes a legacy peers.json file in the format of the old JSON peer store and creates a new-style configuration structure. This can be used to migrate this data or perform manual recovery when running protocol versions that can interoperate with older, unversioned Raft servers. This should not be used once server IDs are in use, because the old peers.json file didn't have support for these, nor non-voter suffrage types.
func ReverseProxy ¶
func ReverseProxy(targetHost, targetPath string, timeout time.Duration) *httputil.ReverseProxy
ReverseProxy reverse proxy originalPath to targetHost with targetPath.
func TryParseJSON ¶
func TryParseJSON(v string) interface{}
TryParseJSON try parse v as JSON,return parsed object or failed to source v.
func WriteAsJSON ¶
func WriteAsJSON(m interface{}, w http.ResponseWriter)
WriteAsJSON writes m as JSON.
func WriteAsText ¶
func WriteAsText(s string, w http.ResponseWriter)
WriteAsText writes s as text/plain.
Types ¶
type ApplyInterceptor ¶
ApplyInterceptor defines the raft log apply interceptor prototype.
type Arg ¶
type Arg struct { Bootstrap bool InMem bool RaftAddr string RaftAdv string RaftNodeDir string NodeID NodeID HTTPAddr string HTTPAdv string JoinAddrs string IfaceName string // 绑定网卡名称 JoinAddrSlice []string HostIP string ApplyInterceptor ApplyInterceptor `json:"-"` LogDealer `json:"-"` LoggerMore `json:"-"` }
Arg Command line parameters.
func CreateArg ¶
func CreateArg(p ViperProvider, flagOptionFns ...FlagOptionFn) *Arg
CreateArg creates Arg by ViperProvider implementation.
func DefineFlags ¶
func DefineFlags(p FlagProvider, flagOptionFns ...FlagOptionFn) *Arg
DefineFlags define raft args.
func (*Arg) ConvertToZeroHost ¶
ConvertToZeroHost tries to bind localip:port to :port.
type BindAddr ¶
type BindAddr string
BindAddr is the address for bind.
func (BindAddr) URLRaftJoin ¶
URLRaftJoin is http://httpAddr/raft/join
type Command ¶
type Command struct { Op string `json:"op,omitempty"` Key string `json:"key,omitempty"` Value string `json:"value,omitempty"` Time string `json:"time"` }
Command defines raft log value's structure.
type ConfigEntry ¶
type ConfigEntry struct { // ID is the ID of the server (a UUID, usually). ID raft.ServerID `json:"id"` // Address is the host:port of the server. Address raft.ServerAddress `json:"address"` // NonVoter controls the suffrage. We choose this sense so people // can leave this out and get a Voter by default. Suffrage string `json:"suffrage"` }
ConfigEntry is used when decoding a new-style peers.json.
type DealerMap ¶
DealerMap keep mapping dealer path to registered dealer.
func (*DealerMap) RegisterJobDealer ¶
RegisterJobDealer registers path dealers.
type Dialer ¶
Dialer defines dialer function alias.
func TimeoutDialer ¶
TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. https://gist.github.com/c4milo/275abc6eccbfd88ad56ca7c77947883a HTTP client with support for read and write timeouts which are missing in Go's standard library.
type DistributedApplier ¶
type DistributedApplier interface {
Distribute(NodeID NodeID, item Identifier)
}
DistributedApplier is the data applier with NodeID.
type Distributor ¶
type Distributor struct { // sticky to the previous nodeID when redistribute every time. StickyMap map[string]NodeID }
Distributor is the role to charge the distribution among the hraft cluster nodes.
func (*Distributor) CleanSticky ¶
func (d *Distributor) CleanSticky()
CleanSticky cleans the sticky map state.
func (*Distributor) Distribute ¶
func (d *Distributor) Distribute(peers []Peer, data, emptyReceiver interface{}) interface{}
Distribute do the distribution.
func (*Distributor) Put ¶
func (d *Distributor) Put(id string, nodeID NodeID)
Put puts the node ID related to id directly.
type FlagNames ¶
type FlagNames struct { Rmem string `default:"rmem"` Haddr string `default:"haddr"` Hadv string `default:"hadv"` Raddr string `default:"raddr"` Radv string `default:"radv"` Rdir string `default:"rdir"` Rjoin string `default:"rjoin"` Iface string `default:"iface"` }
FlagNames defines struct for flag names.
type FlagOptionFn ¶
type FlagOptionFn func(flagNames *FlagNames)
FlagOptionFn defines FlagOption option func prototype.
func FlagHaddr ¶
func FlagHaddr(name string) FlagOptionFn
FlagHaddr defines HTTPAddr flag name. If empty, disable the flag.
func FlagHadv ¶
func FlagHadv(name string) FlagOptionFn
FlagHadv defines HTTPAdv flag name. If empty, disable the flag.
func FlagIface ¶
func FlagIface(name string) FlagOptionFn
FlagIface defines IfaceName flag name. If empty, disable the flag.
func FlagRaddr ¶
func FlagRaddr(name string) FlagOptionFn
FlagRaddr defines RaftAddr flag name. If empty, disable the flag.
func FlagRadv ¶
func FlagRadv(name string) FlagOptionFn
FlagRadv defines RaftAdv flag name. If empty, disable the flag.
func FlagRdir ¶
func FlagRdir(name string) FlagOptionFn
FlagRdir defines RaftNodeDir flag name. If empty, disable the flag.
func FlagRjoin ¶
func FlagRjoin(name string) FlagOptionFn
FlagRjoin defines JoinAddrs flag name. If empty, disable the flag.
func FlagRmem ¶
func FlagRmem(name string) FlagOptionFn
FlagRmem defines InMem flag name. If empty, disable the flag.
type FlagProvider ¶
type FlagProvider interface { BoolVar(p *bool, name string, value bool, usage string) StringVar(p *string, name string, value string, usage string) }
FlagProvider defines the interface for flag definitions required for hraftd.
type JobRsp ¶
type JobRsp struct { OK bool `json:"ok"` Msg string `json:"msg,omitempty"` Data jsoniter.RawMessage `json:"data,omitempty"` }
JobRsp defines the Job Response structure.
type JoinRequest ¶
JoinRequest defines the Raft join request.
func (*JoinRequest) Fix ¶
func (r *JoinRequest) Fix(remoteAddr string)
Fix fixes the join request's host.
type LevelLogger ¶
type LevelLogger interface { // Printf prints info. Printf(format string, data ...interface{}) // Debugf prints debug. Debugf(format string, data ...interface{}) // Infof prints info. Infof(format string, data ...interface{}) // Warnf prints warn messages. Warnf(format string, data ...interface{}) // Errorf prints error messages. Errorf(format string, data ...interface{}) // Panicf prints error messages and panics. Panicf(format string, data ...interface{}) }
LevelLogger ...
type LevelLoggerAdapter ¶
type LevelLoggerAdapter struct{ Logger }
LevelLoggerAdapter adapters Logger to LevelLogger.
func NewLogrusAdapter ¶
func NewLogrusAdapter(logrus *logrus.Logger) *LevelLoggerAdapter
NewLogrusAdapter news a LogrusAdapter.
func (LevelLoggerAdapter) Debugf ¶
func (l LevelLoggerAdapter) Debugf(format string, data ...interface{})
Debugf prints debug.
func (LevelLoggerAdapter) Errorf ¶
func (l LevelLoggerAdapter) Errorf(format string, data ...interface{})
Errorf prints error messages.
func (LevelLoggerAdapter) Infof ¶
func (l LevelLoggerAdapter) Infof(format string, data ...interface{})
Infof prints info.
func (LevelLoggerAdapter) Panicf ¶
func (l LevelLoggerAdapter) Panicf(format string, data ...interface{})
Panicf prints error messages and panic.
func (LevelLoggerAdapter) Printf ¶
func (l LevelLoggerAdapter) Printf(format string, data ...interface{})
Printf prints info.
func (LevelLoggerAdapter) Warnf ¶
func (l LevelLoggerAdapter) Warnf(format string, data ...interface{})
Warnf prints warn messages.
type LogDealer ¶
type LogDealer struct {
DealerMap
}
LogDealer defines the structure of log dealer.
func (*LogDealer) RegisterLogDealer ¶
RegisterLogDealer registers the dealer for the command which name is cmdName.
type Logger ¶
type Logger interface { // SetLogLevel sets the log level. SetLogLevel(logLevel LogLevel) // GetLogLevel returns the log level. GetLogLevel() LogLevel // GetIOWriter returns io.Writer. GetIOWriter() io.Writer // Logf prints log. Logf(level LogLevel, format string, data ...interface{}) }
Logger defines logger interface.
type LogrusAdapter ¶
LogrusAdapter adapts the logrus to Logger.
func (LogrusAdapter) GetIOWriter ¶
func (l LogrusAdapter) GetIOWriter() io.Writer
GetIOWriter returns io.Writer.
func (LogrusAdapter) GetLogLevel ¶
func (l LogrusAdapter) GetLogLevel() LogLevel
GetLogLevel returns the log level.
func (LogrusAdapter) Logf ¶
func (l LogrusAdapter) Logf(logLevel LogLevel, format string, data ...interface{})
Logf prints log.
func (*LogrusAdapter) SetLogLevel ¶
func (l *LogrusAdapter) SetLogLevel(logLevel LogLevel)
SetLogLevel sets the log level.
type NodeID ¶
type NodeID string
NodeID is the raft node ID.
func (NodeID) URLRaftCluster ¶
URLRaftCluster is http://httpAddr/raft/cluster.
func (NodeID) URLRaftJoin ¶
URLRaftJoin is http://httpAddr/raft/join.
func (NodeID) URLRaftState ¶
URLRaftState is http://httpAddr/raft/state.
type NodeState ¶
type NodeState struct { StartTime string `json:"startTime"` NodeID string `json:"nodeID"` Hostname string `json:"hostname"` IP string `json:"IP"` }
NodeState is raft cluster node state.
type Peer ¶
type Peer struct { Address string `json:"address"` ID NodeID `json:"id"` State string `json:"state"` Suffrage string `json:"suffrage"` }
Peer defines the peers information.
func (Peer) AnyStateOf ¶
AnyStateOf returns true if current state of peer is in any of states.
func (Peer) DistributeJob ¶
func (p Peer) DistributeJob(logger LevelLogger, path string, req interface{}, rsp interface{}) error
DistributeJob distributes job to the peer node in the raft clusters.
type RaftCluster ¶
type RaftCluster struct { Current Peer `json:"current"` Leader Peer `json:"leader"` Servers []Peer `json:"servers"` }
RaftCluster is raft cluster.
func Cluster ¶
func Cluster(logger LevelLogger, nodeID NodeID) (v RaftCluster, err error)
Cluster retrieves the RaftCluster. nolint:gofumpt
func (RaftCluster) ActivePeers ¶
func (r RaftCluster) ActivePeers() []Peer
ActivePeers returns active peers in the cluster.
type RaftStore ¶
type RaftStore struct { *Arg // contains filtered or unexported fields }
RaftStore is a simple key-value store, where all changes are made via Raft consensus.
func (*RaftStore) Cluster ¶
func (s *RaftStore) Cluster() (RaftCluster, error)
Cluster returns the raft cluster state.
func (*RaftStore) Join ¶
Join joins a node, identified by nodeID and located at addr, to this store. The node must be ready to respond to Raft communications at that address.
func (*RaftStore) LeadServer ¶
LeadServer returns the raft lead server.
func (*RaftStore) LeaderAddr ¶
LeaderAddr returns the address of the current leader. Returns blank if no leader.
func (*RaftStore) LeaderCh ¶
LeaderCh is used to get a channel which delivers signals on acquiring or losing leadership. It sends true if we become the leader, and false if we lose it. The channel is not buffered, and does not block on writes.
func (*RaftStore) Open ¶
Open opens the store. If enableSingle is set, and there are no existing peers, then this node becomes the first node, and therefore leader, of the cluster. localID should be the server identifier for this node.
func (*RaftStore) Restore ¶
func (s *RaftStore) Restore(rc io.ReadCloser) error
Restore stores the key-value store to a previous state.
func (*RaftStore) Snapshot ¶
func (s *RaftStore) Snapshot() (raft.FSMSnapshot, error)
Snapshot returns a snapshot of the key-value store.
func (*RaftStore) WaitForApplied ¶
WaitForApplied waits for all Raft log entries to to be applied to the underlying database.
func (*RaftStore) WaitForAppliedIndex ¶
WaitForAppliedIndex blocks until a given log index has been applied, or the timeout expires.
type Rsp ¶
type Rsp struct { OK bool `json:"ok"` Msg string `json:"msg,omitempty"` Data interface{} `json:"data,omitempty"` }
Rsp defines the Raft join response.
type SLogger ¶
type SLogger struct { Writer IOWriter io.Writer Level LogLevel LevelLogger }
SLogger defines the simplest logger implementation of Interface.
func (*SLogger) GetIOWriter ¶
GetIOWriter returns io.Writer.
func (SLogger) GetLogLevel ¶
GetLogLevel gets the log level.
func (*SLogger) SetLogLevel ¶
SetLogLevel sets the log level.
type ServeHTTPFn ¶
type ServeHTTPFn func(w http.ResponseWriter, r *http.Request)
ServeHTTPFn defines ServeHTTP function prototype.
type ServeHTTPFnE ¶
type ServeHTTPFnE func(w http.ResponseWriter, r *http.Request) error
ServeHTTPFnE defines ServeHTTP function prototype.
type Service ¶
Service provides HTTP service.
func (*Service) GoStartHTTP ¶
GoStartHTTP starts the http server in go routine.
func (*Service) RaftCluster ¶
func (s *Service) RaftCluster() (RaftCluster, error)
RaftCluster returns raft cluster.
func (*Service) ServeHTTP ¶
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP allows Service to serve HTTP requests.
type StdLogger ¶
type StdLogger struct { Out io.Writer // destination for output CallDepth int // used for print logger file and line number PrintCallerInfo bool // switcher to print caller info // contains filtered or unexported fields }
A StdLogger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.
func NewStdLogger ¶
NewStdLogger creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line. The flag argument defines the logging properties.
func (*StdLogger) Output ¶
Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. CallDepth is used to recover the PC and is provided for generality, although at the moment on all pre-defined paths it will be 2.
type Store ¶
type Store interface { // Get returns the value for the given key. Get(key string) (string, bool) // IsLeader tells the current node is raft leader or not. IsLeader() bool // Set sets the value for the given key, via distributed consensus. Set(key, value string) error // Delete removes the given key, via distributed consensus. Delete(key string) error // Join joins the node, identified by nodeID and reachable at addr, to the cluster. Join(nodeID string, addr string) error // Remove removes node from the cluster Remove(nodeID string) error // RaftStats returns the raft stats RaftStats() map[string]interface{} // Cluster returns the raft cluster servers Cluster() (RaftCluster, error) // LeadServer returns the raft lead server LeadServer() (Peer, error) // WaitForLeader blocks until a leader is detected, or the timeout expires. WaitForLeader(timeout time.Duration) (string, error) // WaitForApplied waits for all Raft log entries to to be applied to the // underlying database. WaitForApplied(timeout time.Duration) error // LeaderCh is used to get a channel which delivers signals on // acquiring or losing leadership. It sends true if we become // the leader, and false if we lose it. The channel is not buffered, // and does not block on writes. LeaderCh() <-chan bool // NodeState returns the state of current node NodeState() string }
Store is the interface Raft-backed key-value stores must implement.
type Ticker ¶
type Ticker struct {
// contains filtered or unexported fields
}
Ticker defines a ticker.
func (*Ticker) StartAsync ¶
func (j *Ticker) StartAsync(tickerFns ...func())
StartAsync starts the ticker. if tickerFns are passed, they will overwrite the previous passed in NewTicker call.