wrk

package module
v0.0.0-...-c07f79f Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 10 Imported by: 0

README

wrk

wrk is a utility for running multiple workers, such as web servers (HTTP/gRPC/etc) as well as daemon-style goroutines in a coordinated fashion. On any errors, all workers are gracefully stopped either through context-cancellation or by executing a worker's defined Stop function.

Usage

To import this module into a Go project, use go get:

$ go get -u github.com/rodaine/wrk
Example
package main

import (
	"context"
	"log"
	"net/http"
	"syscall"
	"time"

	"github.com/rodaine/wrk"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	// captures any signals to initiate a graceful shutdown
	sigs := wrk.Signals{
		syscall.SIGINT,
		syscall.SIGTERM,
	}

	// launches the http.DefaultServeMux on port 8080
	web := &wrk.HTTPServer{
		Server:              &http.Server{Addr: ":8080"},
		StopTimeout:         10 * time.Second,
		OverrideBaseContext: true,
	}

	// launches the prometheus metrics on port 2112
	metrics := &wrk.HTTPServer{
		Server: &http.Server{
			Addr:    ":2112",
			Handler: promhttp.Handler(),
		},
	}

	// spawns a daemon worker
	daemon := wrk.Named{
		Name:     "my daemon",
		Delegate: wrk.WorkerFunc(MyDaemon),
	} 

	// blocks until all workers are done
	err := wrk.Work(context.Background(), 
		sigs, web, metrics, daemon)
	
	log.Println(err)
}

func MyDaemon(ctx context.Context) error {
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Second):
			log.Println("tick")
		}
	}
}

Documentation

Overview

Package wrk is a utility for running multiple workers, such as web-servers (HTTP/gRPC/etc) as well as daemon-style goroutines in a coordinated fashion. On any errors, all workers are gracefully stopped either through context-cancellation or by executing a worker's defined Stop function.

Index

Constants

View Source
const DefaultHTTPStopTimeout = 5 * time.Second

Variables

This section is empty.

Functions

func Work

func Work(ctx context.Context, workers ...Worker) error

Work runs all the provided workers concurrently, terminating if any Worker returns an error or if the provided context is canceled. This function blocks until all workers have shutdown. The first error produced by a Worker is returned; it is nil if all workers have stopped cleanly.

Types

type HTTPServer

type HTTPServer struct {
	// Server is the http.Server instance that will be run. If nil, the default,
	// zero-value server will be executed instead. See the http.Server
	// documentation details on the default behavior.
	Server *http.Server

	// StopTimeout is the grace-period allowed for the graceful shutdown of the
	// Server to complete. If zero, the DefaultHTTPStopTimeout value is used.
	StopTimeout time.Duration

	// If OverrideBaseContext is true, the base context attached to the
	// http.Request's handled by the Server are replaced with the context
	// passed to Run. Note, this means all in-flight requests will have their
	// context canceled during graceful shutdown
	OverrideBaseContext bool
	// contains filtered or unexported fields
}

HTTPServer executes an http.Server, stopping it gracefully via its Shutdown method.

func (*HTTPServer) Run

func (srv *HTTPServer) Run(ctx context.Context) error

func (*HTTPServer) Stop

func (srv *HTTPServer) Stop() error

type Named

type Named struct {
	// Name is the identifier for the wrapped Worker.
	Name string

	// Delegate is the Worker (or WorkStopper) associated with Name.
	Delegate Worker
}

Named is a decorator WorkStopper that wraps any errors returned by Run or Stop as a NamedError.

func (Named) Run

func (n Named) Run(ctx context.Context) error

func (Named) Stop

func (n Named) Stop() error

type NamedError

type NamedError struct {
	Name string
	Err  error
}

NamedError is the wrapped error returned by Named

func (NamedError) Error

func (err NamedError) Error() string

func (NamedError) Unwrap

func (err NamedError) Unwrap() error

type ReceivedSignalError

type ReceivedSignalError struct {
	// Signal is the captured os.Signal
	Signal os.Signal
}

ReceivedSignalError is returned by Signals.Run when a signal is captured.

func (ReceivedSignalError) Error

func (err ReceivedSignalError) Error() string

type Signals

type Signals []os.Signal

Signals is a Worker that blocks until a specified os.Signal is received or the context is canceled. This worker always returns an error, either a ReceivedSignalError or the context's error when canceled. After the first signal is received, any subsequent signals will not be captured and will follow their default behavior.

See signal.Notify for documentation on the signal capture behavior.

func (Signals) Run

func (s Signals) Run(ctx context.Context) error

type WorkStopper

type WorkStopper interface {
	Worker

	// Stop is called to signal that execution of the Worker should stop
	// (typically when another Worker returns an error or the root context is
	// canceled). Stop will always be called to allow any cleanup operations to
	// occur. Stop should return an error if the Worker cannot be shutdown
	// gracefully (or within a reasonable amount of time).
	//
	// Note: it is possible that both Stop and Run can be executed concurrently.
	// Any mutations from either method must be synchronized to avoid data races.
	Stop() error
}

A WorkStopper is a Worker that needs to be shutdown from an external goroutine.

type Worker

type Worker interface {
	// Run should be a blocking operation that continues to execute until ctx
	// is canceled. Run should return an error only if the operation did not
	// exit intentionally (i.e., http.ErrServerClosed should be converted to
	// nil).
	//
	// If the work cannot be cancelled directly via the ctx (e.g.,
	// http.ListenAndServe) or resources need to be cleaned up out-of-band, a
	// Stop function should be provided. See WorkStopper for the appropriate
	// interface.
	Run(ctx context.Context) error
}

Worker describes a long-running process that's executed concurrently with other workers within an application. Some examples of workers would be a web server (e.g., HTTPServer) or a daemon listening on a data stream.

type WorkerFunc

type WorkerFunc func(ctx context.Context) error

WorkerFunc is a Worker defined as just by just its Run method.

func (WorkerFunc) Run

func (w WorkerFunc) Run(ctx context.Context) error

Directories

Path Synopsis
grpc module

Jump to

Keyboard shortcuts

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