net

package
v0.0.0-...-d224df5 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2022 License: MIT Imports: 45 Imported by: 0

Documentation

Overview

* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.

Index

Constants

View Source
const (
	CompressNone            CompressType = flate.NoCompression      // 0
	CompressZip                          = flate.DefaultCompression // -1
	CompressBestSpeed                    = flate.BestSpeed          // 1
	CompressBestCompression              = flate.BestCompression    // 9
	CompressHuffman                      = flate.HuffmanOnly        // -2
	CompressSnappy                       = 10
)
View Source
const (
	Version = "1.3.0"
	DATE    = "2020/12/13"
)
View Source
const (
	MaxWheelTimeSpan = 900e9 // 900s, 15 minute

)
View Source
const (
	WritePkgTimeout = 1e8
)

Variables

View Source
var (
	ErrSessionClosed  = jerrors.New("session Already Closed")
	ErrSessionBlocked = jerrors.New("session Full Blocked")
	ErrNullPeerAddr   = jerrors.New("peer address is nil")
)
View Source
var (
	ErrNotEnoughStream = errors.New("packet stream is not enough")
	ErrTooLargePackage = errors.New("package length is exceed the echo package's legal maximum length.")
	ErrIllegalMagic    = errors.New("package magic is not right.")
)
View Source
var EndPointType_name = map[int32]string{
	2: "TCP_CLIENT",
	7: "TCP_SERVER",
}
View Source
var EndPointType_value = map[string]int32{
	"TCP_CLIENT": 2,
	"TCP_SERVER": 7,
}

Functions

func GetTimeWheel

func GetTimeWheel() *gxtime.Wheel

func NewMySQLServerSession

func NewMySQLServerSession(session Session) innodb.MySQLServerSession

Types

type Client

type Client interface {
	EndPoint
}

func NewTCPClient

func NewTCPClient(opts ...ClientOption) Client

NewTcpClient function builds a tcp client.

type ClientOption

type ClientOption func(*ClientOptions)

func WithClientSslEnabled

func WithClientSslEnabled(sslEnabled bool) ClientOption

@WithSslEnabled enable use tls

func WithClientTaskPool

func WithClientTaskPool(pool gxsync.GenericTaskPool) ClientOption

@pool client task pool.

func WithClientTlsConfigBuilder

func WithClientTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ClientOption

@WithClientKeyCertChainPath sslConfig is tls config

func WithConnectionNumber

func WithConnectionNumber(num int) ClientOption

@num is connection number.

func WithReconnectInterval

func WithReconnectInterval(reconnectInterval int) ClientOption

@reconnectInterval is serverimpl address.

func WithRootCertificateFile

func WithRootCertificateFile(cert string) ClientOption

@cert is client certificate file. it can be empty.

func WithServerAddress

func WithServerAddress(addr string) ClientOption

@addr is serverimpl address.

type ClientOptions

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

type ClientTlsConfigBuilder

type ClientTlsConfigBuilder struct {
	ClientKeyCertChainPath        string
	ClientPrivateKeyPath          string
	ClientKeyPassword             string
	ClientTrustCertCollectionPath string
}

ClientTlsConfigBuilder impl TlsConfigBuilder for client

func (*ClientTlsConfigBuilder) BuildTlsConfig

func (c *ClientTlsConfigBuilder) BuildTlsConfig() (*tls.Config, error)

BuildTlsConfig impl TlsConfigBuilder method

type CompressType

type CompressType int

type Connection

type Connection interface {
	ID() uint32
	SetCompressType(CompressType)
	LocalAddr() string
	RemoteAddr() string

	// update session's active time
	UpdateActive()
	// get session's active time
	GetActive() time.Time

	// SetReadTimeout sets deadline for the future read calls.
	SetReadTimeout(time.Duration)

	// SetWriteTimeout sets deadline for the future read calls.
	SetWriteTimeout(time.Duration)
	// contains filtered or unexported methods
}

type EndPoint

type EndPoint interface {
	// get EndPoint ID
	ID() EndPointID
	// get endpoint type
	EndPointType() EndPointType
	// run event loop and serves client request.
	RunEventLoop(newSession NewSessionCallback)
	// check the endpoint has been closed
	IsClosed() bool
	// close the endpoint and free its resource
	Close()
	GetTaskPool() gxsync.GenericTaskPool
}

type EndPointID

type EndPointID = int32

type EndPointType

type EndPointType int32
const (
	TCP_CLIENT EndPointType = 2
	TCP_SERVER EndPointType = 7
)

func (EndPointType) String

func (x EndPointType) String() string

type EventListener

type EventListener interface {
	// invoked when session opened
	// If the return error is not nil, @Session will be closed.
	OnOpen(Session) error

	// invoked when session closed.
	OnClose(Session)

	// invoked when got error.
	OnError(Session, error)

	// invoked periodically, its period can be set by (Session)SetCronPeriod
	OnCron(Session)

	// invoked when getty received a package. Pls attention that do not handle long time
	// logic processing in this func. You'd better set the package's maximum length.
	// If the message's length is greater than it, u should should return err in
	// Reader{Read} and getty will close this connection soon.
	//
	// If ur logic processing in this func will take a long time, u should start a goroutine
	// pool(like working thread pool in cpp) to handle the processing asynchronously. Or u
	// can do the logic processing in other asynchronous way.
	// !!!In short, ur OnMessage callback func should return asap.
	//
	// If this is a udp event listener, the second parameter type is UDPContext.
	OnMessage(Session, interface{})
}

EventListener is used to process pkg that received from remote session

type MySQLEchoPkgHandler

type MySQLEchoPkgHandler struct {
}

func NewMySQLEchoPkgHandler

func NewMySQLEchoPkgHandler() *MySQLEchoPkgHandler

func (*MySQLEchoPkgHandler) Read

func (h *MySQLEchoPkgHandler) Read(ss Session, data []byte) (interface{}, int, error)

func (*MySQLEchoPkgHandler) Write

func (h *MySQLEchoPkgHandler) Write(ss Session, pkg interface{}) ([]byte, error)

type MySQLMessageHandler

type MySQLMessageHandler struct {
	XMySQLEngine *engine.XMySQLEngine
	// contains filtered or unexported fields
}

func NewMySQLMessageHandler

func NewMySQLMessageHandler(cfg *conf.Cfg) *MySQLMessageHandler

func (*MySQLMessageHandler) OnClose

func (m *MySQLMessageHandler) OnClose(session Session)

func (*MySQLMessageHandler) OnCron

func (m *MySQLMessageHandler) OnCron(session Session)

func (*MySQLMessageHandler) OnError

func (m *MySQLMessageHandler) OnError(session Session, err error)

func (*MySQLMessageHandler) OnMessage

func (m *MySQLMessageHandler) OnMessage(session Session, pkg interface{})

func (*MySQLMessageHandler) OnOpen

func (m *MySQLMessageHandler) OnOpen(session Session) error

type MySQLPackage

type MySQLPackage struct {
	Header MySQLPkgHeader
	Body   []byte
}

func (MySQLPackage) Marshal

func (p MySQLPackage) Marshal() (*bytes.Buffer, error)

func (*MySQLPackage) Unmarshal

func (p *MySQLPackage) Unmarshal(buf *bytes.Buffer) (int, error)

type MySQLPackageHandler

type MySQLPackageHandler struct {
}

func (*MySQLPackageHandler) Handle

func (h *MySQLPackageHandler) Handle(session Session, pkg *MySQLPackage) error

type MySQLPkgHeader

type MySQLPkgHeader struct {
	PacketLength []byte //3
	PacketId     byte
}

type MySQLServer

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

func NewMySQLServer

func NewMySQLServer(conf *conf.Cfg) *MySQLServer

func (*MySQLServer) Start

func (srv *MySQLServer) Start()

type MySQLServerSessionImpl

type MySQLServerSessionImpl struct {
	innodb.MySQLServerSession
	// contains filtered or unexported fields
}

MySQL serverimpl session 本地存储

func (*MySQLServerSessionImpl) ClearValue

func (s *MySQLServerSessionImpl) ClearValue(key fmt.Stringer)

func (*MySQLServerSessionImpl) Close

func (s *MySQLServerSessionImpl) Close() error

Close function does some clean work when session end.

func (*MySQLServerSessionImpl) Commit

func (m *MySQLServerSessionImpl) Commit()

func (*MySQLServerSessionImpl) GetCurrentDataBase

func (m *MySQLServerSessionImpl) GetCurrentDataBase() string

func (*MySQLServerSessionImpl) GetLastActiveTime

func (m *MySQLServerSessionImpl) GetLastActiveTime() time.Time

func (*MySQLServerSessionImpl) GetSessionVars

func (s *MySQLServerSessionImpl) GetSessionVars() *variable.SessionVars

GetSessionVars implements the context.Context interface.

func (*MySQLServerSessionImpl) GoCtx

func (*MySQLServerSessionImpl) NewTxn

func (m *MySQLServerSessionImpl) NewTxn() error

NewTxn creates a new transaction for further execution. If old transaction is valid, it is committed first. It's used in BEGIN statement and DDL statements to commit old transaction.

func (*MySQLServerSessionImpl) ParseOneSQL

func (s *MySQLServerSessionImpl) ParseOneSQL(sql, charset, collation string) (ast.StmtNode, error)

func (*MySQLServerSessionImpl) ParseSQL

func (s *MySQLServerSessionImpl) ParseSQL(sql, charset, collation string) ([]ast.StmtNode, error)

func (*MySQLServerSessionImpl) PrepareTxnCtx

func (m *MySQLServerSessionImpl) PrepareTxnCtx()

func (MySQLServerSessionImpl) SendError

func (m MySQLServerSessionImpl) SendError(error *mysql.SQLError)

func (*MySQLServerSessionImpl) SendHandleOk

func (m *MySQLServerSessionImpl) SendHandleOk()

func (*MySQLServerSessionImpl) SendOK

func (m *MySQLServerSessionImpl) SendOK()

func (MySQLServerSessionImpl) SetCurrentDatabase

func (m MySQLServerSessionImpl) SetCurrentDatabase(name string)

func (*MySQLServerSessionImpl) SetValue

func (s *MySQLServerSessionImpl) SetValue(key fmt.Stringer, value interface{})

func (*MySQLServerSessionImpl) Status

func (s *MySQLServerSessionImpl) Status() uint16

func (*MySQLServerSessionImpl) String

func (s *MySQLServerSessionImpl) String() string

func (*MySQLServerSessionImpl) Txn

func (*MySQLServerSessionImpl) Value

func (s *MySQLServerSessionImpl) Value(key fmt.Stringer) interface{}

type MysqlTCPConn

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

func (*MysqlTCPConn) GetActive

func (c *MysqlTCPConn) GetActive() time.Time

func (*MysqlTCPConn) ID

func (c *MysqlTCPConn) ID() uint32

func (*MysqlTCPConn) LocalAddr

func (c *MysqlTCPConn) LocalAddr() string

func (*MysqlTCPConn) RemoteAddr

func (c *MysqlTCPConn) RemoteAddr() string

func (*MysqlTCPConn) SetCompressType

func (t *MysqlTCPConn) SetCompressType(c CompressType)

set compress type(tcp: zip/snappy, websocket:zip)

func (*MysqlTCPConn) SetReadTimeout

func (c *MysqlTCPConn) SetReadTimeout(rTimeout time.Duration)

Pls do not set read deadline for websocket connection. AlexStocks 20180310 gorilla/websocket/conn.go:NextReader will always fail when got a timeout error.

Pls do not set read deadline when using compression. AlexStocks 20180314.

func (*MysqlTCPConn) SetWriteTimeout

func (c *MysqlTCPConn) SetWriteTimeout(wTimeout time.Duration)

Pls do not set write deadline for websocket connection. AlexStocks 20180310 gorilla/websocket/conn.go:NextWriter will always fail when got a timeout error.

Pls do not set write deadline when using compression. AlexStocks 20180314.

func (*MysqlTCPConn) UpdateActive

func (c *MysqlTCPConn) UpdateActive()

type NewSessionCallback

type NewSessionCallback func(Session) error

NewSessionCallback will be invoked when serverimpl accepts a new client connection or client connects to serverimpl successfully. If there are too many client connections or u do not want to connect a serverimpl again, u can return non-nil error. And then getty will close the new session.

type PackageHandler

type PackageHandler interface {
	Handle(Session, *MySQLPackage) error
}

type ReadWriter

type ReadWriter interface {
	Reader
	Writer
}

package handler interface

type Reader

type Reader interface {
	// Parse tcp/udp/websocket pkg from buffer_pool and if possible return a complete pkg.
	// When receiving a tcp network streaming segment, there are 4 cases as following:
	// case 1: a error found in the streaming segment;
	// case 2: can not unmarshal a pkg header from the streaming segment;
	// case 3: unmarshal a pkg header but can not unmarshal a pkg from the streaming segment;
	// case 4: just unmarshal a pkg from the streaming segment;
	// case 5: unmarshal more than one pkg from the streaming segment;
	//
	// The return value is (nil, 0, error) as case 1.
	// The return value is (nil, 0, nil) as case 2.
	// The return value is (nil, pkgLen, nil) as case 3.
	// The return value is (pkg, pkgLen, nil) as case 4.
	// The handleTcpPackage may invoke func Read many times as case 5.
	Read(Session, []byte) (interface{}, int, error)
}

Reader is used to unmarshal a complete pkg from buffer_pool

type Server

type Server interface {
	EndPoint
}

Server interface

func NewTCPServer

func NewTCPServer(opts ...ServerOption) Server

NewTCPServer builds a tcp serverimpl.

type ServerOption

type ServerOption func(*ServerOptions)

func WithLocalAddress

func WithLocalAddress(addr string) ServerOption

@addr serverimpl listen address.

func WithServerSslEnabled

func WithServerSslEnabled(sslEnabled bool) ServerOption

@WithSslEnabled enable use tls

func WithServerTaskPool

func WithServerTaskPool(pool gxsync.GenericTaskPool) ServerOption

@pool serverimpl task pool.

func WithServerTlsConfigBuilder

func WithServerTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ServerOption

@WithServerKeyCertChainPath sslConfig is tls config

func WithWebsocketServerCert

func WithWebsocketServerCert(cert string) ServerOption

@cert: serverimpl certificate file

func WithWebsocketServerPath

func WithWebsocketServerPath(path string) ServerOption

@path: websocket request url path

func WithWebsocketServerPrivateKey

func WithWebsocketServerPrivateKey(key string) ServerOption

@key: serverimpl private key(contains its public key)

func WithWebsocketServerRootCert

func WithWebsocketServerRootCert(cert string) ServerOption

@cert is the root certificate file to verify the legitimacy of serverimpl

type ServerOptions

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

type ServerTlsConfigBuilder

type ServerTlsConfigBuilder struct {
	ServerKeyCertChainPath        string
	ServerPrivateKeyPath          string
	ServerKeyPassword             string
	ServerTrustCertCollectionPath string
}

ServerTlsConfigBuilder impl TlsConfigBuilder for serverimpl

func (*ServerTlsConfigBuilder) BuildTlsConfig

func (s *ServerTlsConfigBuilder) BuildTlsConfig() (*tls.Config, error)

BuildTlsConfig impl TlsConfigBuilder method

type Session

type Session interface {
	Connection
	Reset()
	Conn() net.Conn
	Stat() string
	IsClosed() bool
	// get endpoint type
	EndPoint() EndPoint

	SetMaxMsgLen(int)
	SetName(string)
	SetEventListener(EventListener)
	SetPkgHandler(ReadWriter)
	SetReader(Reader)
	SetWriter(Writer)
	SetCronPeriod(int)

	SetWQLen(int)
	SetWaitTime(time.Duration)

	GetAttribute(interface{}) interface{}
	SetAttribute(interface{}, interface{})
	RemoveAttribute(interface{})

	// the Writer will invoke this function. Pls attention that if timeout is less than 0, WritePkg will send @pkg asap.
	// for udp session, the first parameter should be UDPContext.
	WritePkg(pkg interface{}, timeout time.Duration) error
	WriteBytes([]byte) error
	WriteBytesArray(...[]byte) error
	Close()
}

type TlsConfigBuilder

type TlsConfigBuilder interface {
	BuildTlsConfig() (*tls.Config, error)
}

TlsConfigBuilder tls config builder interface

type Writer

type Writer interface {
	// if @Session is udpGettySession, the second parameter is UDPContext.
	Write(Session, interface{}) ([]byte, error)
}

Writer is used to marshal pkg and write to session

Jump to

Keyboard shortcuts

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