zk

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2024 License: BSD-3-Clause Imports: 18 Imported by: 1

README

Native Go Zookeeper Client Library

zk Coverage Status

License

3-clause BSD. See LICENSE file.

Documentation

Overview

Package zk is a native Go client library for the ZooKeeper orchestration service.

Index

Constants

View Source
const (
	// FlagEphemeral means the node is ephemeral.
	FlagEphemeral = 1
	FlagSequence  = 2
	FlagTTL       = 4
)
View Source
const (
	// PermRead represents the permission needed to read a znode.
	PermRead = 1 << iota
	PermWrite
	PermCreate
	PermDelete
	PermAdmin
	PermAll = 0x1f
)

Constants for ACL permissions

View Source
const (

	// DefaultPort is the default port listened by server.
	DefaultPort = 2181
)

Variables

View Source
var (
	// ErrConnectionClosed means the connection has been closed.
	ErrConnectionClosed        = errors.New("zk: connection closed")
	ErrUnknown                 = errors.New("zk: unknown error")
	ErrAPIError                = errors.New("zk: api error")
	ErrNoNode                  = errors.New("zk: node does not exist")
	ErrNoAuth                  = errors.New("zk: not authenticated")
	ErrBadVersion              = errors.New("zk: version conflict")
	ErrNoChildrenForEphemerals = errors.New("zk: ephemeral nodes may not have children")
	ErrNodeExists              = errors.New("zk: node already exists")
	ErrNotEmpty                = errors.New("zk: node has children")
	ErrSessionExpired          = errors.New("zk: session has been expired by the server")
	ErrInvalidACL              = errors.New("zk: invalid ACL specified")
	ErrAuthFailed              = errors.New("zk: client authentication failed")
	ErrClosing                 = errors.New("zk: zookeeper is closing")
	ErrNothing                 = errors.New("zk: no server responses to process")
	ErrSessionMoved            = errors.New("zk: session moved to another server, so operation is ignored")
	ErrReconfigDisabled        = errors.New("attempts to perform a reconfiguration operation when reconfiguration feature is disabled")
	ErrBadArguments            = errors.New("invalid arguments")
)
View Source
var (
	ErrUnhandledFieldType = errors.New("zk: unhandled field type")
	ErrPtrExpected        = errors.New("zk: encode/decode expect a non-nil pointer to struct")
	ErrShortBuffer        = errors.New("zk: buffer too small")
)
View Source
var ErrInvalidPath = errors.New("zk: invalid path")

ErrInvalidPath indicates that an operation was being attempted on an invalid path. (e.g. empty path).

Functions

func FormatServers

func FormatServers(servers []string) []string

FormatServers takes a slice of addresses, and makes sure they are in a format that resembles <addr>:<port>. If the server has no port provided, the DefaultPort constant is added to the end.

func ValidatePath

func ValidatePath(path string, isSequential bool) error

ValidatePath will make sure a path is valid before sending the request

Types

type ACL

type ACL struct {
	Perms  int32
	Scheme string
	ID     string
}

func AuthACL

func AuthACL(perms int32) []ACL

AuthACL produces an ACL list containing a single ACL which uses the provided permissions, with the scheme "auth", and ID "", which is used by ZooKeeper to represent any authenticated user.

func DigestACL

func DigestACL(perms int32, user, password string) []ACL

func WorldACL

func WorldACL(perms int32) []ACL

WorldACL produces an ACL list containing a single ACL which uses the provided permissions, with the scheme "world", and ID "anyone", which is used by ZooKeeper to represent any user at all.

type AddAuthResponse

type AddAuthResponse struct {
	Zxid int64
}

type CheckVersionRequest

type CheckVersionRequest PathVersionRequest

type ChildrenOption

type ChildrenOption func(opts *childrenOpts)

func WithChildrenWatch

func WithChildrenWatch(callback func(ev Event)) ChildrenOption

type ChildrenResponse

