Removed evio option

This commit is contained in:
tidwall 2019-04-26 11:50:49 -07:00
parent 63ff185401
commit 3ae59274e3
61 changed files with 46 additions and 4756 deletions

20
Gopkg.lock generated
View File

@ -128,14 +128,6 @@
pruneopts = ""
revision = "c2b33e84"
[[projects]]
digest = "1:be1d3b7623f11b628068933282015f3dbcd522fa8e6b16d2931edffd42ef2c0b"
name = "github.com/kavu/go_reuseport"
packages = ["."]
pruneopts = ""
revision = "ffa96de2479e10ecd06aca8069bf9c55a86701b5"
version = "v1.4.0"
[[projects]]
branch = "master"
digest = "1:75dddee0eb82002b5aff6937fdf6d544b85322d2414524a521768fe4b4e5ed3d"
@ -228,17 +220,6 @@
revision = "6249481c29c2cd96f53b691b74ac1893f72774c2"
version = "v1.1.0"
[[projects]]
digest = "1:91acf4d86b348c1f1832336836035373b047ffcb16a0fde066bd531bbe3452b2"
name = "github.com/tidwall/evio"
packages = [
".",
"internal",
]
pruneopts = ""
revision = "b353be3a765785dafabbb63a7b25aadec3533946"
version = "v1.0.2"
[[projects]]
digest = "1:cdab3bce90a53a124ac3982719abde77d779e961d9c180e55c23fb74fc62563a"
name = "github.com/tidwall/geojson"
@ -482,7 +463,6 @@
"github.com/tidwall/boxtree/d2",
"github.com/tidwall/btree",
"github.com/tidwall/buntdb",
"github.com/tidwall/evio",
"github.com/tidwall/geojson",
"github.com/tidwall/geojson/geo",
"github.com/tidwall/geojson/geometry",

View File

@ -22,8 +22,7 @@
required = [
"github.com/tidwall/lotsa",
"github.com/mmcloughlin/geohash",
"github.com/tidwall/evio"
"github.com/mmcloughlin/geohash"
]
[[constraint]]

View File

@ -101,7 +101,6 @@ Advanced Options:
--http-transport yes/no : HTTP transport (default: yes)
--protected-mode yes/no : protected mode (default: yes)
--threads num : number of network threads (default: num cores)
--evio yes/no : use the evio package (default: no)
--nohup : do not exist on SIGHUP
Developer Options:
@ -153,6 +152,8 @@ Developer Options:
return
}
var showEvioDisabled bool
// parse non standard args.
nargs := []string{os.Args[0]}
for i := 1; i < len(os.Args); i++ {
@ -243,11 +244,8 @@ Developer Options:
i++
if i < len(os.Args) {
switch strings.ToLower(os.Args[i]) {
case "no":
core.Evio = false
continue
case "yes":
core.Evio = true
case "no", "yes":
showEvioDisabled = true
continue
}
}
@ -408,6 +406,10 @@ Developer Options:
if pidferr != nil {
log.Warnf("pidfile: %v", pidferr)
}
if showEvioDisabled {
// we don't currently support evio in Tile38
log.Warnf("evio is not currently supported")
}
if err := server.Serve(host, port, dir, httpTransport); err != nil {
log.Fatal(err)
}

View File

@ -20,6 +20,3 @@ var QueueFileName = ""
// NumThreads is the number of network threads to use.
var NumThreads int
// Evio set the networking to use the evio package.
var Evio = false

View File

@ -10,20 +10,19 @@ import (
"sync"
"time"
"github.com/tidwall/evio"
"github.com/tidwall/resp"
)
// Client is an remote connection into to Tile38
type Client struct {
id int // unique id
replPort int // the known replication port for follower connections
authd bool // client has been authenticated
outputType Type // Null, JSON, or RESP
remoteAddr string // original remote address
in evio.InputStream // input stream
pr PipelineReader // command reader
out []byte // output write buffer
id int // unique id
replPort int // the known replication port for follower connections
authd bool // client has been authenticated
outputType Type // Null, JSON, or RESP
remoteAddr string // original remote address
in InputStream // input stream
pr PipelineReader // command reader
out []byte // output write buffer
goLiveErr error // error type used for going line
goLiveMsg *Message // last message for go live

View File

@ -24,7 +24,6 @@ import (
"github.com/tidwall/boxtree/d2"
"github.com/tidwall/buntdb"
"github.com/tidwall/evio"
"github.com/tidwall/geojson"
"github.com/tidwall/geojson/geometry"
"github.com/tidwall/redcon"
@ -39,6 +38,7 @@ import (
)
var errOOM = errors.New("OOM command not allowed when used memory > 'maxmemory'")
func errTimeoutOnCmd(cmd string) error {
return fmt.Errorf("timeout not supported for '%s'", cmd)
}
@ -284,9 +284,6 @@ func Serve(host string, port int, dir string, http bool) error {
}()
// Start the network server
if core.Evio {
return server.evioServe()
}
return server.netServe()
}
@ -304,203 +301,6 @@ func (server *Server) isProtected() bool {
return is
}
func (server *Server) evioServe() error {
var events evio.Events
if core.NumThreads == 0 {
events.NumLoops = -1
} else {
events.NumLoops = core.NumThreads
}
events.LoadBalance = evio.LeastConnections
events.Serving = func(eserver evio.Server) (action evio.Action) {
if eserver.NumLoops == 1 {
log.Infof("Running single-threaded")
} else {
log.Infof("Running on %d threads", eserver.NumLoops)
}
for _, addr := range eserver.Addrs {
log.Infof("Ready to accept connections at %s",
addr)
}
return
}
var clientID int64
events.Opened = func(econn evio.Conn) (out []byte, opts evio.Options, action evio.Action) {
// create the client
client := new(Client)
client.id = int(atomic.AddInt64(&clientID, 1))
client.opened = time.Now()
client.remoteAddr = econn.RemoteAddr().String()
// keep track of the client
econn.SetContext(client)
// add client to server map
server.connsmu.Lock()
server.conns[client.id] = client
server.connsmu.Unlock()
server.statsTotalConns.add(1)
// set the client keep-alive, if needed
if server.config.keepAlive() > 0 {
opts.TCPKeepAlive = time.Duration(server.config.keepAlive()) * time.Second
}
log.Debugf("Opened connection: %s", client.remoteAddr)
// check if the connection is protected
if !strings.HasPrefix(client.remoteAddr, "127.0.0.1:") &&
!strings.HasPrefix(client.remoteAddr, "[::1]:") {
if server.isProtected() {
// This is a protected server. Only loopback is allowed.
out = append(out, deniedMessage...)
action = evio.Close
return
}
}
return
}
events.Closed = func(econn evio.Conn, err error) (action evio.Action) {
// load the client
client := econn.Context().(*Client)
// delete from server map
server.connsmu.Lock()
delete(server.conns, client.id)
server.connsmu.Unlock()
log.Debugf("Closed connection: %s", client.remoteAddr)
return
}
events.Data = func(econn evio.Conn, in []byte) (out []byte, action evio.Action) {
// load the client
client := econn.Context().(*Client)
// read the payload packet from the client input stream.
packet := client.in.Begin(in)
// load the pipeline reader
pr := &client.pr
rdbuf := bytes.NewBuffer(packet)
pr.rd = rdbuf
pr.wr = client
msgs, err := pr.ReadMessages()
if err != nil {
log.Error(err)
action = evio.Close
return
}
for _, msg := range msgs {
// Just closing connection if we have deprecated HTTP or WS connection,
// And --http-transport = false
if !server.http && (msg.ConnType == WebSocket ||
msg.ConnType == HTTP) {
action = evio.Close
break
}
if msg != nil && msg.Command() != "" {
if client.outputType != Null {
msg.OutputType = client.outputType
}
if msg.Command() == "quit" {
if msg.OutputType == RESP {
io.WriteString(client, "+OK\r\n")
}
action = evio.Close
break
}
// increment last used
client.mu.Lock()
client.last = time.Now()
client.mu.Unlock()
// update total command count
server.statsTotalCommands.add(1)
// handle the command
err := server.handleInputCommand(client, msg)
if err != nil {
if err.Error() == goingLive {
client.goLiveErr = err
client.goLiveMsg = msg
action = evio.Detach
return
}
log.Error(err)
action = evio.Close
return
}
client.outputType = msg.OutputType
} else {
client.Write([]byte("HTTP/1.1 500 Bad Request\r\nConnection: close\r\n\r\n"))
action = evio.Close
break
}
if msg.ConnType == HTTP || msg.ConnType == WebSocket {
action = evio.Close
break
}
}
packet = packet[len(packet)-rdbuf.Len():]
client.in.End(packet)
out = client.out
client.out = nil
return
}
events.Detached = func(econn evio.Conn, rwc io.ReadWriteCloser) (action evio.Action) {
client := econn.Context().(*Client)
client.conn = rwc
if len(client.out) > 0 {
rwc.Write(client.out)
client.out = nil
}
client.in = evio.InputStream{}
client.pr.rd = rwc
client.pr.wr = rwc
log.Debugf("Detached connection: %s", client.remoteAddr)
go func() {
defer func() {
// close connection
rwc.Close()
server.connsmu.Lock()
delete(server.conns, client.id)
server.connsmu.Unlock()
log.Debugf("Closed connection: %s", client.remoteAddr)
}()
err := server.goLive(
client.goLiveErr,
&liveConn{econn.RemoteAddr(), rwc},
&client.pr,
client.goLiveMsg,
client.goLiveMsg.ConnType == WebSocket,
)
if err != nil {
log.Error(err)
}
}()
return
}
events.PreWrite = func() {
if atomic.LoadInt32(&server.aofdirty) != 0 {
server.mu.Lock()
defer server.mu.Unlock()
server.flushAOF(false)
atomic.StoreInt32(&server.aofdirty, 1)
}
}
return evio.Serve(events, fmt.Sprintf("%s:%d", server.host, server.port))
}
func (server *Server) netServe() error {
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", server.host, server.port))
if err != nil {
@ -623,7 +423,7 @@ func (server *Server) netServe() error {
client.conn.Write(client.out)
client.out = nil
}
client.in = evio.InputStream{}
client.in = InputStream{}
client.pr.rd = rwc
client.pr.wr = rwc
log.Debugf("Detached connection: %s", client.remoteAddr)
@ -1056,7 +856,7 @@ func (server *Server) handleInputCommand(client *Client, msg *Message) error {
if msg.Deadline != nil {
if write {
res = NOMessage
err = errTimeoutOnCmd(msg.Command())
err = errTimeoutOnCmd(msg.Command())
return
}
defer func() {
@ -1639,3 +1439,29 @@ reading:
}
return &Message{Args: args, ConnType: Native, OutputType: JSON}, nil
}
// InputStream is a helper type for managing input streams from inside
// the Data event.
type InputStream struct{ b []byte }
// Begin accepts a new packet and returns a working sequence of
// unprocessed bytes.
func (is *InputStream) Begin(packet []byte) (data []byte) {
data = packet
if len(is.b) > 0 {
is.b = append(is.b, data...)
data = is.b
}
return data
}
// End shifts the stream to match the unprocessed data.
func (is *InputStream) End(data []byte) {
if len(data) > 0 {
if len(data) != len(is.b) {
is.b = append(is.b[:0], data...)
}
} else if len(is.b) > 0 {
is.b = is.b[:0]
}
}

View File

@ -1,14 +0,0 @@
version: 2
jobs:
build:
docker:
- image: circleci/golang:1.8
working_directory: /go/src/github.com/kavu/go_reuseport
steps:
- checkout
- run: go get -v -t -d ./...
- run: go test -v -cover ./...
- run: go test -v -cover -race ./... -coverprofile=coverage.txt -covermode=atomic
- run: go test -v -cover -race -benchmem -benchtime=5s -bench=.

View File

@ -1,23 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
.DS_Store

View File

@ -1,30 +0,0 @@
dist: trusty
sudo: true
language: go
go:
- "1.6"
- "1.7"
- "1.8"
- "1.9"
- "1.10"
- "1.11"
- tip
os:
- linux
- osx
before_install:
- uname -a
script: ./test.bash
matrix:
allow_failures:
- os: osx
- go: tip
after_success:
- bash <(curl -s https://codecov.io/bash)

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Max Riveiro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,9 +0,0 @@
lint:
@gometalinter \
--disable=errcheck \
--disable=dupl \
--min-const-length=5 \
--min-confidence=0.25 \
--cyclo-over=20 \
--enable=unused \
--deadline=100s

View File

@ -1,48 +0,0 @@
# GO_REUSEPORT
[![Build Status](https://travis-ci.org/kavu/go_reuseport.png?branch=master)](https://travis-ci.org/kavu/go_reuseport)
[![codecov](https://codecov.io/gh/kavu/go_reuseport/branch/master/graph/badge.svg)](https://codecov.io/gh/kavu/go_reuseport)
[![GoDoc](https://godoc.org/github.com/kavu/go_reuseport?status.png)](https://godoc.org/github.com/kavu/go_reuseport)
**GO_REUSEPORT** is a little expirement to create a `net.Listener` that supports [SO_REUSEPORT](http://lwn.net/Articles/542629/) socket option.
For now, Darwin and Linux (from 3.9) systems are supported. I'll be pleased if you'll test other systems and tell me the results.
documentation on [godoc.org](http://godoc.org/github.com/kavu/go_reuseport "go_reuseport documentation").
## Example ##
```go
package main
import (
"fmt"
"html"
"net/http"
"os"
"runtime"
"github.com/kavu/go_reuseport"
)
func main() {
listener, err := reuseport.Listen("tcp", "localhost:8881")
if err != nil {
panic(err)
}
defer listener.Close()
server := &http.Server{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(os.Getgid())
fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
})
panic(server.Serve(listener))
}
```
Now you can run several instances of this tiny server without `Address already in use` errors.
## Thanks
Inspired by [Artur Siekielski](https://github.com/aartur) [post](http://freeprogrammersblog.vhex.net/post/linux-39-introdued-new-way-of-writing-socket-servers/2) about `SO_REUSEPORT`.

View File

@ -1 +0,0 @@
module github.com/kavu/go_reuseport

View File

@ -1,50 +0,0 @@
// +build linux darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Package reuseport provides a function that returns a net.Listener powered
// by a net.FileListener with a SO_REUSEPORT option set to the socket.
package reuseport
import (
"errors"
"fmt"
"net"
"os"
"syscall"
)
const fileNameTemplate = "reuseport.%d.%s.%s"
var errUnsupportedProtocol = errors.New("only tcp, tcp4, tcp6, udp, udp4, udp6 are supported")
// getSockaddr parses protocol and address and returns implementor
// of syscall.Sockaddr: syscall.SockaddrInet4 or syscall.SockaddrInet6.
func getSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err error) {
switch proto {
case "tcp", "tcp4", "tcp6":
return getTCPSockaddr(proto, addr)
case "udp", "udp4", "udp6":
return getUDPSockaddr(proto, addr)
default:
return nil, -1, errUnsupportedProtocol
}
}
func getSocketFileName(proto, addr string) string {
return fmt.Sprintf(fileNameTemplate, os.Getpid(), proto, addr)
}
// Listen function is an alias for NewReusablePortListener.
func Listen(proto, addr string) (l net.Listener, err error) {
return NewReusablePortListener(proto, addr)
}
// ListenPacket is an alias for NewReusablePortPacketConn.
func ListenPacket(proto, addr string) (l net.PacketConn, err error) {
return NewReusablePortPacketConn(proto, addr)
}

View File

@ -1,44 +0,0 @@
// +build darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Ma Weiwei, Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import (
"runtime"
"syscall"
)
var reusePort = syscall.SO_REUSEPORT
func maxListenerBacklog() int {
var (
n uint32
err error
)
switch runtime.GOOS {
case "darwin", "freebsd":
n, err = syscall.SysctlUint32("kern.ipc.somaxconn")
case "netbsd":
// NOTE: NetBSD has no somaxconn-like kernel state so far
case "openbsd":
n, err = syscall.SysctlUint32("kern.somaxconn")
}
if n == 0 || err != nil {
return syscall.SOMAXCONN
}
// FreeBSD stores the backlog in a uint16, as does Linux.
// Assume the other BSDs do too. Truncate number to avoid wrapping.
// See issue 5030.
if n > 1<<16-1 {
n = 1<<16 - 1
}
return int(n)
}

View File

@ -1,52 +0,0 @@
// +build linux
// Copyright (C) 2017 Ma Weiwei, Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import (
"bufio"
"os"
"strconv"
"strings"
"syscall"
)
var reusePort = 0x0F
func maxListenerBacklog() int {
fd, err := os.Open("/proc/sys/net/core/somaxconn")
if err != nil {
return syscall.SOMAXCONN
}
defer fd.Close()
rd := bufio.NewReader(fd)
line, err := rd.ReadString('\n')
if err != nil {
return syscall.SOMAXCONN
}
f := strings.Fields(line)
if len(f) < 1 {
return syscall.SOMAXCONN
}
n, err := strconv.Atoi(f[0])
if err != nil || n == 0 {
return syscall.SOMAXCONN
}
// Linux stores the backlog in a uint16.
// Truncate number to avoid wrapping.
// See issue 5030.
if n > 1<<16-1 {
n = 1<<16 - 1
}
return n
}

View File

@ -1,19 +0,0 @@
// +build windows
// Copyright (C) 2017 Ma Weiwei, Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import "net"
func NewReusablePortListener(proto, addr string) (net.Listener, error) {
return net.Listen(proto, addr)
}
func NewReusablePortPacketConn(proto, addr string) (net.PacketConn, error) {
return net.ListenPacket(proto, addr)
}

View File

@ -1,143 +0,0 @@
// +build linux darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import (
"errors"
"net"
"os"
"syscall"
)
var (
listenerBacklogMaxSize = maxListenerBacklog()
errUnsupportedTCPProtocol = errors.New("only tcp, tcp4, tcp6 are supported")
)
func getTCPSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err error) {
var tcp *net.TCPAddr
tcp, err = net.ResolveTCPAddr(proto, addr)
if err != nil && tcp.IP != nil {
return nil, -1, err
}
tcpVersion, err := determineTCPProto(proto, tcp)
if err != nil {
return nil, -1, err
}
switch tcpVersion {
case "tcp":
return &syscall.SockaddrInet4{Port: tcp.Port}, syscall.AF_INET, nil
case "tcp4":
sa := &syscall.SockaddrInet4{Port: tcp.Port}
if tcp.IP != nil {
copy(sa.Addr[:], tcp.IP[12:16]) // copy last 4 bytes of slice to array
}
return sa, syscall.AF_INET, nil
case "tcp6":
sa := &syscall.SockaddrInet6{Port: tcp.Port}
if tcp.IP != nil {
copy(sa.Addr[:], tcp.IP) // copy all bytes of slice to array
}
if tcp.Zone != "" {
iface, err := net.InterfaceByName(tcp.Zone)
if err != nil {
return nil, -1, err
}
sa.ZoneId = uint32(iface.Index)
}
return sa, syscall.AF_INET6, nil
}
return nil, -1, errUnsupportedProtocol
}
func determineTCPProto(proto string, ip *net.TCPAddr) (string, error) {
// If the protocol is set to "tcp", we try to determine the actual protocol
// version from the size of the resolved IP address. Otherwise, we simple use
// the protcol given to us by the caller.
if ip.IP.To4() != nil {
return "tcp4", nil
}
if ip.IP.To16() != nil {
return "tcp6", nil
}
switch proto {
case "tcp", "tcp4", "tcp6":
return proto, nil
}
return "", errUnsupportedTCPProtocol
}
// NewReusablePortListener returns net.FileListener that created from
// a file discriptor for a socket with SO_REUSEPORT option.
func NewReusablePortListener(proto, addr string) (l net.Listener, err error) {
var (
soType, fd int
file *os.File
sockaddr syscall.Sockaddr
)
if sockaddr, soType, err = getSockaddr(proto, addr); err != nil {
return nil, err
}
syscall.ForkLock.RLock()
if fd, err = syscall.Socket(soType, syscall.SOCK_STREAM, syscall.IPPROTO_TCP); err != nil {
syscall.ForkLock.RUnlock()
return nil, err
}
syscall.ForkLock.RUnlock()
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
syscall.Close(fd)
return nil, err
}
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, reusePort, 1); err != nil {
syscall.Close(fd)
return nil, err
}
if err = syscall.Bind(fd, sockaddr); err != nil {
syscall.Close(fd)
return nil, err
}
// Set backlog size to the maximum
if err = syscall.Listen(fd, listenerBacklogMaxSize); err != nil {
syscall.Close(fd)
return nil, err
}
file = os.NewFile(uintptr(fd), getSocketFileName(proto, addr))
if l, err = net.FileListener(file); err != nil {
file.Close()
return nil, err
}
if err = file.Close(); err != nil {
return nil, err
}
return l, err
}

View File

@ -1,218 +0,0 @@
// +build linux darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import (
"fmt"
"html"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
)
const (
httpServerOneResponse = "1"
httpServerTwoResponse = "2"
)
var (
httpServerOne = NewHTTPServer(httpServerOneResponse)
httpServerTwo = NewHTTPServer(httpServerTwoResponse)
)
func NewHTTPServer(resp string) *httptest.Server {
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, resp)
}))
}
func TestNewReusablePortListener(t *testing.T) {
listenerOne, err := NewReusablePortListener("tcp4", "localhost:10081")
if err != nil {
t.Error(err)
}
defer listenerOne.Close()
listenerTwo, err := NewReusablePortListener("tcp", "127.0.0.1:10081")
if err != nil {
t.Error(err)
}
defer listenerTwo.Close()
listenerThree, err := NewReusablePortListener("tcp6", "[::1]:10081")
if err != nil {
t.Error(err)
}
defer listenerThree.Close()
listenerFour, err := NewReusablePortListener("tcp6", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFour.Close()
listenerFive, err := NewReusablePortListener("tcp4", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFive.Close()
listenerSix, err := NewReusablePortListener("tcp", ":10081")
if err != nil {
t.Error(err)
}
defer listenerSix.Close()
}
func TestListen(t *testing.T) {
listenerOne, err := Listen("tcp4", "localhost:10081")
if err != nil {
t.Error(err)
}
defer listenerOne.Close()
listenerTwo, err := Listen("tcp", "127.0.0.1:10081")
if err != nil {
t.Error(err)
}
defer listenerTwo.Close()
listenerThree, err := Listen("tcp6", "[::1]:10081")
if err != nil {
t.Error(err)
}
defer listenerThree.Close()
listenerFour, err := Listen("tcp6", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFour.Close()
listenerFive, err := Listen("tcp4", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFive.Close()
listenerSix, err := Listen("tcp", ":10081")
if err != nil {
t.Error(err)
}
defer listenerSix.Close()
}
func TestNewReusablePortServers(t *testing.T) {
listenerOne, err := NewReusablePortListener("tcp4", "localhost:10081")
if err != nil {
t.Error(err)
}
defer listenerOne.Close()
listenerTwo, err := NewReusablePortListener("tcp6", ":10081")
if err != nil {
t.Error(err)
}
defer listenerTwo.Close()
httpServerOne.Listener = listenerOne
httpServerTwo.Listener = listenerTwo
httpServerOne.Start()
httpServerTwo.Start()
// Server One — First Response
resp1, err := http.Get(httpServerOne.URL)
if err != nil {
t.Error(err)
}
body1, err := ioutil.ReadAll(resp1.Body)
resp1.Body.Close()
if err != nil {
t.Error(err)
}
if string(body1) != httpServerOneResponse && string(body1) != httpServerTwoResponse {
t.Errorf("Expected %#v or %#v, got %#v.", httpServerOneResponse, httpServerTwoResponse, string(body1))
}
// Server Two — First Response
resp2, err := http.Get(httpServerTwo.URL)
if err != nil {
t.Error(err)
}
body2, err := ioutil.ReadAll(resp2.Body)
resp1.Body.Close()
if err != nil {
t.Error(err)
}
if string(body2) != httpServerOneResponse && string(body2) != httpServerTwoResponse {
t.Errorf("Expected %#v or %#v, got %#v.", httpServerOneResponse, httpServerTwoResponse, string(body2))
}
httpServerTwo.Close()
// Server One — Second Response
resp3, err := http.Get(httpServerOne.URL)
if err != nil {
t.Error(err)
}
body3, err := ioutil.ReadAll(resp3.Body)
resp1.Body.Close()
if err != nil {
t.Error(err)
}
if string(body3) != httpServerOneResponse {
t.Errorf("Expected %#v, got %#v.", httpServerOneResponse, string(body3))
}
// Server One — Third Response
resp5, err := http.Get(httpServerOne.URL)
if err != nil {
t.Error(err)
}
body5, err := ioutil.ReadAll(resp5.Body)
resp1.Body.Close()
if err != nil {
t.Error(err)
}
if string(body5) != httpServerOneResponse {
t.Errorf("Expected %#v, got %#v.", httpServerOneResponse, string(body5))
}
httpServerOne.Close()
}
func BenchmarkNewReusablePortListener(b *testing.B) {
for i := 0; i < b.N; i++ {
listener, err := NewReusablePortListener("tcp", ":10081")
if err != nil {
b.Error(err)
} else {
listener.Close()
}
}
}
func ExampleNewReusablePortListener() {
listener, err := NewReusablePortListener("tcp", ":8881")
if err != nil {
panic(err)
}
defer listener.Close()
server := &http.Server{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(os.Getgid())
fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
})
panic(server.Serve(listener))
}

View File

@ -1,22 +0,0 @@
#!/bin/bash
set -e
# Thanks to IPFS team
if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
if [[ "$TRAVIS_SUDO" == true ]]; then
# Ensure that IPv6 is enabled.
# While this is unsupported by TravisCI, it still works for localhost.
sudo sysctl -w net.ipv6.conf.lo.disable_ipv6=0
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=0
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=0
fi
else
# OSX has a default file limit of 256, for some tests we need a
# maximum of 8192.
ulimit -Sn 8192
fi
go test -v -cover ./...
go test -v -cover -race ./... -coverprofile=coverage.txt -covermode=atomic
go test -v -cover -race -benchmem -benchtime=5s -bench=.

View File

@ -1,143 +0,0 @@
// +build linux darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import (
"errors"
"net"
"os"
"syscall"
)
var errUnsupportedUDPProtocol = errors.New("only udp, udp4, udp6 are supported")
func getUDPSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err error) {
var udp *net.UDPAddr
udp, err = net.ResolveUDPAddr(proto, addr)
if err != nil && udp.IP != nil {
return nil, -1, err
}
udpVersion, err := determineUDPProto(proto, udp)
if err != nil {
return nil, -1, err
}
switch udpVersion {
case "udp":
return &syscall.SockaddrInet4{Port: udp.Port}, syscall.AF_INET, nil
case "udp4":
sa := &syscall.SockaddrInet4{Port: udp.Port}
if udp.IP != nil {
copy(sa.Addr[:], udp.IP[12:16]) // copy last 4 bytes of slice to array
}
return sa, syscall.AF_INET, nil
case "udp6":
sa := &syscall.SockaddrInet6{Port: udp.Port}
if udp.IP != nil {
copy(sa.Addr[:], udp.IP) // copy all bytes of slice to array
}
if udp.Zone != "" {
iface, err := net.InterfaceByName(udp.Zone)
if err != nil {
return nil, -1, err
}
sa.ZoneId = uint32(iface.Index)
}
return sa, syscall.AF_INET6, nil
}
return nil, -1, errUnsupportedProtocol
}
func determineUDPProto(proto string, ip *net.UDPAddr) (string, error) {
// If the protocol is set to "udp", we try to determine the actual protocol
// version from the size of the resolved IP address. Otherwise, we simple use
// the protcol given to us by the caller.
if ip.IP.To4() != nil {
return "udp4", nil
}
if ip.IP.To16() != nil {
return "udp6", nil
}
switch proto {
case "udp", "udp4", "udp6":
return proto, nil
}
return "", errUnsupportedUDPProtocol
}
// NewReusablePortPacketConn returns net.FilePacketConn that created from
// a file discriptor for a socket with SO_REUSEPORT option.
func NewReusablePortPacketConn(proto, addr string) (l net.PacketConn, err error) {
var (
soType, fd int
file *os.File
sockaddr syscall.Sockaddr
)
if sockaddr, soType, err = getSockaddr(proto, addr); err != nil {
return nil, err
}
syscall.ForkLock.RLock()
fd, err = syscall.Socket(soType, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
if err == nil {
syscall.CloseOnExec(fd)
}
syscall.ForkLock.RUnlock()
if err != nil {
syscall.Close(fd)
return nil, err
}
defer func() {
if err != nil {
syscall.Close(fd)
}
}()
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
return nil, err
}
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, reusePort, 1); err != nil {
return nil, err
}
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1); err != nil {
return nil, err
}
if err = syscall.Bind(fd, sockaddr); err != nil {
return nil, err
}
file = os.NewFile(uintptr(fd), getSocketFileName(proto, addr))
if l, err = net.FilePacketConn(file); err != nil {
return nil, err
}
if err = file.Close(); err != nil {
return nil, err
}
return l, err
}

View File

@ -1,99 +0,0 @@
// +build linux darwin dragonfly freebsd netbsd openbsd
// Copyright (C) 2017 Max Riveiro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package reuseport
import "testing"
func TestNewReusablePortPacketConn(t *testing.T) {
listenerOne, err := NewReusablePortPacketConn("udp4", "localhost:10082")
if err != nil {
t.Error(err)
}
defer listenerOne.Close()
listenerTwo, err := NewReusablePortPacketConn("udp", "127.0.0.1:10082")
if err != nil {
t.Error(err)
}
defer listenerTwo.Close()
listenerThree, err := NewReusablePortPacketConn("udp6", "[::1]:10082")
if err != nil {
t.Error(err)
}
defer listenerThree.Close()
listenerFour, err := NewReusablePortListener("udp6", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFour.Close()
listenerFive, err := NewReusablePortListener("udp4", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFive.Close()
listenerSix, err := NewReusablePortListener("udp", ":10081")
if err != nil {
t.Error(err)
}
defer listenerSix.Close()
}
func TestListenPacket(t *testing.T) {
listenerOne, err := ListenPacket("udp4", "localhost:10082")
if err != nil {
t.Error(err)
}
defer listenerOne.Close()
listenerTwo, err := ListenPacket("udp", "127.0.0.1:10082")
if err != nil {
t.Error(err)
}
defer listenerTwo.Close()
listenerThree, err := ListenPacket("udp6", "[::1]:10082")
if err != nil {
t.Error(err)
}
defer listenerThree.Close()
listenerFour, err := ListenPacket("udp6", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFour.Close()
listenerFive, err := ListenPacket("udp4", ":10081")
if err != nil {
t.Error(err)
}
defer listenerFive.Close()
listenerSix, err := ListenPacket("udp", ":10081")
if err != nil {
t.Error(err)
}
defer listenerSix.Close()
}
func BenchmarkNewReusableUDPPortListener(b *testing.B) {
for i := 0; i < b.N; i++ {
listener, err := NewReusablePortPacketConn("udp4", "localhost:10082")
if err != nil {
b.Error(err)
} else {
listener.Close()
}
}
}

View File

@ -1,2 +0,0 @@
language: go
script: go test -run none

View File

@ -1,20 +0,0 @@
The MIT License (MIT)
Copyright (c) 2017 Joshua J Baker
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,168 +0,0 @@
<p align="center">
<img
src="logo.png"
width="213" height="75" border="0" alt="evio">
<br>
<a href="https://travis-ci.org/tidwall/evio"><img src="https://img.shields.io/travis/tidwall/evio.svg?style=flat-square" alt="Build Status"></a>
<a href="https://godoc.org/github.com/tidwall/evio"><img src="https://img.shields.io/badge/api-reference-blue.svg?style=flat-square" alt="GoDoc"></a>
</p>
`evio` is an event loop networking framework that is fast and small. It makes direct [epoll](https://en.wikipedia.org/wiki/Epoll) and [kqueue](https://en.wikipedia.org/wiki/Kqueue) syscalls rather than using the standard Go [net](https://golang.org/pkg/net/) package, and works in a similar manner as [libuv](https://github.com/libuv/libuv) and [libevent](https://github.com/libevent/libevent).
The goal of this project is to create a server framework for Go that performs on par with [Redis](http://redis.io) and [Haproxy](http://www.haproxy.org) for packet handling. It was built to be the foundation for [Tile38](https://github.com/tidwall/tile38) and a future L7 proxy for Go.
*Please note: Evio should not be considered as a drop-in replacement for the standard Go net or net/http packages.*
## Features
- [Fast](#performance) single-threaded or [multithreaded](#multithreaded) event loop
- Built-in [load balancing](#load-balancing) options
- Simple API
- Low memory usage
- Supports tcp, [udp](#udp), and unix sockets
- Allows [multiple network binding](#multiple-addresses) on the same event loop
- Flexible [ticker](#ticker) event
- Fallback for non-epoll/kqueue operating systems by simulating events with the [net](https://golang.org/pkg/net/) package
- [SO_REUSEPORT](#so_reuseport) socket option
## Getting Started
### Installing
To start using evio, install Go and run `go get`:
```sh
$ go get -u github.com/tidwall/evio
```
This will retrieve the library.
### Usage
Starting a server is easy with `evio`. Just set up your events and pass them to the `Serve` function along with the binding address(es). Each connections is represented as an `evio.Conn` object that is passed to various events to differentiate the clients. At any point you can close a client or shutdown the server by return a `Close` or `Shutdown` action from an event.
Example echo server that binds to port 5000:
```go
package main
import "github.com/tidwall/evio"
func main() {
var events evio.Events
events.Data = func(c evio.Conn, in []byte) (out []byte, action evio.Action) {
out = in
return
}
if err := evio.Serve(events, "tcp://localhost:5000"); err != nil {
panic(err.Error())
}
}
```
Here the only event being used is `Data`, which fires when the server receives input data from a client.
The exact same input data is then passed through the output return value, which is then sent back to the client.
Connect to the echo server:
```sh
$ telnet localhost 5000
```
### Events
The event type has a bunch of handy events:
- `Serving` fires when the server is ready to accept new connections.
- `Opened` fires when a connection has opened.
- `Closed` fires when a connection has closed.
- `Detach` fires when a connection has been detached using the `Detach` return action.
- `Data` fires when the server receives new data from a connection.
- `Tick` fires immediately after the server starts and will fire again after a specified interval.
### Multiple addresses
A server can bind to multiple addresses and share the same event loop.
```go
evio.Serve(events, "tcp://192.168.0.10:5000", "unix://socket")
```
### Ticker
The `Tick` event fires ticks at a specified interval.
The first tick fires immediately after the `Serving` events.
```go
events.Tick = func() (delay time.Duration, action Action){
log.Printf("tick")
delay = time.Second
return
}
```
## UDP
The `Serve` function can bind to UDP addresses.
- All incoming and outgoing packets are not buffered and sent individually.
- The `Opened` and `Closed` events are not availble for UDP sockets, only the `Data` event.
## Multithreaded
The `events.NumLoops` options sets the number of loops to use for the server.
A value greater than 1 will effectively make the server multithreaded for multi-core machines.
Which means you must take care when synchonizing memory between event callbacks.
Setting to 0 or 1 will run the server as single-threaded.
Setting to -1 will automatically assign this value equal to `runtime.NumProcs()`.
## Load balancing
The `events.LoadBalance` options sets the load balancing method.
Load balancing is always a best effort to attempt to distribute the incoming connections between multiple loops.
This option is only available when `events.NumLoops` is set.
- `Random` requests that connections are randomly distributed.
- `RoundRobin` requests that connections are distributed to a loop in a round-robin fashion.
- `LeastConnections` assigns the next accepted connection to the loop with the least number of active connections.
## SO_REUSEPORT
Servers can utilize the [SO_REUSEPORT](https://lwn.net/Articles/542629/) option which allows multiple sockets on the same host to bind to the same port.
Just provide `reuseport=true` to an address:
```go
evio.Serve(events, "tcp://0.0.0.0:1234?reuseport=true"))
```
## More examples
Please check out the [examples](examples) subdirectory for a simplified [redis](examples/redis-server/main.go) clone, an [echo](examples/echo-server/main.go) server, and a very basic [http](examples/http-server/main.go) server.
To run an example:
```sh
$ go run examples/http-server/main.go
$ go run examples/redis-server/main.go
$ go run examples/echo-server/main.go
```
## Performance
### Benchmarks
These benchmarks were run on an ec2 c4.xlarge instance in single-threaded mode (GOMAXPROC=1) over Ipv4 localhost.
Check out [benchmarks](benchmarks) for more info.
<img src="benchmarks/out/echo.png" width="336" height="144" border="0" alt="echo benchmark"><img src="benchmarks/out/http.png" width="336" height="144" border="0" alt="http benchmark"><img src="benchmarks/out/redis_pipeline_1.png" width="336" height="144" border="0" alt="redis 1 benchmark"><img src="benchmarks/out/redis_pipeline_8.png" width="336" height="144" border="0" alt="redis 8 benchmark">
## Contact
Josh Baker [@tidwall](http://twitter.com/tidwall)
## License
`evio` source code is available under the MIT [License](/LICENSE).

View File

@ -1,2 +0,0 @@
bin/
socket

View File

@ -1,27 +0,0 @@
## evio benchmark tools
Required tools:
- [bombardier](https://github.com/codesenberg/bombardier) for HTTP
- [tcpkali](https://github.com/machinezone/tcpkali) for Echo
- [Redis](http://redis.io) for Redis
Required Go packages:
```
go get gonum.org/v1/plot/...
go get -u github.com/valyala/fasthttp
go get -u github.com/tidwall/redcon
```
And of course [Go](https://golang.org) is required.
Run `bench.sh` for all benchmarks.
## Notes
- The current results were run on an Ec2 c4.xlarge instance.
- The servers started in single-threaded mode (GOMAXPROC=1).
- Network clients connected over Ipv4 localhost.
Like all benchmarks ever made in the history of whatever, YMMV. Please tweak and run in your environment and let me know if you see any glaring issues.

View File

@ -1,308 +0,0 @@
package main
import (
"fmt"
"io/ioutil"
"math"
"strconv"
"strings"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/plotutil"
"gonum.org/v1/plot/vg"
)
var category string
var kind string
var connections, commands, pipeline, seconds int
var rate float64
var values []float64
var names []string
func main() {
analyze()
autoplot()
}
func autoplot() {
if category == "" {
return
}
var title = category
path := strings.Replace("out/"+category+".png", " ", "_", -1)
plotit(
path,
title,
values,
names,
)
}
func analyze() {
lines := readlines("out/http.txt", "out/echo.txt", "out/redis1.txt", "out/redis8.txt", "out/redis16.txt")
var err error
for _, line := range lines {
rlines := strings.Split(line, "\r")
line = strings.TrimSpace(rlines[len(rlines)-1])
if strings.HasPrefix(line, "--- ") {
if strings.HasSuffix(line, " START ---") {
autoplot()
category = strings.ToLower(strings.Replace(strings.Replace(line, "--- ", "", -1), " START ---", "", -1))
category = strings.Replace(category, "bench ", "", -1)
values = nil
names = nil
} else {
kind = strings.ToLower(strings.Replace(strings.Replace(line, "--- ", "", -1), " ---", "", -1))
}
connections, commands, pipeline, seconds = 0, 0, 0, 0
} else if strings.HasPrefix(line, "*** ") {
details := strings.Split(strings.ToLower(strings.Replace(line, "*** ", "", -1)), ", ")
for _, item := range details {
if strings.HasSuffix(item, " connections") {
connections, err = strconv.Atoi(strings.Split(item, " ")[0])
must(err)
} else if strings.HasSuffix(item, " commands") {
commands, err = strconv.Atoi(strings.Split(item, " ")[0])
must(err)
} else if strings.HasSuffix(item, " commands pipeline") {
pipeline, err = strconv.Atoi(strings.Split(item, " ")[0])
must(err)
} else if strings.HasSuffix(item, " seconds") {
seconds, err = strconv.Atoi(strings.Split(item, " ")[0])
must(err)
}
}
} else {
switch {
case category == "echo":
if strings.HasPrefix(line, "Packet rate estimate: ") {
rate, err = strconv.ParseFloat(strings.Split(strings.Split(line, ": ")[1], "↓,")[0], 64)
must(err)
output()
}
case category == "http":
if strings.HasPrefix(line, "Reqs/sec ") {
rate, err = strconv.ParseFloat(
strings.Split(strings.TrimSpace(strings.Split(line, "Reqs/sec ")[1]), " ")[0], 64)
must(err)
output()
}
case strings.HasPrefix(category, "redis"):
if strings.HasPrefix(line, "PING_INLINE: ") {
rate, err = strconv.ParseFloat(strings.Split(strings.Split(line, ": ")[1], " ")[0], 64)
must(err)
output()
}
}
}
}
}
func output() {
name := kind
names = append(names, name)
values = append(values, rate)
//csv += fmt.Sprintf("%s,%s,%d,%d,%d,%d,%f\n", category, kind, connections, commands, pipeline, seconds, rate)
}
func readlines(paths ...string) (lines []string) {
for _, path := range paths {
data, err := ioutil.ReadFile(path)
must(err)
lines = append(lines, strings.Split(string(data), "\n")...)
}
return
}
func must(err error) {
if err != nil {
panic(err)
}
}
func plotit(path, title string, values []float64, names []string) {
plot.DefaultFont = "Helvetica"
var groups []plotter.Values
for _, value := range values {
groups = append(groups, plotter.Values{value})
}
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = title
p.Y.Tick.Marker = commaTicks{}
p.Y.Label.Text = "Req/s"
bw := 25.0
w := vg.Points(bw)
var bars []plot.Plotter
var barsp []*plotter.BarChart
for i := 0; i < len(values); i++ {
bar, err := plotter.NewBarChart(groups[i], w)
if err != nil {
panic(err)
}
bar.LineStyle.Width = vg.Length(0)
bar.Color = plotutil.Color(i)
bar.Offset = vg.Length(
(float64(w) * float64(i)) -
(float64(w)*float64(len(values)))/2)
bars = append(bars, bar)
barsp = append(barsp, bar)
}
p.Add(bars...)
for i, name := range names {
p.Legend.Add(fmt.Sprintf("%s (%.0f req/s)", name, values[i]), barsp[i])
}
p.Legend.Top = true
p.NominalX("")
if err := p.Save(7*vg.Inch, 3*vg.Inch, path); err != nil {
panic(err)
}
}
// PreciseTicks is suitable for the Tick.Marker field of an Axis, it returns a
// set of tick marks with labels that have been rounded less agressively than
// what DefaultTicks provides.
type PreciseTicks struct{}
// Ticks returns Ticks in a specified range
func (PreciseTicks) Ticks(min, max float64) []plot.Tick {
const suggestedTicks = 3
if max <= min {
panic("illegal range")
}
tens := math.Pow10(int(math.Floor(math.Log10(max - min))))
n := (max - min) / tens
for n < suggestedTicks-1 {
tens /= 10
n = (max - min) / tens
}
majorMult := int(n / (suggestedTicks - 1))
switch majorMult {
case 7:
majorMult = 6
case 9:
majorMult = 8
}
majorDelta := float64(majorMult) * tens
val := math.Floor(min/majorDelta) * majorDelta
// Makes a list of non-truncated y-values.
var labels []float64
for val <= max {
if val >= min {
labels = append(labels, val)
}
val += majorDelta
}
prec := int(math.Ceil(math.Log10(val)) - math.Floor(math.Log10(majorDelta)))
// Makes a list of big ticks.
var ticks []plot.Tick
for _, v := range labels {
vRounded := round(v, prec)
ticks = append(ticks, plot.Tick{Value: vRounded, Label: strconv.FormatFloat(vRounded, 'f', -1, 64)})
}
minorDelta := majorDelta / 2
switch majorMult {
case 3, 6:
minorDelta = majorDelta / 3
case 5:
minorDelta = majorDelta / 5
}
val = math.Floor(min/minorDelta) * minorDelta
for val <= max {
found := false
for _, t := range ticks {
if t.Value == val {
found = true
}
}
if val >= min && val <= max && !found {
ticks = append(ticks, plot.Tick{Value: val})
}
val += minorDelta
}
return ticks
}
type commaTicks struct{}
// Ticks computes the default tick marks, but inserts commas
// into the labels for the major tick marks.
func (commaTicks) Ticks(min, max float64) []plot.Tick {
tks := PreciseTicks{}.Ticks(min, max)
for i, t := range tks {
if t.Label == "" { // Skip minor ticks, they are fine.
continue
}
tks[i].Label = addCommas(t.Label)
}
return tks
}
// AddCommas adds commas after every 3 characters from right to left.
// NOTE: This function is a quick hack, it doesn't work with decimal
// points, and may have a bunch of other problems.
func addCommas(s string) string {
rev := ""
n := 0
for i := len(s) - 1; i >= 0; i-- {
rev += string(s[i])
n++
if n%3 == 0 {
rev += ","
}
}
s = ""
for i := len(rev) - 1; i >= 0; i-- {
s += string(rev[i])
}
if strings.HasPrefix(s, ",") {
s = s[1:]
}
return s
}
// round returns the half away from zero rounded value of x with a prec precision.
//
// Special cases are:
// round(±0) = +0
// round(±Inf) = ±Inf
// round(NaN) = NaN
func round(x float64, prec int) float64 {
if x == 0 {
// Make sure zero is returned
// without the negative bit set.
return 0
}
// Fast path for positive precision on integers.
if prec >= 0 && x == math.Trunc(x) {
return x
}
pow := math.Pow10(prec)
intermed := x * pow
if math.IsInf(intermed, 0) {
return x
}
if x < 0 {
x = math.Ceil(intermed - 0.5)
} else {
x = math.Floor(intermed + 0.5)
}
if x == 0 {
return 0
}
return x / pow
}

View File

@ -1,36 +0,0 @@
#!/bin/bash
set -e
echo ""
echo "--- BENCH ECHO START ---"
echo ""
cd $(dirname "${BASH_SOURCE[0]}")
function cleanup {
echo "--- BENCH ECHO DONE ---"
kill -9 $(jobs -rp)
wait $(jobs -rp) 2>/dev/null
}
trap cleanup EXIT
mkdir -p bin
$(pkill -9 net-echo-server || printf "")
$(pkill -9 evio-echo-server || printf "")
function gobench {
echo "--- $1 ---"
if [ "$3" != "" ]; then
go build -o $2 $3
fi
GOMAXPROCS=1 $2 --port $4 &
sleep 1
echo "*** 50 connections, 10 seconds, 6 byte packets"
nl=$'\r\n'
tcpkali --workers 1 -c 50 -T 10s -m "PING{$nl}" 127.0.0.1:$4
echo "--- DONE ---"
echo ""
}
gobench "GO STDLIB" bin/net-echo-server net-echo-server/main.go 5001
gobench "EVIO" bin/evio-echo-server ../examples/echo-server/main.go 5002

View File

@ -1,37 +0,0 @@
#!/bin/bash
set -e
echo ""
echo "--- BENCH HTTP START ---"
echo ""
cd $(dirname "${BASH_SOURCE[0]}")
function cleanup {
echo "--- BENCH HTTP DONE ---"
kill -9 $(jobs -rp)
wait $(jobs -rp) 2>/dev/null
}
trap cleanup EXIT
mkdir -p bin
$(pkill -9 net-http-server || printf "")
$(pkill -9 fasthttp-server || printf "")
$(pkill -9 evio-http-server || printf "")
function gobench {
echo "--- $1 ---"
if [ "$3" != "" ]; then
go build -o $2 $3
fi
GOMAXPROCS=1 $2 --port $4 &
sleep 1
echo "*** 50 connections, 10 seconds"
bombardier -c 50 http://127.0.0.1:$4
echo "--- DONE ---"
echo ""
}
gobench "GO STDLIB" bin/net-http-server net-http-server/main.go 8081
gobench "FASTHTTP" bin/fasthttp-server fasthttp-server/main.go 8083
gobench "EVIO" bin/evio-http-server ../examples/http-server/main.go 8084

View File

@ -1,43 +0,0 @@
#!/bin/bash
set -e
pl=$1
if [ "$pl" == "" ]; then
pl="1"
fi
echo ""
echo "--- BENCH REDIS PIPELINE $pl START ---"
echo ""
cd $(dirname "${BASH_SOURCE[0]}")
function cleanup {
echo "--- BENCH REDIS PIPELINE $pl DONE ---"
kill -9 $(jobs -rp)
wait $(jobs -rp) 2>/dev/null
}
trap cleanup EXIT
mkdir -p bin
$(pkill -9 redis-server || printf "")
$(pkill -9 evio-redis-server || printf "")
function gobench {
echo "--- $1 ---"
if [ "$3" != "" ]; then
go build -o $2 $3
fi
GOMAXPROCS=1 $2 --port $4 &
sleep 1
echo "*** 50 connections, 1000000 commands, $pl commands pipeline"
redis-benchmark -p $4 -t ping_inline -q -c 50 -P $pl -n 1000000
# echo "*** 50 connections, 1000000 commands, 10 commands pipeline"
# redis-benchmark -p $4 -t ping_inline -q -c 50 -P 10 -n 1000000
# echo "*** 50 connections, 1000000 commands, 20 commands pipeline"
# redis-benchmark -p $4 -t ping_inline -q -c 50 -P 20 -n 1000000
echo "--- DONE ---"
echo ""
}
gobench "REAL REDIS" redis-server "" 6392
gobench "EVIO REDIS CLONE" bin/evio-redis-server ../examples/redis-server/main.go 6393

View File

@ -1,15 +0,0 @@
#!/bin/bash
set -e
cd $(dirname "${BASH_SOURCE[0]}")
mkdir -p out/
./bench-http.sh 2>&1 | tee out/http.txt
./bench-echo.sh 2>&1 | tee out/echo.txt
./bench-redis.sh 1 2>&1 | tee out/redis1.txt
./bench-redis.sh 8 2>&1 | tee out/redis8.txt
./bench-redis.sh 16 2>&1 | tee out/redis16.txt
go run analyze.go

View File

@ -1,32 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"github.com/valyala/fasthttp"
)
var res string
func main() {
var port int
flag.IntVar(&port, "port", 8080, "server port")
flag.Parse()
go log.Printf("http server started on port %d", port)
err := fasthttp.ListenAndServe(fmt.Sprintf(":%d", port),
func(c *fasthttp.RequestCtx) {
_, werr := c.WriteString("Hello World!\r\n")
if werr != nil {
log.Fatal(werr)
}
})
if err != nil {
log.Fatal(err)
}
}

View File

@ -1,47 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"net"
)
func main() {
var port int
flag.IntVar(&port, "port", 5000, "server port")
flag.Parse()
ln, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Printf("echo server started on port %d", port)
var id int
for {
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
id++
go func(id int, conn net.Conn) {
defer func() {
//log.Printf("closed: %d", id)
conn.Close()
}()
//log.Printf("opened: %d: %s", id, conn.RemoteAddr().String())
var packet [0xFFF]byte
for {
n, err := conn.Read(packet[:])
if err != nil {
return
}
conn.Write(packet[:n])
}
}(id, conn)
}
}

View File

@ -1,36 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"strings"
)
var res string
func main() {
var port int
var aaaa bool
flag.IntVar(&port, "port", 8080, "server port")
flag.BoolVar(&aaaa, "aaaa", false, "aaaaa....")
flag.Parse()
if aaaa {
res = strings.Repeat("a", 1024)
} else {
res = "Hello World!\r\n"
}
log.Printf("http server started on port %d", port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(res))
})
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
log.Fatal(err)
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

View File

@ -1,34 +0,0 @@
--- BENCH ECHO START ---
--- GO STDLIB ---
2017/11/04 13:13:38 echo server started on port 5001
*** 50 connections, 10 seconds, 6 byte packets
Destination: [127.0.0.1]:5001
Interface lo address [127.0.0.1]:0
Using interface lo to connect to [127.0.0.1]:5001
Ramped up to 50 connections.
Total data sent: 9165.8 MiB (9610985472 bytes)
Total data received: 8951.1 MiB (9385891515 bytes)
Bandwidth per channel: 303.867⇅ Mbps (37983.4 kBps)
Aggregate bandwidth: 7506.663↓, 7686.689↑ Mbps
Packet rate estimate: 732150.4↓, 659753.8↑ (6↓, 45↑ TCP MSS/op)
Test duration: 10.0027 s.
--- DONE ---
--- EVIO ---
2017/11/04 13:13:50 echo server started on port 5002
*** 50 connections, 10 seconds, 6 byte packets
Destination: [127.0.0.1]:5002
Interface lo address [127.0.0.1]:0
Using interface lo to connect to [127.0.0.1]:5002
Ramped up to 50 connections.
Total data sent: 15441.1 MiB (16191127552 bytes)
Total data received: 15430.5 MiB (16180050837 bytes)
Bandwidth per channel: 517.825⇅ Mbps (64728.2 kBps)
Aggregate bandwidth: 12941.205↓, 12950.064↑ Mbps
Packet rate estimate: 1184847.1↓, 1111512.9↑ (12↓, 45↑ TCP MSS/op)
Test duration: 10.0022 s.
--- DONE ---
--- BENCH ECHO DONE ---

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,49 +0,0 @@
--- BENCH HTTP START ---
--- GO STDLIB ---
2017/11/06 11:43:15 http server started on port 8081
*** 50 connections, 10 seconds
Bombarding http://127.0.0.1:8081 for 10s using 50 connections
[------------------------------------------------------------------------------] [=======>-------------------------------------------------------------------] 9s [==============>------------------------------------------------------------] 8s [======================>----------------------------------------------------] 7s [=============================>---------------------------------------------] 6s [=====================================>-------------------------------------] 5s [============================================>------------------------------] 4s [====================================================>----------------------] 3s [===========================================================>---------------] 2s [===================================================================>-------] 1s [===========================================================================] 0s [==========================================================================] 10s
Done!
Statistics Avg Stdev Max
Reqs/sec 42487.26 9452.41 53042
Latency 1.17ms 742.47us 12.53ms
HTTP codes:
1xx - 0, 2xx - 424966, 3xx - 0, 4xx - 0, 5xx - 0
others - 0
Throughput: 7.82MB/s
--- DONE ---
--- FASTHTTP ---
2017/11/06 11:43:27 http server started on port 8083
*** 50 connections, 10 seconds
Bombarding http://127.0.0.1:8083 for 10s using 50 connections
[------------------------------------------------------------------------------] [=======>-------------------------------------------------------------------] 9s [==============>------------------------------------------------------------] 8s [======================>----------------------------------------------------] 7s [=============================>---------------------------------------------] 6s [=====================================>-------------------------------------] 5s [============================================>------------------------------] 4s [====================================================>----------------------] 3s [===========================================================>---------------] 2s [===================================================================>-------] 1s [===========================================================================] 0s [==========================================================================] 10s
Done!
Statistics Avg Stdev Max
Reqs/sec 104926.32 2744.15 117354
Latency 474.64us 255.41us 11.06ms
HTTP codes:
1xx - 0, 2xx - 1049311, 3xx - 0, 4xx - 0, 5xx - 0
others - 0
Throughput: 21.11MB/s
--- DONE ---
--- EVIO ---
2017/11/06 11:43:38 http server started on port 8084
*** 50 connections, 10 seconds
Bombarding http://127.0.0.1:8084 for 10s using 50 connections
[------------------------------------------------------------------------------] [=======>-------------------------------------------------------------------] 9s [==============>------------------------------------------------------------] 8s [======================>----------------------------------------------------] 7s [=============================>---------------------------------------------] 6s [=====================================>-------------------------------------] 5s [============================================>------------------------------] 4s [====================================================>----------------------] 3s [===========================================================>---------------] 2s [===================================================================>-------] 1s [===========================================================================] 0s [==========================================================================] 10s
Done!
Statistics Avg Stdev Max
Reqs/sec 123821.87 2821.88 130897
Latency 401.99us 121.11us 12.88ms
HTTP codes:
1xx - 0, 2xx - 1238166, 3xx - 0, 4xx - 0, 5xx - 0
others - 0
Throughput: 19.60MB/s
--- DONE ---
--- BENCH HTTP DONE ---

View File

@ -1,28 +0,0 @@
--- BENCH REDIS PIPELINE 1 START ---
--- REAL REDIS ---
31889:C 04 Nov 13:14:02.373 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
31889:C 04 Nov 13:14:02.373 # Redis version=4.0.2, bits=64, commit=00000000, modified=0, pid=31889, just started
31889:C 04 Nov 13:14:02.373 # Configuration loaded
31889:M 04 Nov 13:14:02.374 * Increased maximum number of open files to 10032 (it was originally set to 1024).
31889:M 04 Nov 13:14:02.374 * Running mode=standalone, port=6392.
31889:M 04 Nov 13:14:02.374 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
31889:M 04 Nov 13:14:02.374 # Server initialized
31889:M 04 Nov 13:14:02.374 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
31889:M 04 Nov 13:14:02.374 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
31889:M 04 Nov 13:14:02.374 * Ready to accept connections
*** 50 connections, 1000000 commands, 1 commands pipeline
PING_INLINE: -nan PING_INLINE: 171620.00 PING_INLINE: 175064.00 PING_INLINE: 175986.67 PING_INLINE: 176586.00 PING_INLINE: 176886.41 PING_INLINE: 177081.33 PING_INLINE: 177301.14 PING_INLINE: 177444.50 PING_INLINE: 177331.11 PING_INLINE: 177247.20 PING_INLINE: 177178.91 PING_INLINE: 177169.00 PING_INLINE: 177084.31 PING_INLINE: 177083.72 PING_INLINE: 177058.67 PING_INLINE: 177036.50 PING_INLINE: 177041.17 PING_INLINE: 177017.11 PING_INLINE: 177013.69 PING_INLINE: 177009.80 PING_INLINE: 177003.81 PING_INLINE: 177004.36 PING_INLINE: 176991.14 requests per second
--- DONE ---
--- EVIO REDIS CLONE ---
2017/11/04 13:14:09 redis server started on port 6393
2017/11/04 13:14:09 redis server started at socket
*** 50 connections, 1000000 commands, 1 commands pipeline
PING_INLINE: -nan PING_INLINE: 167180.00 PING_INLINE: 173258.00 PING_INLINE: 175005.33 PING_INLINE: 176102.00 PING_INLINE: 176358.41 PING_INLINE: 176593.33 PING_INLINE: 176877.72 PING_INLINE: 177103.00 PING_INLINE: 177186.67 PING_INLINE: 177269.59 PING_INLINE: 177322.19 PING_INLINE: 177363.67 PING_INLINE: 177420.00 PING_INLINE: 177448.86 PING_INLINE: 177411.73 PING_INLINE: 177371.75 PING_INLINE: 177334.59 PING_INLINE: 177310.44 PING_INLINE: 177264.62 PING_INLINE: 177205.00 PING_INLINE: 177171.62 PING_INLINE: 177173.64 PING_INLINE: 177147.92 requests per second
--- DONE ---
--- BENCH REDIS PIPELINE 1 DONE ---

View File

@ -1,28 +0,0 @@
--- BENCH REDIS PIPELINE 16 START ---
--- REAL REDIS ---
32002:C 04 Nov 13:14:20.410 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
32002:C 04 Nov 13:14:20.410 # Redis version=4.0.2, bits=64, commit=00000000, modified=0, pid=32002, just started
32002:C 04 Nov 13:14:20.410 # Configuration loaded
32002:M 04 Nov 13:14:20.411 * Increased maximum number of open files to 10032 (it was originally set to 1024).
32002:M 04 Nov 13:14:20.411 * Running mode=standalone, port=6392.
32002:M 04 Nov 13:14:20.412 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
32002:M 04 Nov 13:14:20.412 # Server initialized
32002:M 04 Nov 13:14:20.412 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
32002:M 04 Nov 13:14:20.412 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
32002:M 04 Nov 13:14:20.412 * Ready to accept connections
*** 50 connections, 1000000 commands, 16 commands pipeline
PING_INLINE: 0.00 PING_INLINE: 874135.50 PING_INLINE: 877221.56 PING_INLINE: 877315.62 PING_INLINE: 877810.12 PING_INLINE: 879507.50 requests per second
--- DONE ---
--- EVIO REDIS CLONE ---
2017/11/04 13:14:22 redis server started on port 6393
2017/11/04 13:14:22 redis server started at socket
*** 50 connections, 1000000 commands, 16 commands pipeline
PING_INLINE: -nan PING_INLINE: 2127552.00 PING_INLINE: 2123142.25 requests per second
--- DONE ---
--- BENCH REDIS PIPELINE 16 DONE ---

View File

@ -1,28 +0,0 @@
--- BENCH REDIS PIPELINE 8 START ---
--- REAL REDIS ---
31946:C 04 Nov 13:14:16.084 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
31946:C 04 Nov 13:14:16.084 # Redis version=4.0.2, bits=64, commit=00000000, modified=0, pid=31946, just started
31946:C 04 Nov 13:14:16.084 # Configuration loaded
31946:M 04 Nov 13:14:16.084 * Increased maximum number of open files to 10032 (it was originally set to 1024).
31946:M 04 Nov 13:14:16.085 * Running mode=standalone, port=6392.
31946:M 04 Nov 13:14:16.085 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
31946:M 04 Nov 13:14:16.085 # Server initialized
31946:M 04 Nov 13:14:16.085 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
31946:M 04 Nov 13:14:16.085 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
31946:M 04 Nov 13:14:16.085 * Ready to accept connections
*** 50 connections, 1000000 commands, 8 commands pipeline
PING_INLINE: -nan PING_INLINE: 823072.00 PING_INLINE: 859168.00 PING_INLINE: 870933.31 PING_INLINE: 876680.00 PING_INLINE: 878734.62 requests per second
--- DONE ---
--- EVIO REDIS CLONE ---
2017/11/04 13:14:18 redis server started on port 6393
2017/11/04 13:14:18 redis server started at socket
*** 50 connections, 1000000 commands, 8 commands pipeline
PING_INLINE: -nan PING_INLINE: 1284896.00 PING_INLINE: 1284144.00 PING_INLINE: 1285141.38 PING_INLINE: 1285347.00 requests per second
--- DONE ---
--- BENCH REDIS PIPELINE 8 DONE ---

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,268 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package evio
import (
"io"
"net"
"os"
"strings"
"time"
)
// Action is an action that occurs after the completion of an event.
type Action int
const (
// None indicates that no action should occur following an event.
None Action = iota
// Detach detaches a connection. Not available for UDP connections.
Detach
// Close closes the connection.
Close
// Shutdown shutdowns the server.
Shutdown
)
// Options are set when the client opens.
type Options struct {
// TCPKeepAlive (SO_KEEPALIVE) socket option.
TCPKeepAlive time.Duration
// ReuseInputBuffer will forces the connection to share and reuse the
// same input packet buffer with all other connections that also use
// this option.
// Default value is false, which means that all input data which is
// passed to the Data event will be a uniquely copied []byte slice.
ReuseInputBuffer bool
}
// Server represents a server context which provides information about the
// running server and has control functions for managing state.
type Server struct {
// The addrs parameter is an array of listening addresses that align
// with the addr strings passed to the Serve function.
Addrs []net.Addr
// NumLoops is the number of loops that the server is using.
NumLoops int
}
// Conn is an evio connection.
type Conn interface {
// Context returns a user-defined context.
Context() interface{}
// SetContext sets a user-defined context.
SetContext(interface{})
// AddrIndex is the index of server address that was passed to the Serve call.
AddrIndex() int
// LocalAddr is the connection's local socket address.
LocalAddr() net.Addr
// RemoteAddr is the connection's remote peer address.
RemoteAddr() net.Addr
// Wake triggers a Data event for this connection.
Wake()
}
// LoadBalance sets the load balancing method.
type LoadBalance int
const (
// Random requests that connections are randomly distributed.
Random LoadBalance = iota
// RoundRobin requests that connections are distributed to a loop in a
// round-robin fashion.
RoundRobin
// LeastConnections assigns the next accepted connection to the loop with
// the least number of active connections.
LeastConnections
)
// Events represents the server events for the Serve call.
// Each event has an Action return value that is used manage the state
// of the connection and server.
type Events struct {
// NumLoops sets the number of loops to use for the server. Setting this
// to a value greater than 1 will effectively make the server
// multithreaded for multi-core machines. Which means you must take care
// with synchonizing memory between all event callbacks. Setting to 0 or 1
// will run the server single-threaded. Setting to -1 will automatically
// assign this value equal to runtime.NumProcs().
NumLoops int
// LoadBalance sets the load balancing method. Load balancing is always a
// best effort to attempt to distribute the incoming connections between
// multiple loops. This option is only works when NumLoops is set.
LoadBalance LoadBalance
// Serving fires when the server can accept connections. The server
// parameter has information and various utilities.
Serving func(server Server) (action Action)
// Opened fires when a new connection has opened.
// The info parameter has information about the connection such as
// it's local and remote address.
// Use the out return value to write data to the connection.
// The opts return value is used to set connection options.
Opened func(c Conn) (out []byte, opts Options, action Action)
// Closed fires when a connection has closed.
// The err parameter is the last known connection error.
Closed func(c Conn, err error) (action Action)
// Detached fires when a connection has been previously detached.
// Once detached it's up to the receiver of this event to manage the
// state of the connection. The Closed event will not be called for
// this connection.
// The conn parameter is a ReadWriteCloser that represents the
// underlying socket connection. It can be freely used in goroutines
// and should be closed when it's no longer needed.
Detached func(c Conn, rwc io.ReadWriteCloser) (action Action)
// PreWrite fires just before any data is written to any client socket.
PreWrite func()
// Data fires when a connection sends the server data.
// The in parameter is the incoming data.
// Use the out return value to write data to the connection.
Data func(c Conn, in []byte) (out []byte, action Action)
// Tick fires immediately after the server starts and will fire again
// following the duration specified by the delay return value.
Tick func() (delay time.Duration, action Action)
}
// Serve starts handling events for the specified addresses.
//
// Addresses should use a scheme prefix and be formatted
// like `tcp://192.168.0.10:9851` or `unix://socket`.
// Valid network schemes:
// tcp - bind to both IPv4 and IPv6
// tcp4 - IPv4
// tcp6 - IPv6
// udp - bind to both IPv4 and IPv6
// udp4 - IPv4
// udp6 - IPv6
// unix - Unix Domain Socket
//
// The "tcp" network scheme is assumed when one is not specified.
func Serve(events Events, addr ...string) error {
var lns []*listener
defer func() {
for _, ln := range lns {
ln.close()
}
}()
var stdlib bool
for _, addr := range addr {
var ln listener
var stdlibt bool
ln.network, ln.addr, ln.opts, stdlibt = parseAddr(addr)
if stdlibt {
stdlib = true
}
if ln.network == "unix" {
os.RemoveAll(ln.addr)
}
var err error
if ln.network == "udp" {
if ln.opts.reusePort {
ln.pconn, err = reuseportListenPacket(ln.network, ln.addr)
} else {
ln.pconn, err = net.ListenPacket(ln.network, ln.addr)
}
} else {
if ln.opts.reusePort {
ln.ln, err = reuseportListen(ln.network, ln.addr)
} else {
ln.ln, err = net.Listen(ln.network, ln.addr)
}
}
if err != nil {
return err
}
if ln.pconn != nil {
ln.lnaddr = ln.pconn.LocalAddr()
} else {
ln.lnaddr = ln.ln.Addr()
}
if !stdlib {
if err := ln.system(); err != nil {
return err
}
}
lns = append(lns, &ln)
}
if stdlib {
return stdserve(events, lns)
}
return serve(events, lns)
}
// InputStream is a helper type for managing input streams from inside
// the Data event.
type InputStream struct{ b []byte }
// Begin accepts a new packet and returns a working sequence of
// unprocessed bytes.
func (is *InputStream) Begin(packet []byte) (data []byte) {
data = packet
if len(is.b) > 0 {
is.b = append(is.b, data...)
data = is.b
}
return data
}
// End shifts the stream to match the unprocessed data.
func (is *InputStream) End(data []byte) {
if len(data) > 0 {
if len(data) != len(is.b) {
is.b = append(is.b[:0], data...)
}
} else if len(is.b) > 0 {
is.b = is.b[:0]
}
}
type listener struct {
ln net.Listener
lnaddr net.Addr
pconn net.PacketConn
opts addrOpts
f *os.File
fd int
network string
addr string
}
type addrOpts struct {
reusePort bool
}
func parseAddr(addr string) (network, address string, opts addrOpts, stdlib bool) {
network = "tcp"
address = addr
opts.reusePort = false
if strings.Contains(address, "://") {
network = strings.Split(address, "://")[0]
address = strings.Split(address, "://")[1]
}
if strings.HasSuffix(network, "-net") {
stdlib = true
network = network[:len(network)-4]
}
q := strings.Index(address, "?")
if q != -1 {
for _, part := range strings.Split(address[q+1:], "&") {
kv := strings.Split(part, "=")
if len(kv) == 2 {
switch kv[0] {
case "reuseport":
if len(kv[1]) != 0 {
switch kv[1][0] {
default:
opts.reusePort = kv[1][0] >= '1' && kv[1][0] <= '9'
case 'T', 't', 'Y', 'y':
opts.reusePort = true
}
}
}
}
}
address = address[:q]
}
return
}

View File

@ -1,41 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build !darwin,!netbsd,!freebsd,!openbsd,!dragonfly,!linux
package evio
import (
"errors"
"net"
"os"
)
func (ln *listener) close() {
if ln.ln != nil {
ln.ln.Close()
}
if ln.pconn != nil {
ln.pconn.Close()
}
if ln.network == "unix" {
os.RemoveAll(ln.addr)
}
}
func (ln *listener) system() error {
return nil
}
func serve(events Events, listeners []*listener) error {
return stdserve(events, listeners)
}
func reuseportListenPacket(proto, addr string) (l net.PacketConn, err error) {
return nil, errors.New("reuseport is not available")
}
func reuseportListen(proto, addr string) (l net.Listener, err error) {
return nil, errors.New("reuseport is not available")
}

View File

@ -1,459 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package evio
import (
"errors"
"io"
"net"
"runtime"
"sync"
"sync/atomic"
"time"
)
var errClosing = errors.New("closing")
var errCloseConns = errors.New("close conns")
type stdserver struct {
events Events // user events
loops []*stdloop // all the loops
lns []*listener // all the listeners
loopwg sync.WaitGroup // loop close waitgroup
lnwg sync.WaitGroup // listener close waitgroup
cond *sync.Cond // shutdown signaler
serr error // signal error
accepted uintptr // accept counter
}
type stdudpconn struct {
addrIndex int
localAddr net.Addr
remoteAddr net.Addr
in []byte
}
func (c *stdudpconn) Context() interface{} { return nil }
func (c *stdudpconn) SetContext(ctx interface{}) {}
func (c *stdudpconn) AddrIndex() int { return c.addrIndex }
func (c *stdudpconn) LocalAddr() net.Addr { return c.localAddr }
func (c *stdudpconn) RemoteAddr() net.Addr { return c.remoteAddr }
func (c *stdudpconn) Wake() {}
type stdloop struct {
idx int // loop index
ch chan interface{} // command channel
conns map[*stdconn]bool // track all the conns bound to this loop
}
type stdconn struct {
addrIndex int
localAddr net.Addr
remoteAddr net.Addr
conn net.Conn // original connection
ctx interface{} // user-defined context
loop *stdloop // owner loop
lnidx int // index of listener
donein []byte // extra data for done connection
done int32 // 0: attached, 1: closed, 2: detached
}
type wakeReq struct {
c *stdconn
}
func (c *stdconn) Context() interface{} { return c.ctx }
func (c *stdconn) SetContext(ctx interface{}) { c.ctx = ctx }
func (c *stdconn) AddrIndex() int { return c.addrIndex }
func (c *stdconn) LocalAddr() net.Addr { return c.localAddr }
func (c *stdconn) RemoteAddr() net.Addr { return c.remoteAddr }
func (c *stdconn) Wake() { c.loop.ch <- wakeReq{c} }
type stdin struct {
c *stdconn
in []byte
}
type stderr struct {
c *stdconn
err error
}
// waitForShutdown waits for a signal to shutdown
func (s *stdserver) waitForShutdown() error {
s.cond.L.Lock()
s.cond.Wait()
err := s.serr
s.cond.L.Unlock()
return err
}
// signalShutdown signals a shutdown an begins server closing
func (s *stdserver) signalShutdown(err error) {
s.cond.L.Lock()
s.serr = err
s.cond.Signal()
s.cond.L.Unlock()
}
func stdserve(events Events, listeners []*listener) error {
numLoops := events.NumLoops
if numLoops <= 0 {
if numLoops == 0 {
numLoops = 1
} else {
numLoops = runtime.NumCPU()
}
}
s := &stdserver{}
s.events = events
s.lns = listeners
s.cond = sync.NewCond(&sync.Mutex{})
//println("-- server starting")
if events.Serving != nil {
var svr Server
svr.NumLoops = numLoops
svr.Addrs = make([]net.Addr, len(listeners))
for i, ln := range listeners {
svr.Addrs[i] = ln.lnaddr
}
action := events.Serving(svr)
switch action {
case Shutdown:
return nil
}
}
for i := 0; i < numLoops; i++ {
s.loops = append(s.loops, &stdloop{
idx: i,
ch: make(chan interface{}),
conns: make(map[*stdconn]bool),
})
}
var ferr error
defer func() {
// wait on a signal for shutdown
ferr = s.waitForShutdown()
// notify all loops to close by closing all listeners
for _, l := range s.loops {
l.ch <- errClosing
}
// wait on all loops to main loop channel events
s.loopwg.Wait()
// shutdown all listeners
for i := 0; i < len(s.lns); i++ {
s.lns[i].close()
}
// wait on all listeners to complete
s.lnwg.Wait()
// close all connections
s.loopwg.Add(len(s.loops))
for _, l := range s.loops {
l.ch <- errCloseConns
}
s.loopwg.Wait()
}()
s.loopwg.Add(numLoops)
for i := 0; i < numLoops; i++ {
go stdloopRun(s, s.loops[i])
}
s.lnwg.Add(len(listeners))
for i := 0; i < len(listeners); i++ {
go stdlistenerRun(s, listeners[i], i)
}
return ferr
}
func stdlistenerRun(s *stdserver, ln *listener, lnidx int) {
var ferr error
defer func() {
s.signalShutdown(ferr)
s.lnwg.Done()
}()
var packet [0xFFFF]byte
for {
if ln.pconn != nil {
// udp
n, addr, err := ln.pconn.ReadFrom(packet[:])
if err != nil {
ferr = err
return
}
l := s.loops[int(atomic.AddUintptr(&s.accepted, 1))%len(s.loops)]
l.ch <- &stdudpconn{
addrIndex: lnidx,
localAddr: ln.lnaddr,
remoteAddr: addr,
in: append([]byte{}, packet[:n]...),
}
} else {
// tcp
conn, err := ln.ln.Accept()
if err != nil {
ferr = err
return
}
l := s.loops[int(atomic.AddUintptr(&s.accepted, 1))%len(s.loops)]
c := &stdconn{conn: conn, loop: l, lnidx: lnidx}
l.ch <- c
go func(c *stdconn) {
var packet [0xFFFF]byte
for {
n, err := c.conn.Read(packet[:])
if err != nil {
c.conn.SetReadDeadline(time.Time{})
l.ch <- &stderr{c, err}
return
}
l.ch <- &stdin{c, append([]byte{}, packet[:n]...)}
}
}(c)
}
}
}
func stdloopRun(s *stdserver, l *stdloop) {
var err error
tick := make(chan bool)
tock := make(chan time.Duration)
defer func() {
//fmt.Println("-- loop stopped --", l.idx)
if l.idx == 0 && s.events.Tick != nil {
close(tock)
go func() {
for range tick {
}
}()
}
s.signalShutdown(err)
s.loopwg.Done()
stdloopEgress(s, l)
s.loopwg.Done()
}()
if l.idx == 0 && s.events.Tick != nil {
go func() {
for {
tick <- true
delay, ok := <-tock
if !ok {
break
}
time.Sleep(delay)
}
}()
}
//fmt.Println("-- loop started --", l.idx)
for {
select {
case <-tick:
delay, action := s.events.Tick()
switch action {
case Shutdown:
err = errClosing
}
tock <- delay
case v := <-l.ch:
switch v := v.(type) {
case error:
err = v
case *stdconn:
err = stdloopAccept(s, l, v)
case *stdin:
err = stdloopRead(s, l, v.c, v.in)
case *stdudpconn:
err = stdloopReadUDP(s, l, v)
case *stderr:
err = stdloopError(s, l, v.c, v.err)
case wakeReq:
err = stdloopRead(s, l, v.c, nil)
}
}
if err != nil {
return
}
}
}
func stdloopEgress(s *stdserver, l *stdloop) {
var closed bool
loop:
for v := range l.ch {
switch v := v.(type) {
case error:
if v == errCloseConns {
closed = true
for c := range l.conns {
stdloopClose(s, l, c)
}
}
case *stderr:
stdloopError(s, l, v.c, v.err)
}
if len(l.conns) == 0 && closed {
break loop
}
}
}
func stdloopError(s *stdserver, l *stdloop, c *stdconn, err error) error {
delete(l.conns, c)
closeEvent := true
switch atomic.LoadInt32(&c.done) {
case 0: // read error
c.conn.Close()
if err == io.EOF {
err = nil
}
case 1: // closed
c.conn.Close()
err = nil
case 2: // detached
err = nil
if s.events.Detached == nil {
c.conn.Close()
} else {
closeEvent = false
switch s.events.Detached(c, &stddetachedConn{c.conn, c.donein}) {
case Shutdown:
return errClosing
}
}
}
if closeEvent {
if s.events.Closed != nil {
switch s.events.Closed(c, err) {
case Shutdown:
return errClosing
}
}
}
return nil
}
type stddetachedConn struct {
conn net.Conn // original conn
in []byte // extra input data
}
func (c *stddetachedConn) Read(p []byte) (n int, err error) {
if len(c.in) > 0 {
if len(c.in) <= len(p) {
copy(p, c.in)
n = len(c.in)
c.in = nil
return
}
copy(p, c.in[:len(p)])
n = len(p)
c.in = c.in[n:]
return
}
return c.conn.Read(p)
}
func (c *stddetachedConn) Write(p []byte) (n int, err error) {
return c.conn.Write(p)
}
func (c *stddetachedConn) Close() error {
return c.conn.Close()
}
func (c *stddetachedConn) Wake() {}
func stdloopRead(s *stdserver, l *stdloop, c *stdconn, in []byte) error {
if atomic.LoadInt32(&c.done) == 2 {
// should not ignore reads for detached connections
c.donein = append(c.donein, in...)
return nil
}
if s.events.Data != nil {
out, action := s.events.Data(c, in)
if len(out) > 0 {
if s.events.PreWrite != nil {
s.events.PreWrite()
}
c.conn.Write(out)
}
switch action {
case Shutdown:
return errClosing
case Detach:
return stdloopDetach(s, l, c)
case Close:
return stdloopClose(s, l, c)
}
}
return nil
}
func stdloopReadUDP(s *stdserver, l *stdloop, c *stdudpconn) error {
if s.events.Data != nil {
out, action := s.events.Data(c, c.in)
if len(out) > 0 {
if s.events.PreWrite != nil {
s.events.PreWrite()
}
s.lns[c.addrIndex].pconn.WriteTo(out, c.remoteAddr)
}
switch action {
case Shutdown:
return errClosing
}
}
return nil
}
func stdloopDetach(s *stdserver, l *stdloop, c *stdconn) error {
atomic.StoreInt32(&c.done, 2)
c.conn.SetReadDeadline(time.Now())
return nil
}
func stdloopClose(s *stdserver, l *stdloop, c *stdconn) error {
atomic.StoreInt32(&c.done, 1)
c.conn.SetReadDeadline(time.Now())
return nil
}
func stdloopAccept(s *stdserver, l *stdloop, c *stdconn) error {
l.conns[c] = true
c.addrIndex = c.lnidx
c.localAddr = s.lns[c.lnidx].lnaddr
c.remoteAddr = c.conn.RemoteAddr()
if s.events.Opened != nil {
out, opts, action := s.events.Opened(c)
if len(out) > 0 {
if s.events.PreWrite != nil {
s.events.PreWrite()
}
c.conn.Write(out)
}
if opts.TCPKeepAlive > 0 {
if c, ok := c.conn.(*net.TCPConn); ok {
c.SetKeepAlive(true)
c.SetKeepAlivePeriod(opts.TCPKeepAlive)
}
}
switch action {
case Shutdown:
return errClosing
case Detach:
return stdloopDetach(s, l, c)
case Close:
return stdloopClose(s, l, c)
}
}
return nil
}

View File

@ -1,478 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package evio
import (
"bufio"
"fmt"
"io"
"math/rand"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestServe(t *testing.T) {
// start a server
// connect 10 clients
// each client will pipe random data for 1-3 seconds.
// the writes to the server will be random sizes. 0KB - 1MB.
// the server will echo back the data.
// waits for graceful connection closing.
t.Run("stdlib", func(t *testing.T) {
t.Run("tcp", func(t *testing.T) {
t.Run("1-loop", func(t *testing.T) {
testServe("tcp-net", ":9997", false, 10, 1, Random)
})
t.Run("5-loop", func(t *testing.T) {
testServe("tcp-net", ":9998", false, 10, 5, LeastConnections)
})
t.Run("N-loop", func(t *testing.T) {
testServe("tcp-net", ":9999", false, 10, -1, RoundRobin)
})
})
t.Run("unix", func(t *testing.T) {
t.Run("1-loop", func(t *testing.T) {
testServe("tcp-net", ":9989", true, 10, 1, Random)
})
t.Run("5-loop", func(t *testing.T) {
testServe("tcp-net", ":9988", true, 10, 5, LeastConnections)
})
t.Run("N-loop", func(t *testing.T) {
testServe("tcp-net", ":9987", true, 10, -1, RoundRobin)
})
})
})
t.Run("poll", func(t *testing.T) {
t.Run("tcp", func(t *testing.T) {
t.Run("1-loop", func(t *testing.T) {
testServe("tcp", ":9991", false, 10, 1, Random)
})
t.Run("5-loop", func(t *testing.T) {
testServe("tcp", ":9992", false, 10, 5, LeastConnections)
})
t.Run("N-loop", func(t *testing.T) {
testServe("tcp", ":9993", false, 10, -1, RoundRobin)
})
})
t.Run("unix", func(t *testing.T) {
t.Run("1-loop", func(t *testing.T) {
testServe("tcp", ":9994", true, 10, 1, Random)
})
t.Run("5-loop", func(t *testing.T) {
testServe("tcp", ":9995", true, 10, 5, LeastConnections)
})
t.Run("N-loop", func(t *testing.T) {
testServe("tcp", ":9996", true, 10, -1, RoundRobin)
})
})
})
}
func testServe(network, addr string, unix bool, nclients, nloops int, balance LoadBalance) {
var started int32
var connected int32
var disconnected int32
var events Events
events.LoadBalance = balance
events.NumLoops = nloops
events.Serving = func(srv Server) (action Action) {
return
}
events.Opened = func(c Conn) (out []byte, opts Options, action Action) {
c.SetContext(c)
atomic.AddInt32(&connected, 1)
out = []byte("sweetness\r\n")
opts.TCPKeepAlive = time.Minute * 5
if c.LocalAddr() == nil {
panic("nil local addr")
}
if c.RemoteAddr() == nil {
panic("nil local addr")
}
return
}
events.Closed = func(c Conn, err error) (action Action) {
if c.Context() != c {
panic("invalid context")
}
atomic.AddInt32(&disconnected, 1)
if atomic.LoadInt32(&connected) == atomic.LoadInt32(&disconnected) &&
atomic.LoadInt32(&disconnected) == int32(nclients) {
action = Shutdown
}
return
}
events.Data = func(c Conn, in []byte) (out []byte, action Action) {
out = in
return
}
events.Tick = func() (delay time.Duration, action Action) {
if atomic.LoadInt32(&started) == 0 {
for i := 0; i < nclients; i++ {
go startClient(network, addr, nloops)
}
atomic.StoreInt32(&started, 1)
}
delay = time.Second / 5
return
}
var err error
if unix {
socket := strings.Replace(addr, ":", "socket", 1)
os.RemoveAll(socket)
defer os.RemoveAll(socket)
err = Serve(events, network+"://"+addr, "unix://"+socket)
} else {
err = Serve(events, network+"://"+addr)
}
if err != nil {
panic(err)
}
}
func startClient(network, addr string, nloops int) {
onetwork := network
network = strings.Replace(network, "-net", "", -1)
rand.Seed(time.Now().UnixNano())
c, err := net.Dial(network, addr)
if err != nil {
panic(err)
}
defer c.Close()
rd := bufio.NewReader(c)
msg, err := rd.ReadBytes('\n')
if err != nil {
panic(err)
}
if string(msg) != "sweetness\r\n" {
panic("bad header")
}
duration := time.Duration((rand.Float64()*2+1)*float64(time.Second)) / 8
start := time.Now()
for time.Since(start) < duration {
sz := rand.Int() % (1024 * 1024)
data := make([]byte, sz)
if _, err := rand.Read(data); err != nil {
panic(err)
}
if _, err := c.Write(data); err != nil {
panic(err)
}
data2 := make([]byte, len(data))
if _, err := io.ReadFull(rd, data2); err != nil {
panic(err)
}
if string(data) != string(data2) {
fmt.Printf("mismatch %s/%d: %d vs %d bytes\n", onetwork, nloops, len(data), len(data2))
//panic("mismatch")
}
}
}
func must(err error) {
if err != nil {
panic(err)
}
}
func TestTick(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
testTick("tcp", ":9991", false)
}()
wg.Add(1)
go func() {
defer wg.Done()
testTick("tcp", ":9992", true)
}()
wg.Add(1)
go func() {
defer wg.Done()
testTick("unix", "socket1", false)
}()
wg.Add(1)
go func() {
defer wg.Done()
testTick("unix", "socket2", true)
}()
wg.Wait()
}
func testTick(network, addr string, stdlib bool) {
var events Events
var count int
start := time.Now()
events.Tick = func() (delay time.Duration, action Action) {
if count == 25 {
action = Shutdown
return
}
count++
delay = time.Millisecond * 10
return
}
if stdlib {
must(Serve(events, network+"-net://"+addr))
} else {
must(Serve(events, network+"://"+addr))
}
dur := time.Since(start)
if dur < 250&time.Millisecond || dur > time.Second {
panic("bad ticker timing")
}
}
func TestShutdown(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
testShutdown("tcp", ":9991", false)
}()
wg.Add(1)
go func() {
defer wg.Done()
testShutdown("tcp", ":9992", true)
}()
wg.Add(1)
go func() {
defer wg.Done()
testShutdown("unix", "socket1", false)
}()
wg.Add(1)
go func() {
defer wg.Done()
testShutdown("unix", "socket2", true)
}()
wg.Wait()
}
func testShutdown(network, addr string, stdlib bool) {
var events Events
var count int
var clients int64
var N = 10
events.Opened = func(c Conn) (out []byte, opts Options, action Action) {
atomic.AddInt64(&clients, 1)
return
}
events.Closed = func(c Conn, err error) (action Action) {
atomic.AddInt64(&clients, -1)
return
}
events.Tick = func() (delay time.Duration, action Action) {
if count == 0 {
// start clients
for i := 0; i < N; i++ {
go func() {
conn, err := net.Dial(network, addr)
must(err)
defer conn.Close()
_, err = conn.Read([]byte{0})
if err == nil {
panic("expected error")
}
}()
}
} else {
if int(atomic.LoadInt64(&clients)) == N {
action = Shutdown
}
}
count++
delay = time.Second / 20
return
}
if stdlib {
must(Serve(events, network+"-net://"+addr))
} else {
must(Serve(events, network+"://"+addr))
}
if clients != 0 {
panic("did not call close on all clients")
}
}
func TestDetach(t *testing.T) {
t.Run("poll", func(t *testing.T) {
t.Run("tcp", func(t *testing.T) {
testDetach("tcp", ":9991", false)
})
t.Run("unix", func(t *testing.T) {
testDetach("unix", "socket1", false)
})
})
t.Run("stdlib", func(t *testing.T) {
t.Run("tcp", func(t *testing.T) {
testDetach("tcp", ":9992", true)
})
t.Run("unix", func(t *testing.T) {
testDetach("unix", "socket2", true)
})
})
}
func testDetach(network, addr string, stdlib bool) {
// we will write a bunch of data with the text "--detached--" in the
// middle followed by a bunch of data.
rand.Seed(time.Now().UnixNano())
rdat := make([]byte, 10*1024)
if _, err := rand.Read(rdat); err != nil {
panic("random error: " + err.Error())
}
expected := []byte(string(rdat) + "--detached--" + string(rdat))
var cin []byte
var events Events
events.Data = func(c Conn, in []byte) (out []byte, action Action) {
cin = append(cin, in...)
if len(cin) >= len(expected) {
if string(cin) != string(expected) {
panic("mismatch client -> server")
}
return cin, Detach
}
return
}
var done int64
events.Detached = func(c Conn, conn io.ReadWriteCloser) (action Action) {
go func() {
p := make([]byte, len(expected))
defer conn.Close()
_, err := io.ReadFull(conn, p)
must(err)
conn.Write(expected)
}()
return
}
events.Serving = func(srv Server) (action Action) {
go func() {
p := make([]byte, len(expected))
_ = expected
conn, err := net.Dial(network, addr)
must(err)
defer conn.Close()
conn.Write(expected)
_, err = io.ReadFull(conn, p)
must(err)
conn.Write(expected)
_, err = io.ReadFull(conn, p)
must(err)
atomic.StoreInt64(&done, 1)
}()
return
}
events.Tick = func() (delay time.Duration, action Action) {
delay = time.Second / 5
if atomic.LoadInt64(&done) == 1 {
action = Shutdown
}
return
}
if stdlib {
must(Serve(events, network+"-net://"+addr))
} else {
must(Serve(events, network+"://"+addr))
}
}
func TestBadAddresses(t *testing.T) {
var events Events
events.Serving = func(srv Server) (action Action) {
return Shutdown
}
if err := Serve(events, "tulip://howdy"); err == nil {
t.Fatalf("expected error")
}
if err := Serve(events, "howdy"); err == nil {
t.Fatalf("expected error")
}
if err := Serve(events, "tcp://"); err != nil {
t.Fatalf("expected nil, got '%v'", err)
}
}
func TestInputStream(t *testing.T) {
var s InputStream
in := []byte("HELLO")
data := s.Begin(in)
if string(data) != string(in) {
t.Fatalf("expected '%v', got '%v'", in, data)
}
s.End(in[3:])
data = s.Begin([]byte("WLY"))
if string(data) != "LOWLY" {
t.Fatalf("expected '%v', got '%v'", "LOWLY", data)
}
s.End(nil)
data = s.Begin([]byte("PLAYER"))
if string(data) != "PLAYER" {
t.Fatalf("expected '%v', got '%v'", "PLAYER", data)
}
}
func TestReuseInputBuffer(t *testing.T) {
reuses := []bool{true, false}
for _, reuse := range reuses {
var events Events
events.Opened = func(c Conn) (out []byte, opts Options, action Action) {
opts.ReuseInputBuffer = reuse
return
}
var prev []byte
events.Data = func(c Conn, in []byte) (out []byte, action Action) {
if prev == nil {
prev = in
} else {
reused := string(in) == string(prev)
if reused != reuse {
t.Fatalf("expected %v, got %v", reuse, reused)
}
action = Shutdown
}
return
}
events.Serving = func(_ Server) (action Action) {
go func() {
c, err := net.Dial("tcp", ":9991")
must(err)
defer c.Close()
c.Write([]byte("packet1"))
time.Sleep(time.Second / 5)
c.Write([]byte("packet2"))
}()
return
}
must(Serve(events, "tcp://:9991"))
}
}
func TestReuseport(t *testing.T) {
var events Events
events.Serving = func(s Server) (action Action) {
return Shutdown
}
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
var t = "1"
if i%2 == 0 {
t = "true"
}
go func(t string) {
defer wg.Done()
must(Serve(events, "tcp://:9991?reuseport="+t))
}(t)
}
wg.Wait()
}

View File

@ -1,534 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build darwin netbsd freebsd openbsd dragonfly linux
package evio
import (
"io"
"net"
"os"
"runtime"
"sync"
"sync/atomic"
"syscall"
"time"
reuseport "github.com/kavu/go_reuseport"
"github.com/tidwall/evio/internal"
)
type conn struct {
fd int // file descriptor
lnidx int // listener index in the server lns list
out []byte // write buffer
sa syscall.Sockaddr // remote socket address
reuse bool // should reuse input buffer
opened bool // connection opened event fired
action Action // next user action
ctx interface{} // user-defined context
addrIndex int // index of listening address
localAddr net.Addr // local addre
remoteAddr net.Addr // remote addr
loop *loop // connected loop
}
func (c *conn) Context() interface{} { return c.ctx }
func (c *conn) SetContext(ctx interface{}) { c.ctx = ctx }
func (c *conn) AddrIndex() int { return c.addrIndex }
func (c *conn) LocalAddr() net.Addr { return c.localAddr }
func (c *conn) RemoteAddr() net.Addr { return c.remoteAddr }
func (c *conn) Wake() {
if c.loop != nil {
c.loop.poll.Trigger(c)
}
}
type server struct {
events Events // user events
loops []*loop // all the loops
lns []*listener // all the listeners
wg sync.WaitGroup // loop close waitgroup
cond *sync.Cond // shutdown signaler
balance LoadBalance // load balancing method
accepted uintptr // accept counter
tch chan time.Duration // ticker channel
//ticktm time.Time // next tick time
}
type loop struct {
idx int // loop index in the server loops list
poll *internal.Poll // epoll or kqueue
packet []byte // read packet buffer
fdconns map[int]*conn // loop connections fd -> conn
count int32 // connection count
}
// waitForShutdown waits for a signal to shutdown
func (s *server) waitForShutdown() {
s.cond.L.Lock()
s.cond.Wait()
s.cond.L.Unlock()
}
// signalShutdown signals a shutdown an begins server closing
func (s *server) signalShutdown() {
s.cond.L.Lock()
s.cond.Signal()
s.cond.L.Unlock()
}
func serve(events Events, listeners []*listener) error {
// figure out the correct number of loops/goroutines to use.
numLoops := events.NumLoops
if numLoops <= 0 {
if numLoops == 0 {
numLoops = 1
} else {
numLoops = runtime.NumCPU()
}
}
s := &server{}
s.events = events
s.lns = listeners
s.cond = sync.NewCond(&sync.Mutex{})
s.balance = events.LoadBalance
s.tch = make(chan time.Duration)
//println("-- server starting")
if s.events.Serving != nil {
var svr Server
svr.NumLoops = numLoops
svr.Addrs = make([]net.Addr, len(listeners))
for i, ln := range listeners {
svr.Addrs[i] = ln.lnaddr
}
action := s.events.Serving(svr)
switch action {
case None:
case Shutdown:
return nil
}
}
defer func() {
// wait on a signal for shutdown
s.waitForShutdown()
// notify all loops to close by closing all listeners
for _, l := range s.loops {
l.poll.Trigger(errClosing)
}
// wait on all loops to complete reading events
s.wg.Wait()
// close loops and all outstanding connections
for _, l := range s.loops {
for _, c := range l.fdconns {
loopCloseConn(s, l, c, nil)
}
l.poll.Close()
}
//println("-- server stopped")
}()
// create loops locally and bind the listeners.
for i := 0; i < numLoops; i++ {
l := &loop{
idx: i,
poll: internal.OpenPoll(),
packet: make([]byte, 0xFFFF),
fdconns: make(map[int]*conn),
}
for _, ln := range listeners {
l.poll.AddRead(ln.fd)
}
s.loops = append(s.loops, l)
}
// start loops in background
s.wg.Add(len(s.loops))
for _, l := range s.loops {
go loopRun(s, l)
}
return nil
}
func loopCloseConn(s *server, l *loop, c *conn, err error) error {
atomic.AddInt32(&l.count, -1)
delete(l.fdconns, c.fd)
syscall.Close(c.fd)
if s.events.Closed != nil {
switch s.events.Closed(c, err) {
case None:
case Shutdown:
return errClosing
}
}
return nil
}
func loopDetachConn(s *server, l *loop, c *conn, err error) error {
if s.events.Detached == nil {
return loopCloseConn(s, l, c, err)
}
l.poll.ModDetach(c.fd)
atomic.AddInt32(&l.count, -1)
delete(l.fdconns, c.fd)
if err := syscall.SetNonblock(c.fd, false); err != nil {
return err
}
switch s.events.Detached(c, &detachedConn{fd: c.fd}) {
case None:
case Shutdown:
return errClosing
}
return nil
}
func loopNote(s *server, l *loop, note interface{}) error {
var err error
switch v := note.(type) {
case time.Duration:
delay, action := s.events.Tick()
switch action {
case None:
case Shutdown:
err = errClosing
}
s.tch <- delay
case error: // shutdown
err = v
case *conn:
// Wake called for connection
if l.fdconns[v.fd] != v {
return nil // ignore stale wakes
}
return loopWake(s, l, v)
}
return err
}
func loopRun(s *server, l *loop) {
defer func() {
//fmt.Println("-- loop stopped --", l.idx)
s.signalShutdown()
s.wg.Done()
}()
if l.idx == 0 && s.events.Tick != nil {
go loopTicker(s, l)
}
//fmt.Println("-- loop started --", l.idx)
l.poll.Wait(func(fd int, note interface{}) error {
if fd == 0 {
return loopNote(s, l, note)
}
c := l.fdconns[fd]
switch {
case c == nil:
return loopAccept(s, l, fd)
case !c.opened:
return loopOpened(s, l, c)
case len(c.out) > 0:
return loopWrite(s, l, c)
case c.action != None:
return loopAction(s, l, c)
default:
return loopRead(s, l, c)
}
})
}
func loopTicker(s *server, l *loop) {
for {
if err := l.poll.Trigger(time.Duration(0)); err != nil {
break
}
time.Sleep(<-s.tch)
}
}
func loopAccept(s *server, l *loop, fd int) error {
for i, ln := range s.lns {
if ln.fd == fd {
if len(s.loops) > 1 {
switch s.balance {
case LeastConnections:
n := atomic.LoadInt32(&l.count)
for _, lp := range s.loops {
if lp.idx != l.idx {
if atomic.LoadInt32(&lp.count) < n {
return nil // do not accept
}
}
}
case RoundRobin:
idx := int(atomic.LoadUintptr(&s.accepted)) % len(s.loops)
if idx != l.idx {
return nil // do not accept
}
atomic.AddUintptr(&s.accepted, 1)
}
}
if ln.pconn != nil {
return loopUDPRead(s, l, i, fd)
}
nfd, sa, err := syscall.Accept(fd)
if err != nil {
if err == syscall.EAGAIN {
return nil
}
return err
}
if err := syscall.SetNonblock(nfd, true); err != nil {
return err
}
c := &conn{fd: nfd, sa: sa, lnidx: i, loop: l}
l.fdconns[c.fd] = c
l.poll.AddReadWrite(c.fd)
atomic.AddInt32(&l.count, 1)
break
}
}
return nil
}
func loopUDPRead(s *server, l *loop, lnidx, fd int) error {
n, sa, err := syscall.Recvfrom(fd, l.packet, 0)
if err != nil || n == 0 {
return nil
}
if s.events.Data != nil {
var sa6 syscall.SockaddrInet6
switch sa := sa.(type) {
case *syscall.SockaddrInet4:
sa6.ZoneId = 0
sa6.Port = sa.Port
for i := 0; i < 12; i++ {
sa6.Addr[i] = 0
}
sa6.Addr[12] = sa.Addr[0]
sa6.Addr[13] = sa.Addr[1]
sa6.Addr[14] = sa.Addr[2]
sa6.Addr[15] = sa.Addr[3]
case *syscall.SockaddrInet6:
sa6 = *sa
}
c := &conn{}
c.addrIndex = lnidx
c.localAddr = s.lns[lnidx].lnaddr
c.remoteAddr = internal.SockaddrToAddr(&sa6)
in := append([]byte{}, l.packet[:n]...)
out, action := s.events.Data(c, in)
if len(out) > 0 {
if s.events.PreWrite != nil {
s.events.PreWrite()
}
syscall.Sendto(fd, out, 0, sa)
}
switch action {
case Shutdown:
return errClosing
}
}
return nil
}
func loopOpened(s *server, l *loop, c *conn) error {
c.opened = true
c.addrIndex = c.lnidx
c.localAddr = s.lns[c.lnidx].lnaddr
c.remoteAddr = internal.SockaddrToAddr(c.sa)
if s.events.Opened != nil {
out, opts, action := s.events.Opened(c)
if len(out) > 0 {
c.out = append([]byte{}, out...)
}
c.action = action
c.reuse = opts.ReuseInputBuffer
if opts.TCPKeepAlive > 0 {
if _, ok := s.lns[c.lnidx].ln.(*net.TCPListener); ok {
internal.SetKeepAlive(c.fd, int(opts.TCPKeepAlive/time.Second))
}
}
}
if len(c.out) == 0 && c.action == None {
l.poll.ModRead(c.fd)
}
return nil
}
func loopWrite(s *server, l *loop, c *conn) error {
if s.events.PreWrite != nil {
s.events.PreWrite()
}
n, err := syscall.Write(c.fd, c.out)
if err != nil {
if err == syscall.EAGAIN {
return nil
}
return loopCloseConn(s, l, c, err)
}
if n == len(c.out) {
c.out = nil
} else {
c.out = c.out[n:]
}
if len(c.out) == 0 && c.action == None {
l.poll.ModRead(c.fd)
}
return nil
}
func loopAction(s *server, l *loop, c *conn) error {
switch c.action {
default:
c.action = None
case Close:
return loopCloseConn(s, l, c, nil)
case Shutdown:
return errClosing
case Detach:
return loopDetachConn(s, l, c, nil)
}
if len(c.out) == 0 && c.action == None {
l.poll.ModRead(c.fd)
}
return nil
}
func loopWake(s *server, l *loop, c *conn) error {
if s.events.Data == nil {
return nil
}
out, action := s.events.Data(c, nil)
c.action = action
if len(out) > 0 {
c.out = append([]byte{}, out...)
}
if len(c.out) != 0 || c.action != None {
l.poll.ModReadWrite(c.fd)
}
return nil
}
func loopRead(s *server, l *loop, c *conn) error {
var in []byte
n, err := syscall.Read(c.fd, l.packet)
if n == 0 || err != nil {
if err == syscall.EAGAIN {
return nil
}
return loopCloseConn(s, l, c, err)
}
in = l.packet[:n]
if !c.reuse {
in = append([]byte{}, in...)
}
if s.events.Data != nil {
out, action := s.events.Data(c, in)
c.action = action
if len(out) > 0 {
c.out = append([]byte{}, out...)
}
}
if len(c.out) != 0 || c.action != None {
l.poll.ModReadWrite(c.fd)
}
return nil
}
type detachedConn struct {
fd int
}
func (c *detachedConn) Close() error {
err := syscall.Close(c.fd)
if err != nil {
return err
}
c.fd = -1
return nil
}
func (c *detachedConn) Read(p []byte) (n int, err error) {
n, err = syscall.Read(c.fd, p)
if err != nil {
return n, err
}
if n == 0 {
if len(p) == 0 {
return 0, nil
}
return 0, io.EOF
}
return n, nil
}
func (c *detachedConn) Write(p []byte) (n int, err error) {
n = len(p)
for len(p) > 0 {
nn, err := syscall.Write(c.fd, p)
if err != nil {
return n, err
}
p = p[nn:]
}
return n, nil
}
func (ln *listener) close() {
if ln.fd != 0 {
syscall.Close(ln.fd)
}
if ln.f != nil {
ln.f.Close()
}
if ln.ln != nil {
ln.ln.Close()
}
if ln.pconn != nil {
ln.pconn.Close()
}
if ln.network == "unix" {
os.RemoveAll(ln.addr)
}
}
// system takes the net listener and detaches it from it's parent
// event loop, grabs the file descriptor, and makes it non-blocking.
func (ln *listener) system() error {
var err error
switch netln := ln.ln.(type) {
case nil:
switch pconn := ln.pconn.(type) {
case *net.UDPConn:
ln.f, err = pconn.File()
}
case *net.TCPListener:
ln.f, err = netln.File()
case *net.UnixListener:
ln.f, err = netln.File()
}
if err != nil {
ln.close()
return err
}
ln.fd = int(ln.f.Fd())
return syscall.SetNonblock(ln.fd, true)
}
func reuseportListenPacket(proto, addr string) (l net.PacketConn, err error) {
return reuseport.ListenPacket(proto, addr)
}
func reuseportListen(proto, addr string) (l net.Listener, err error) {
return reuseport.Listen(proto, addr)
}

View File

@ -1,59 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/tidwall/evio"
)
func main() {
var port int
var loops int
var udp bool
var trace bool
var reuseport bool
var stdlib bool
flag.IntVar(&port, "port", 5000, "server port")
flag.BoolVar(&udp, "udp", false, "listen on udp")
flag.BoolVar(&reuseport, "reuseport", false, "reuseport (SO_REUSEPORT)")
flag.BoolVar(&trace, "trace", false, "print packets to console")
flag.IntVar(&loops, "loops", 0, "num loops")
flag.BoolVar(&stdlib, "stdlib", false, "use stdlib")
flag.Parse()
var events evio.Events
events.NumLoops = loops
events.Serving = func(srv evio.Server) (action evio.Action) {
log.Printf("echo server started on port %d (loops: %d)", port, srv.NumLoops)
if reuseport {
log.Printf("reuseport")
}
if stdlib {
log.Printf("stdlib")
}
return
}
events.Data = func(c evio.Conn, in []byte) (out []byte, action evio.Action) {
if trace {
log.Printf("%s", strings.TrimSpace(string(in)))
}
out = in
return
}
scheme := "tcp"
if udp {
scheme = "udp"
}
if stdlib {
scheme += "-net"
}
log.Fatal(evio.Serve(events, fmt.Sprintf("%s://:%d?reuseport=%t", scheme, port, reuseport)))
}

View File

@ -1,221 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/tidwall/evio"
)
var res string
type request struct {
proto, method string
path, query string
head, body string
remoteAddr string
}
func main() {
var port int
var loops int
var aaaa bool
var noparse bool
var unixsocket string
var stdlib bool
flag.StringVar(&unixsocket, "unixsocket", "", "unix socket")
flag.IntVar(&port, "port", 8080, "server port")
flag.BoolVar(&aaaa, "aaaa", false, "aaaaa....")
flag.BoolVar(&noparse, "noparse", true, "do not parse requests")
flag.BoolVar(&stdlib, "stdlib", false, "use stdlib")
flag.IntVar(&loops, "loops", 0, "num loops")
flag.Parse()
if os.Getenv("NOPARSE") == "1" {
noparse = true
}
if aaaa {
res = strings.Repeat("a", 1024)
} else {
res = "Hello World!\r\n"
}
var events evio.Events
events.NumLoops = loops
events.Serving = func(srv evio.Server) (action evio.Action) {
log.Printf("http server started on port %d (loops: %d)", port, srv.NumLoops)
if unixsocket != "" {
log.Printf("http server started at %s", unixsocket)
}
if stdlib {
log.Printf("stdlib")
}
return
}
events.Opened = func(c evio.Conn) (out []byte, opts evio.Options, action evio.Action) {
c.SetContext(&evio.InputStream{})
//log.Printf("opened: laddr: %v: raddr: %v", c.LocalAddr(), c.RemoteAddr())
return
}
events.Closed = func(c evio.Conn, err error) (action evio.Action) {
//log.Printf("closed: %s: %s", c.LocalAddr().String(), c.RemoteAddr().String())
return
}
events.Data = func(c evio.Conn, in []byte) (out []byte, action evio.Action) {
if in == nil {
return
}
is := c.Context().(*evio.InputStream)
data := is.Begin(in)
if noparse && bytes.Contains(data, []byte("\r\n\r\n")) {
// for testing minimal single packet request -> response.
out = appendresp(nil, "200 OK", "", res)
return
}
// process the pipeline
var req request
for {
leftover, err := parsereq(data, &req)
if err != nil {
// bad thing happened
out = appendresp(out, "500 Error", "", err.Error()+"\n")
action = evio.Close
break
} else if len(leftover) == len(data) {
// request not ready, yet
break
}
// handle the request
req.remoteAddr = c.RemoteAddr().String()
out = appendhandle(out, &req)
data = leftover
}
is.End(data)
return
}
var ssuf string
if stdlib {
ssuf = "-net"
}
// We at least want the single http address.
addrs := []string{fmt.Sprintf("tcp"+ssuf+"://:%d", port)}
if unixsocket != "" {
addrs = append(addrs, fmt.Sprintf("unix"+ssuf+"://%s", unixsocket))
}
// Start serving!
log.Fatal(evio.Serve(events, addrs...))
}
// appendhandle handles the incoming request and appends the response to
// the provided bytes, which is then returned to the caller.
func appendhandle(b []byte, req *request) []byte {
return appendresp(b, "200 OK", "", res)
}
// appendresp will append a valid http response to the provide bytes.
// The status param should be the code plus text such as "200 OK".
// The head parameter should be a series of lines ending with "\r\n" or empty.
func appendresp(b []byte, status, head, body string) []byte {
b = append(b, "HTTP/1.1"...)
b = append(b, ' ')
b = append(b, status...)
b = append(b, '\r', '\n')
b = append(b, "Server: evio\r\n"...)
b = append(b, "Date: "...)
b = time.Now().AppendFormat(b, "Mon, 02 Jan 2006 15:04:05 GMT")
b = append(b, '\r', '\n')
if len(body) > 0 {
b = append(b, "Content-Length: "...)
b = strconv.AppendInt(b, int64(len(body)), 10)
b = append(b, '\r', '\n')
}
b = append(b, head...)
b = append(b, '\r', '\n')
if len(body) > 0 {
b = append(b, body...)
}
return b
}
// parsereq is a very simple http request parser. This operation
// waits for the entire payload to be buffered before returning a
// valid request.
func parsereq(data []byte, req *request) (leftover []byte, err error) {
sdata := string(data)
var i, s int
var top string
var clen int
var q = -1
// method, path, proto line
for ; i < len(sdata); i++ {
if sdata[i] == ' ' {
req.method = sdata[s:i]
for i, s = i+1, i+1; i < len(sdata); i++ {
if sdata[i] == '?' && q == -1 {
q = i - s
} else if sdata[i] == ' ' {
if q != -1 {
req.path = sdata[s:q]
req.query = req.path[q+1 : i]
} else {
req.path = sdata[s:i]
}
for i, s = i+1, i+1; i < len(sdata); i++ {
if sdata[i] == '\n' && sdata[i-1] == '\r' {
req.proto = sdata[s:i]
i, s = i+1, i+1
break
}
}
break
}
}
break
}
}
if req.proto == "" {
return data, fmt.Errorf("malformed request")
}
top = sdata[:s]
for ; i < len(sdata); i++ {
if i > 1 && sdata[i] == '\n' && sdata[i-1] == '\r' {
line := sdata[s : i-1]
s = i + 1
if line == "" {
req.head = sdata[len(top)+2 : i+1]
i++
if clen > 0 {
if len(sdata[i:]) < clen {
break
}
req.body = sdata[i : i+clen]
i += clen
}
return data[i:], nil
}
if strings.HasPrefix(line, "Content-Length:") {
n, err := strconv.ParseInt(strings.TrimSpace(line[len("Content-Length:"):]), 10, 64)
if err == nil {
clen = int(n)
}
}
}
}
// not enough data
return data, nil
}

View File

@ -1,181 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"strings"
"sync"
"github.com/tidwall/evio"
"github.com/tidwall/redcon"
)
type conn struct {
is evio.InputStream
addr string
}
func main() {
var port int
var unixsocket string
var stdlib bool
var loops int
var balance string
flag.IntVar(&port, "port", 6380, "server port")
flag.IntVar(&loops, "loops", 0, "num loops")
flag.StringVar(&unixsocket, "unixsocket", "socket", "unix socket")
flag.StringVar(&balance, "balance", "random", "random, round-robin, least-connections")
flag.BoolVar(&stdlib, "stdlib", false, "use stdlib")
flag.Parse()
var mu sync.RWMutex
var keys = make(map[string]string)
var events evio.Events
switch balance {
default:
log.Fatalf("invalid -balance flag: '%v'", balance)
case "random":
events.LoadBalance = evio.Random
case "round-robin":
events.LoadBalance = evio.RoundRobin
case "least-connections":
events.LoadBalance = evio.LeastConnections
}
events.NumLoops = loops
events.Serving = func(srv evio.Server) (action evio.Action) {
log.Printf("redis server started on port %d (loops: %d)", port, srv.NumLoops)
if unixsocket != "" {
log.Printf("redis server started at %s (loops: %d)", unixsocket, srv.NumLoops)
}
if stdlib {
log.Printf("stdlib")
}
return
}
events.Opened = func(ec evio.Conn) (out []byte, opts evio.Options, action evio.Action) {
//fmt.Printf("opened: %v\n", ec.RemoteAddr())
ec.SetContext(&conn{})
return
}
events.Closed = func(ec evio.Conn, err error) (action evio.Action) {
// fmt.Printf("closed: %v\n", ec.RemoteAddr())
return
}
events.Data = func(ec evio.Conn, in []byte) (out []byte, action evio.Action) {
if in == nil {
log.Printf("wake from %s\n", ec.RemoteAddr())
return nil, evio.Close
}
c := ec.Context().(*conn)
data := c.is.Begin(in)
var n int
var complete bool
var err error
var args [][]byte
for action == evio.None {
complete, args, _, data, err = redcon.ReadNextCommand(data, args[:0])
if err != nil {
action = evio.Close
out = redcon.AppendError(out, err.Error())
break
}
if !complete {
break
}
if len(args) > 0 {
n++
switch strings.ToUpper(string(args[0])) {
default:
out = redcon.AppendError(out, "ERR unknown command '"+string(args[0])+"'")
case "PING":
if len(args) > 2 {
out = redcon.AppendError(out, "ERR wrong number of arguments for '"+string(args[0])+"' command")
} else if len(args) == 2 {
out = redcon.AppendBulk(out, args[1])
} else {
out = redcon.AppendString(out, "PONG")
}
case "WAKE":
go ec.Wake()
out = redcon.AppendString(out, "OK")
case "ECHO":
if len(args) != 2 {
out = redcon.AppendError(out, "ERR wrong number of arguments for '"+string(args[0])+"' command")
} else {
out = redcon.AppendBulk(out, args[1])
}
case "SHUTDOWN":
out = redcon.AppendString(out, "OK")
action = evio.Shutdown
case "QUIT":
out = redcon.AppendString(out, "OK")
action = evio.Close
case "GET":
if len(args) != 2 {
out = redcon.AppendError(out, "ERR wrong number of arguments for '"+string(args[0])+"' command")
} else {
key := string(args[1])
mu.Lock()
val, ok := keys[key]
mu.Unlock()
if !ok {
out = redcon.AppendNull(out)
} else {
out = redcon.AppendBulkString(out, val)
}
}
case "SET":
if len(args) != 3 {
out = redcon.AppendError(out, "ERR wrong number of arguments for '"+string(args[0])+"' command")
} else {
key, val := string(args[1]), string(args[2])
mu.Lock()
keys[key] = val
mu.Unlock()
out = redcon.AppendString(out, "OK")
}
case "DEL":
if len(args) < 2 {
out = redcon.AppendError(out, "ERR wrong number of arguments for '"+string(args[0])+"' command")
} else {
var n int
mu.Lock()
for i := 1; i < len(args); i++ {
if _, ok := keys[string(args[i])]; ok {
n++
delete(keys, string(args[i]))
}
}
mu.Unlock()
out = redcon.AppendInt(out, int64(n))
}
case "FLUSHDB":
mu.Lock()
keys = make(map[string]string)
mu.Unlock()
out = redcon.AppendString(out, "OK")
}
}
}
c.is.End(data)
return
}
var ssuf string
if stdlib {
ssuf = "-net"
}
addrs := []string{fmt.Sprintf("tcp"+ssuf+"://:%d", port)}
if unixsocket != "" {
addrs = append(addrs, fmt.Sprintf("unix"+ssuf+"://%s", unixsocket))
}
err := evio.Serve(events, addrs...)
if err != nil {
log.Fatal(err)
}
}

View File

@ -1,125 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// +build darwin netbsd freebsd openbsd dragonfly
package internal
import (
"syscall"
)
// Poll ...
type Poll struct {
fd int
changes []syscall.Kevent_t
notes noteQueue
}
// OpenPoll ...
func OpenPoll() *Poll {
l := new(Poll)
p, err := syscall.Kqueue()
if err != nil {
panic(err)
}
l.fd = p
_, err = syscall.Kevent(l.fd, []syscall.Kevent_t{{
Ident: 0,
Filter: syscall.EVFILT_USER,
Flags: syscall.EV_ADD | syscall.EV_CLEAR,
}}, nil, nil)
if err != nil {
panic(err)
}
return l
}
// Close ...
func (p *Poll) Close() error {
return syscall.Close(p.fd)
}
// Trigger ...
func (p *Poll) Trigger(note interface{}) error {
p.notes.Add(note)
_, err := syscall.Kevent(p.fd, []syscall.Kevent_t{{
Ident: 0,
Filter: syscall.EVFILT_USER,
Fflags: syscall.NOTE_TRIGGER,
}}, nil, nil)
return err
}
// Wait ...
func (p *Poll) Wait(iter func(fd int, note interface{}) error) error {
events := make([]syscall.Kevent_t, 128)
for {
n, err := syscall.Kevent(p.fd, p.changes, events, nil)
if err != nil && err != syscall.EINTR {
return err
}
p.changes = p.changes[:0]
if err := p.notes.ForEach(func(note interface{}) error {
return iter(0, note)
}); err != nil {
return err
}
for i := 0; i < n; i++ {
if fd := int(events[i].Ident); fd != 0 {
if err := iter(fd, nil); err != nil {
return err
}
}
}
}
}
// AddRead ...
func (p *Poll) AddRead(fd int) {
p.changes = append(p.changes,
syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_ADD, Filter: syscall.EVFILT_READ,
},
)
}
// AddReadWrite ...
func (p *Poll) AddReadWrite(fd int) {
p.changes = append(p.changes,
syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_ADD, Filter: syscall.EVFILT_READ,
},
syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_ADD, Filter: syscall.EVFILT_WRITE,
},
)
}
// ModRead ...
func (p *Poll) ModRead(fd int) {
p.changes = append(p.changes, syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_DELETE, Filter: syscall.EVFILT_WRITE,
})
}
// ModReadWrite ...
func (p *Poll) ModReadWrite(fd int) {
p.changes = append(p.changes, syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_ADD, Filter: syscall.EVFILT_WRITE,
})
}
// ModDetach ...
func (p *Poll) ModDetach(fd int) {
p.changes = append(p.changes,
syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_DELETE, Filter: syscall.EVFILT_READ,
},
syscall.Kevent_t{
Ident: uint64(fd), Flags: syscall.EV_DELETE, Filter: syscall.EVFILT_WRITE,
},
)
}

View File

@ -1,20 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
import "syscall"
// SetKeepAlive sets the keepalive for the connection
func SetKeepAlive(fd, secs int) error {
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, 0x8, 1); err != nil {
return err
}
switch err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, 0x101, secs); err {
case nil, syscall.ENOPROTOOPT: // OS X 10.7 and earlier don't support this option
default:
return err
}
return syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE, secs)
}

View File

@ -1,129 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
import (
"syscall"
)
// Poll ...
type Poll struct {
fd int // epoll fd
wfd int // wake fd
notes noteQueue
}
// OpenPoll ...
func OpenPoll() *Poll {
l := new(Poll)
p, err := syscall.EpollCreate1(0)
if err != nil {
panic(err)
}
l.fd = p
r0, _, e0 := syscall.Syscall(syscall.SYS_EVENTFD2, 0, 0, 0)
if e0 != 0 {
syscall.Close(p)
panic(err)
}
l.wfd = int(r0)
l.AddRead(l.wfd)
return l
}
// Close ...
func (p *Poll) Close() error {
if err := syscall.Close(p.wfd); err != nil {
return err
}
return syscall.Close(p.fd)
}
// Trigger ...
func (p *Poll) Trigger(note interface{}) error {
p.notes.Add(note)
_, err := syscall.Write(p.wfd, []byte{0, 0, 0, 0, 0, 0, 0, 1})
return err
}
// Wait ...
func (p *Poll) Wait(iter func(fd int, note interface{}) error) error {
events := make([]syscall.EpollEvent, 64)
for {
n, err := syscall.EpollWait(p.fd, events, -1)
if err != nil && err != syscall.EINTR {
return err
}
if err := p.notes.ForEach(func(note interface{}) error {
return iter(0, note)
}); err != nil {
return err
}
for i := 0; i < n; i++ {
if fd := int(events[i].Fd); fd != p.wfd {
if err := iter(fd, nil); err != nil {
return err
}
} else {
}
}
}
}
// AddReadWrite ...
func (p *Poll) AddReadWrite(fd int) {
if err := syscall.EpollCtl(p.fd, syscall.EPOLL_CTL_ADD, fd,
&syscall.EpollEvent{Fd: int32(fd),
Events: syscall.EPOLLIN | syscall.EPOLLOUT,
},
); err != nil {
panic(err)
}
}
// AddRead ...
func (p *Poll) AddRead(fd int) {
if err := syscall.EpollCtl(p.fd, syscall.EPOLL_CTL_ADD, fd,
&syscall.EpollEvent{Fd: int32(fd),
Events: syscall.EPOLLIN,
},
); err != nil {
panic(err)
}
}
// ModRead ...
func (p *Poll) ModRead(fd int) {
if err := syscall.EpollCtl(p.fd, syscall.EPOLL_CTL_MOD, fd,
&syscall.EpollEvent{Fd: int32(fd),
Events: syscall.EPOLLIN,
},
); err != nil {
panic(err)
}
}
// ModReadWrite ...
func (p *Poll) ModReadWrite(fd int) {
if err := syscall.EpollCtl(p.fd, syscall.EPOLL_CTL_MOD, fd,
&syscall.EpollEvent{Fd: int32(fd),
Events: syscall.EPOLLIN | syscall.EPOLLOUT,
},
); err != nil {
panic(err)
}
}
// ModDetach ...
func (p *Poll) ModDetach(fd int) {
if err := syscall.EpollCtl(p.fd, syscall.EPOLL_CTL_DEL, fd,
&syscall.EpollEvent{Fd: int32(fd),
Events: syscall.EPOLLIN | syscall.EPOLLOUT,
},
); err != nil {
panic(err)
}
}

View File

@ -1,11 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
// SetKeepAlive sets the keepalive for the connection
func SetKeepAlive(fd, secs int) error {
// OpenBSD has no user-settable per-socket TCP keepalive options.
return nil
}

View File

@ -1,19 +0,0 @@
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build netbsd freebsd dragonfly linux
package internal
import "syscall"
func SetKeepAlive(fd, secs int) error {
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil {
return err
}
if err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, secs); err != nil {
return err
}
return syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, secs)
}

View File

@ -1,53 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
import (
"runtime"
"sync/atomic"
)
// this is a good candiate for a lock-free structure.
type spinlock struct{ lock uintptr }
func (l *spinlock) Lock() {
for !atomic.CompareAndSwapUintptr(&l.lock, 0, 1) {
runtime.Gosched()
}
}
func (l *spinlock) Unlock() {
atomic.StoreUintptr(&l.lock, 0)
}
type noteQueue struct {
mu spinlock
notes []interface{}
}
func (q *noteQueue) Add(note interface{}) (one bool) {
q.mu.Lock()
q.notes = append(q.notes, note)
n := len(q.notes)
q.mu.Unlock()
return n == 1
}
func (q *noteQueue) ForEach(iter func(note interface{}) error) error {
q.mu.Lock()
if len(q.notes) == 0 {
q.mu.Unlock()
return nil
}
notes := q.notes
q.notes = nil
q.mu.Unlock()
for _, note := range notes {
if err := iter(note); err != nil {
return err
}
}
return nil
}

View File

@ -1,39 +0,0 @@
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
import (
"net"
"syscall"
)
// SockaddrToAddr returns a go/net friendly address
func SockaddrToAddr(sa syscall.Sockaddr) net.Addr {
var a net.Addr
switch sa := sa.(type) {
case *syscall.SockaddrInet4:
a = &net.TCPAddr{
IP: append([]byte{}, sa.Addr[:]...),
Port: sa.Port,
}
case *syscall.SockaddrInet6:
var zone string
if sa.ZoneId != 0 {
if ifi, err := net.InterfaceByIndex(int(sa.ZoneId)); err == nil {
zone = ifi.Name
}
}
if zone == "" && sa.ZoneId != 0 {
}
a = &net.TCPAddr{
IP: append([]byte{}, sa.Addr[:]...),
Port: sa.Port,
Zone: zone,
}
case *syscall.SockaddrUnix:
a = &net.UnixAddr{Net: "unix", Name: sa.Name}
}
return a
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB