Coder Social home page Coder Social logo

evio's Introduction

evio
Build Status GoDoc

evio is an event loop networking framework that is fast and small. It makes direct epoll and kqueue syscalls rather than using the standard Go net package, and works in a similar manner as libuv and libevent.

The goal of this project is to create a server framework for Go that performs on par with Redis and Haproxy for packet handling. My hope is to use this as a foundation for Tile38 and a future L7 proxy for Go... and a bunch of other stuff.

Just to be perfectly clear

This project is not intended to be a general purpose replacement for the standard Go net package or goroutines. It's for building specialized services such as key value stores, L7 proxies, static websites, etc.

You would not want to use this framework if you need to handle long-running requests (milliseconds or more). For example, a web api that needs to connect to a mongo database, authenticate, and respond; just use the Go net/http package instead.

There are many popular event loop based applications in the wild such as Nginx, Haproxy, Redis, and Memcached. All of these are single-threaded and very fast and written in C.

The reason I wrote this framework is so I can build certain network services that perform like the C apps above, but I also want to continue to work in Go.

Features

  • Fast single-threaded event loop
  • Simple API
  • Low memory usage
  • Supports tcp4, tcp6, and unix sockets
  • Allows multiple network binding on the same event loop
  • Flexible ticker event
  • Fallback for non-epoll/kqueue operating systems by simulating events with the net package
  • Ability to wake up connections from long running background operations

Getting Started

Installing

To start using evio, install Go and run go get:

$ 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 receives an ID that's 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:

package main

import "github.com/tidwall/evio"

func main() {
	var events evio.Events
	events.Data = func(id int, 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:

$ 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.
  • Prewrite fires prior to all write attempts from the server.
  • Postwrite fires immediately after every write attempt.
  • Tick fires immediately after the server starts and will fire again after a specified interval.

Multiple addresses

An server can bind to multiple addresses and share the same event loop.

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.

events.Tick = func() (delay time.Duration, action Action){
	log.Printf("tick")
	delay = time.Second
	return
}

Wake up

A connection can be woken up using the wake function that is made available through the Serving event. This is useful for when you need to offload an operation to a background goroutine and then later notify the event loop that it's time to send some data.

Example echo server that when encountering the line "exec" it waits 5 seconds before responding.

var wake func(id int) bool
var mu sync.Mutex
var execs = make(map[int]int)

events.Serving = func(wakefn func(id int) bool, addrs []net.Addr) (action evio.Action) {
	wake = wakefn // hang on to the wake function
	return
}
events.Data = func(id int, in []byte) (out []byte, action evio.Action) {
	if in == nil {
		// look for `in` param equal to `nil` following a wake call.
		mu.Lock()
		for execs[id] > 0 {
			out = append(out, "exec\r\n"...)
			execs[id]--
		}
		mu.Unlock()
	} else if string(in) == "exec\r\n" {
		go func(){
			// do some long running operation
			time.Sleep(time.Second*5)
			mu.Lock()
			execs[id]++
			mu.Unlock()
			wake(id)
		}()
	} else {
		out = in
	}
	return
}

Data translations

The Translate function wraps events and provides a ReadWriter that can be used to translate data off the wire from one format to another. This can be useful for transparently adding compression or encryption.

For example, let's say we need TLS support:

var events Events

// ... fill the events with happy functions

cer, err := tls.LoadX509KeyPair("certs/ssl-cert-snakeoil.pem", "certs/ssl-cert-snakeoil.key")
if err != nil {
	log.Fatal(err)
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}

// wrap the events with a TLS translator

events = evio.Translate(events, nil, 
	func(id int, rw io.ReadWriter) io.ReadWriter {
		return tls.Server(evio.NopConn(rw), config)
	},
)

log.Fatal(Serve(events, "tcp://0.0.0.0:443"))

Here we wrapped the event with a TLS translator. The evio.NopConn function is used to converts the ReadWriter a net.Conn so the tls.Server() call will work.

There's a working TLS example at examples/http-server/main.go that binds to port 8080 and 4443 using an developer SSL certificate. The 8080 connections will be insecure and the 4443 will be secure.

$ cd examples/http-server
$ go run main.go --tlscert example.pem
2017/11/02 06:24:33 http server started on port 8080
2017/11/02 06:24:33 https server started on port 4443
$ curl http://localhost:8080
Hello World!
$ curl -k https://localhost:4443
Hello World!

More examples

Please check out the examples subdirectory for a simplified redis clone, an echo server, and a very basic http server with TLS support.

To run an example:

$ 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 for more info.

echo benchmarkhttp benchmarkredis 1 benchmarkredis 8 benchmark

Contact

Josh Baker @tidwall

License

evio source code is available under the MIT License.

evio's People

Contributors

tidwall avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.