type ChildrenResponse struct {
	Zxid     int64
	Children []string
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client ...

func NewClient

func NewClient(servers []string, sessionTimeout time.Duration, options ...Option) (*Client, error)

func (*Client) AddAuth

func (c *Client) AddAuth(
	scheme string, auth []byte,
	callback func(resp AddAuthResponse, err error),
)

AddAuth often used with "digest" scheme and auth = "username:password" (password is not hashed)

func (*Client) Children

func (c *Client) Children(
	path string,
	callback func(resp ChildrenResponse, err error),
	options ...ChildrenOption,
)

func (*Client) Close

func (c *Client) Close()

Close ...

func (*Client) Create

func (c *Client) Create(
	path string, data []byte, flags int32, acl []ACL,
	callback func(resp CreateResponse, err error),
)

Create ...

func (*Client) Delete

func (c *Client) Delete(
	path string, version int32,
	callback func(resp DeleteResponse, err error),
)

func (*Client) Exists

func (c *Client) Exists(
	path string,
	callback func(resp ExistsResponse, err error),
	options ...ExistsOption,
)

func (*Client) Get

func (c *Client) Get(
	path string,
	callback func(resp GetResponse, err error),
	options ...GetOption,
)

func (*Client) GetACL

func (c *Client) GetACL(
	path string,
	callback func(resp GetACLResponse, err error),
)

GetACL returns ACL for a znode

func (*Client) Set

func (c *Client) Set(
	path string, data []byte, version int32,
	callback func(resp SetResponse, err error),
)

func (*Client) SetACL

func (c *Client) SetACL(
	path string, acl []ACL, version int32,
	callback func(resp SetACLResponse, err error),
)

SetACL set ACL to ZK version is the ACL Version (Stat.Aversion), not a normal version number

type CreateContainerRequest

type CreateContainerRequest CreateRequest

type CreateRequest

type CreateRequest struct {
	Path  string
	Data  []byte
	Acl   []ACL
	Flags int32
}

type CreateResponse

type CreateResponse struct {
	Zxid int64
	Path string
}

type CreateTTLRequest

type CreateTTLRequest struct {
	Path  string
	Data  []byte
	Acl   []ACL
	Flags int32
	Ttl   int64 // ms
}

type DeleteRequest

type DeleteRequest PathVersionRequest

type DeleteResponse

type DeleteResponse struct {
	Zxid int64
}

type ErrCode

type ErrCode int32

ErrCode is the error code defined by server. Refer to ZK documentations for more specifics.

type Event

type Event struct {
	Type  EventType
	State State
	Path  string // For non-session events, the path of the watched node.
}

Event is a Znode event sent by the server. Refer to EventType for more details.

type EventType

type EventType int32

EventType represents the event type sent by server.

const (
	// EventNodeCreated represents a node is created.
	EventNodeCreated         EventType = 1
	EventNodeDeleted         EventType = 2
	EventNodeDataChanged     EventType = 3
	EventNodeChildrenChanged EventType = 4
)

func (EventType) String

func (t EventType) String() string

type ExistsOption

type ExistsOption func(opts *existsOpts)

func WithExistsWatch

func WithExistsWatch(callback func(ev Event)) ExistsOption

type ExistsResponse

type ExistsResponse struct {
	Zxid int64
	Stat Stat
}

type GetACLResponse

type GetACLResponse struct {
	Zxid int64
	ACL  []ACL
	Stat Stat
}

type GetOption

type GetOption func(opts *getOpts)

func WithGetWatch

func WithGetWatch(callback func(ev Event)) GetOption

type GetResponse

type GetResponse struct {
	Zxid int64
	Data []byte
	Stat Stat
}

type Logger

type Logger interface {
	Infof(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
}

type Mode

type Mode uint8

Mode is used to build custom server modes (leader|follower|standalone).

const (
	ModeUnknown    Mode = iota
	ModeLeader     Mode = iota
	ModeFollower   Mode = iota
	ModeStandalone Mode = iota
)

func (Mode) String

func (m Mode) String() string

type NetworkConn

type NetworkConn interface {
	io.Reader
	io.Writer
	io.Closer

	// SetReadDeadline sets the deadline for future Read calls
	// and any currently-blocked Read call.
	// A zero value for t means Read will not time out.
	SetReadDeadline(d time.Duration) error

	// SetWriteDeadline sets the deadline for future Write calls
	// and any currently-blocked Write call.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	// A zero value for t means Write will not time out.
	SetWriteDeadline(d time.Duration) error
}

func NewTCPConn

func NewTCPConn(conn net.Conn) NetworkConn

type Option

type Option func(c *Client)

Option ...

func WithDialRetryDuration

func WithDialRetryDuration(d time.Duration) Option

func WithDialTimeoutFunc

func WithDialTimeoutFunc(
	dialFunc func(addr string, timeout time.Duration) (NetworkConn, error),
) Option

func WithLogger

func WithLogger(l Logger) Option

func WithReconnectingCallback

func WithReconnectingCallback(callback func(c *Client)) Option

func WithServerSelector

func WithServerSelector(selector ServerSelector) Option

func WithSessionEstablishedCallback

func WithSessionEstablishedCallback(callback func(c *Client)) Option

func WithSessionExpiredCallback

func WithSessionExpiredCallback(callback func(c *Client)) Option

type PathVersionRequest

type PathVersionRequest struct {
	Path    string
	Version int32
}

type SelectNextOutput

type SelectNextOutput struct {
	Server     string
	RetryStart bool
}

type ServerClient

type ServerClient struct {
	Queued        int64
	Received      int64
	Sent          int64
	SessionID     int64
	Lcxid         int64
	Lzxid         int64
	Timeout       int32
	LastLatency   int32
	MinLatency    int32
	AvgLatency    int32
	MaxLatency    int32
	Established   time.Time
	LastResponse  time.Time
	Addr          string
	LastOperation string // maybe?
	Error         error
}

ServerClient is the information for a single Zookeeper client and its session. This is used to parse/extract the output fo the `cons` command.

type ServerClients

type ServerClients struct {
	Clients []*ServerClient
	Error   error
}

ServerClients is a struct for the FLWCons() function. It's used to provide the list of Clients.

This is needed because FLWCons() takes multiple servers.

type ServerListSelector

type ServerListSelector struct {
	// contains filtered or unexported fields
}

func (*ServerListSelector) Init

func (s *ServerListSelector) Init(servers []string)

func (*ServerListSelector) Next

func (*ServerListSelector) NotifyConnected

func (s *ServerListSelector) NotifyConnected()

type ServerSelector

type ServerSelector interface {
	Init(servers []string)
	Next() SelectNextOutput
	NotifyConnected()
}

func NewServerListSelector

func NewServerListSelector(seed int64) ServerSelector

type ServerStats

type ServerStats struct {
	Server      string
	Sent        int64
	Received    int64
	NodeCount   int64
	MinLatency  int64
	AvgLatency  float64
	MaxLatency  int64
	Connections int64
	Outstanding int64
	Epoch       int32
	Counter     int32
	BuildTime   time.Time
	Mode        Mode
	Version     string
	Error       error
}

ServerStats is the information pulled from the Zookeeper `stat` command.

type SetACLResponse

type SetACLResponse struct {
	Zxid int64
	Stat Stat
}

type SetDataRequest

type SetDataRequest struct {
	Path    string
	Data    []byte
	Version int32
}

type SetResponse

type SetResponse struct {
	Zxid int64
	Stat Stat
}

type Stat

type Stat struct {
	Czxid          int64 // The zxid of the change that caused this znode to be created.
	Mzxid          int64 // The zxid of the change that last modified this znode.
	Ctime          int64 // The time in milliseconds from epoch when this znode was created.
	Mtime          int64 // The time in milliseconds from epoch when this znode was last modified.
	Version        int32 // The number of changes to the data of this znode.
	Cversion       int32 // The number of changes to the children of this znode.
	Aversion       int32 // The number of changes to the ACL of this znode.
	EphemeralOwner int64 // The session id of the owner of this znode if the znode is an ephemeral node. If it is not an ephemeral node, it will be zero.
	DataLength     int32 // The length of the data field of this znode.
	NumChildren    int32 // The number of children of this znode.
	Pzxid          int64 // last modified children
}

type State

type State int32

State is the session state.

const (
	// StateUnknown means the session state is unknown.
	StateUnknown           State = -1
	StateDisconnected      State = 0
	StateConnecting        State = 1
	StateAuthFailed        State = 4
	StateConnectedReadOnly State = 5
	StateSaslAuthenticated State = 6
	StateExpired           State = -112

	StateConnected  = State(100)
	StateHasSession = State(101)
)

func (State) String

func (s State) String() string

String converts State to a readable string.

Directories

Path Synopsis
test-examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL