actuator

package module
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2023 License: MIT Imports: 10 Imported by: 0

README

GO Actuator

GoDoc Release Report Coverage Status Mentioned in Awesome Go

GO actuator configures the set of actuator endpoints for your application. It is very extensible and can be configured with Go's native HTTP Server Mux, or with any 3rd party web framework as well.

Project Versioning

Go actuator uses semantic versioning. API should not change between patch and minor releases. New minor versions may add additional features to the API.

Installation

To install Go Actuator package, you need to install Go and set your Go workspace first.

  1. The first need Go installed (version 1.13+ is required), then you can use the below Go command to install Go Actuator.
go get github.com/sinhashubham95/go-actuator
  1. Import it in your code:
import "github.com/sinhashubham95/go-actuator"

How to Use

The actuator library exposes a plain native handler function, and it is the responsibility of the application to put this handler to use. This can be used either directly with Go's native HTTP Server Mux, or with any 3rd party web framework as well.

Configuration

The configuration contains the following:-

  1. Endpoints - This is the list of endpoints which will be enabled. This is not a mandatory parameter. If not provided, then all the endpoints will be enabled. The possible endpoints are - /env, /info, /metrics, /ping, /shutdown and /threadDump. You can find the description of each of these endpoints below.
  2. Env - This is the environment where the application is running. For example, dev, stg, prod, etc.
  3. Name - This is the name of the application which is using this actuator library.
  4. Port - This is the port where the application is running.
  5. Version - This is the current application version.
import actuator "github.com/sinhashubham95/go-actuator"

config := &actuator.Config{
	Endpoints: []int{
		actuator.Env,
		actuator.Info,
		actuator.Metrics,
		actuator.Ping,
		actuator.Shutdown,
		actuator.ThreadDump,
    },
    Env: "dev",
    Name: "Naruto Rocks",
    Port: 8080,
    Version: "0.1.0",
}
Using with Go's Native Server Mux
import (
    actuator "github.com/sinhashubham95/go-actuator"
    "net/http"
)

// create a server
mux := &http.ServeMux{}

// get the handler for actuator
actuatorHandler := actuator.GetActuatorHandler(&Config{})
// configure the handler at this base endpoint
mux.Handle("/actuator", actuatorHandler)

// configure other handlers
....
Using with Fast HTTP
import (
	"strings"
	
    "github.com/valyala/fasthttp"
    actuator "github.com/sinhashubham95/go-actuator"
)

// get the handler for actuator
actuatorHandler := fasthttp.NewFastHTTPHandlerFunc(actuator.GetActuatorHandler(&Config{}))

// create a fast http handler
handler := func(ctx *fasthttp.RequestCtx) {
    if strings.HasPrefix(ctx.Path(), "/actuator") {
        // use the actuator handler
    	actuatorHandler(ctx)
    	return
    }
    // other request handler calls
}
fasthttp.ListenAndServe(":8080", handler)
Using with GIN
import (
    "github.com/gin-gonic/gin"
    actuator "github.com/sinhashubham95/go-actuator"
	"github.com/sinhashubham95/go-actuator/models"
)

// create the gin engine
engine := gin.Default()

// get the handler for actuator
actuatorHandler := actuator.GetActuatorHandler(&Config{})
ginActuatorHandler := func(ctx *gin.Context) {
	actuatorHandler(ctx.Writer, ctx.Request)
}

engine.GET("/actuator/*endpoint", ginActuatorHandler)

Endpoints

Env - /actuator/env

This is used to get all the environment variables for the runtime where the application is running. Note that to use this, you need to pass the runtime environment as an application flag as follows.

go build
./${APPLICATION_NAME}
{
  "env_key_1": "env_value_1",
  "env_key_2": "env_value_2"
}
Info - /actuator/info

This is used to get the basic information for an application. To get the correct and relevant information for your application you need to change the build script as well as the run script for your application as follows.

buildStamp=$(date -u '+%Y-%m-%d_%I:%M:%S%p')
commitId=$(git rev-list -1 HEAD)
commitTime=$(git show -s --format=%ci "$commitId")
commitAuthor=$(git --no-pager show -s --format='%an <%ae>' "$commitId")
gitUrl=$(git config --get remote.origin.url)
userName=$(whoami)
hostName=$(hostname)
go build -ldflags "<other linking params> -X github.com/sinhashubham95/go-actuator.BuildStamp=$buildStamp -X github.com/sinhashubham95/go-actuator.GitCommitID=$commitId -X github.com/sinhashubham95/go-actuator.GitPrimaryBranch=$2 -X github.com/sinhashubham95/go-actuator.GitURL=$gitUrl -X github.com/sinhashubham95/go-actuator.Username=$userName -X github.com/sinhashubham95/go-actuator.HostName=$hostName  -X \"github.com/sinhashubham95/go-actuator.GitCommitTime=$commitTime\" -X \"github.com/sinhashubham95/go-actuator.GitCommitAuthor=$commitAuthor\""
./${APPLICATION_NAME}
{
  "application": {
    "env": "ENVIRONMENT",
    "name": "APPLICATION_NAME",
    "version": "APPLICATION_VERSION"
  },
  "git": {
    "username": "s0s01qp",
    "hostName": "m-C02WV1L6HTD5",
    "buildStamp": "2019-08-22_09:44:04PM",
    "commitAuthor": "Shubham Sinha ",
    "commitId": "836475215e3ecf0ef26e0d5b65a9db626568ef89",
    "commitTime": "2019-08-23 02:27:26 +0530",
    "branch": "master",
    "url": "https://gecgithub01.walmart.com/RT-Integrated-Fulfillment/gif-ui-bff.git"
  },
  "runtime": {
    "arch": "",
    "os": "",
    "port": 8080,
    "runtimeVersion": ""
  }
}
Metrics - /actuator/metrics

This is used to get the runtime memory statistics for your application. You can find the definition of each of the fields here.

{
  "alloc": 2047816,
  "totalAlloc": 2850832,
  "sys": 73942024,
  "lookups": 0,
  "mAllocations": 15623,
  "frees": 9223,
  "heapAlloc": 2047816,
  "heapSys": 66551808,
  "heapIdle": 62832640,
  "heapInUse": 3719168,
  "heapReleased": 62570496,
  "heapObjects": 6400,
  "stackInUse": 557056,
  "stackSys": 557056,
  "mSpanInUse": 81056,
  "mSpanSys": 81920,
  "MCacheInUse": 19200,
  "mCacheSys": 32768,
  "buckHashSys": 1446250,
  "gcSys": 4225056,
  "otherSys": 1047166,
  "nextGC": 4194304,
  "lastGC": 1627102938524536000,
  "pauseTotalNs": 35655,
  "pauseNs": [
    35655
  ],
  "pauseEnd": [
    1627102938524536000
  ],
  "numGC": 1,
  "numForcedGC": 0,
  "gcCPUFraction": 0.000005360999257331059,
  "enableGC": true,
  "debugGC": false,
  "BySize": [
    {
      "Size": 0,
      "MAllocations": 0,
      "Frees": 0
    }
  ]
}
Ping - /actuator/ping

This is the lightweight ping endpoint that can be used along with your load balancer. This is used to know the running status of your application.

Shutdown - /actuator/shutdown

This is used to bring the application down.

Thread dump - /actuator/threadDump

This is used to get the trace of all the goroutines.

goroutine profile: total 1
1 @ 0x103af45 0x10337fb 0x10688f5 0x10c4de5 0x10c58b5 0x10c5897 0x1117e0f 0x1124391 0x11355e8 0x113576f 0x12037a5 0x1203676 0x1217025 0x1217007 0x121db9a 0x121e5b5 0x106e3e1
#	0x10688f4	internal/poll.runtime_pollWait+0x54				/Users/s0s01qp/go/go1.16.6/src/runtime/netpoll.go:222
#	0x10c4de4	internal/poll.(*pollDesc).wait+0x44				/Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_poll_runtime.go:87
#	0x10c58b4	internal/poll.(*pollDesc).waitRead+0x1d4			/Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_poll_runtime.go:92
#	0x10c5896	internal/poll.(*FD).Read+0x1b6					/Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_unix.go:166
#	0x1117e0e	net.(*netFD).Read+0x4e						/Users/s0s01qp/go/go1.16.6/src/net/fd_posix.go:55
#	0x1124390	net.(*conn).Read+0x90						/Users/s0s01qp/go/go1.16.6/src/net/net.go:183
#	0x11355e7	bufio.(*Reader).fill+0x107					/Users/s0s01qp/go/go1.16.6/src/bufio/bufio.go:101
#	0x113576e	bufio.(*Reader).Peek+0x4e					/Users/s0s01qp/go/go1.16.6/src/bufio/bufio.go:139
#	0x12037a4	github.com/valyala/fasthttp.(*RequestHeader).tryRead+0x64	/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1520
#	0x1203675	github.com/valyala/fasthttp.(*RequestHeader).readLoop+0x55	/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1506
#	0x1217024	github.com/valyala/fasthttp.(*RequestHeader).Read+0x1ae4	/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1497
#	0x1217006	github.com/valyala/fasthttp.(*Server).serveConn+0x1ac6		/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/server.go:2112
#	0x121db99	github.com/valyala/fasthttp.(*workerPool).workerFunc+0xb9	/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/workerpool.go:223
#	0x121e5b4	github.com/valyala/fasthttp.(*workerPool).getCh.func1+0x34	/Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/workerpool.go:195

Documentation

Index

Constants

View Source
const (
	Env = iota
	Info
	Metrics
	Ping
	//Shutdown
	GoRoutineDump
	ThreadDump
)

Endpoints enumeration

View Source
const (
	EnvKey = "env"
)

Common Constants

Variables

View Source
var (
	BuildStamp       string
	GitCommitAuthor  string
	GitCommitID      string
	GitCommitTime    string
	GitPrimaryBranch string
	GitURL           string
	HostName         string
	Username         string
)

Set of linked build time variables for providing relevant information for the application

AllEndpoints is the list of endpoints supported

Functions

func GetActuatorHandler

func GetActuatorHandler(config *Config) http.HandlerFunc

GetActuatorHandler is used to get the handler function for the actuator endpoints This single handler is sufficient for handling all the endpoints.

func HandleDump added in v0.9.2

func HandleDump(body []byte, err error, writer http.ResponseWriter, _ *http.Request)

Types

type BySizeElement

type BySizeElement struct {
	// Size is the maximum byte size of an object in this
	// size class.
	Size uint32

	// M-allocations is the cumulative count of heap objects
	// allocated in this size class. The cumulative bytes
	// of allocation is Size * M-allocations. The number of live
	// objects in this size class is M-allocations - Frees.
	MAllocations uint64

	// Frees is the cumulative count of heap objects freed
	// in this size class.
	Frees uint64
}

BySizeElement reports per-size class allocation statistics. BySize[N] gives statistics for allocations of size S where BySize[N-1].Size < S ≤ BySize[N].Size. This does not report allocations larger than BySize[60].Size.

type Config

type Config struct {
	Endpoints []int
	Env       string
	Name      string
	Port      int
	Version   string
}

Config is the set of configurable parameters for the actuator setup

type CpuStats added in v0.9.2

type CpuStats struct {
	NumCpu int `json:"numCpu"`
}

type MemStats

type MemStats struct {
	// Alloc is bytes of allocated heap objects.
	Alloc uint64 `json:"alloc"`

	// TotalAlloc is cumulative bytes allocated for heap objects.
	// This increases as heap objects are allocated, but
	// unlike Alloc, it does not decrease when
	// objects are freed.
	TotalAlloc uint64 `json:"totalAlloc"`

	// Sys is the total bytes of memory obtained from the OS.
	// It is the sum of the XSys fields below. It measures the
	// virtual address space reserved by the Go runtime for the
	// heap, stacks, and other internal data structures. It's
	// likely that not all of the virtual address space is backed
	// by physical memory at any given moment, though in general
	// it all was at some point.
	Sys uint64 `json:"sys"`

	// Lookups is the number of pointer lookups performed by the
	// runtime.
	// This is primarily useful for debugging runtime internals.
	Lookups uint64 `json:"lookups"`

	// MAllocations is the cumulative count of heap objects allocated.
	// The number of live objects is MAllocations - Frees.
	MAllocations uint64 `json:"mAllocations"`

	// Frees is the cumulative count of heap objects freed.
	Frees uint64 `json:"frees"`

	// HeapAlloc is bytes of allocated heap objects.
	// "Allocated" heap objects include all reachable objects, as
	// well as unreachable objects that the garbage collector has
	// not yet freed. Specifically, HeapAlloc increases as heap
	// objects are allocated and decreases as the heap is swept
	// and unreachable objects are freed. Sweeping occurs
	// incrementally between GC cycles, so these two processes
	// occur simultaneously, and as a result HeapAlloc tends to
	// change smoothly (in contrast with the sawtooth that is
	// typical of stop-the-world garbage collectors).
	HeapAlloc uint64 `json:"heapAlloc"`

	// HeapSys is bytes of heap memory obtained from the OS.
	// It measures the amount of virtual address space
	// reserved for the heap. This includes virtual address space
	// that has been reserved but not yet used, which consumes no
	// physical memory, but tends to be small, as well as virtual
	// address space for which the physical memory has been
	// returned to the OS after it became unused (see HeapReleased
	// for a measure of the latter).
	// It estimates the largest size the heap has had.
	HeapSys uint64 `json:"heapSys"`

	// HeapIdle is bytes in idle (unused) spans.
	// Idle spans have no objects in them. These spans could be
	// (and may already have been) returned to the OS, or they can
	// be reused for heap allocations, or they can be reused as
	// stack memory.
	// HeapIdle minus HeapReleased estimates the amount of memory
	// that could be returned to the OS, but is being retained by
	// the runtime, so it can grow the heap without requesting more
	// memory from the OS. If this difference is significantly
	// larger than the heap size, it indicates there was a recent
	// transient spike in live heap size.
	HeapIdle uint64 `json:"heapIdle"`

	// HeapInuse is bytes in in-use spans.
	// In-use spans have at least one object in them. These spans
	// can only be used for other objects of roughly the same
	// size.
	// HeapInuse minus HeapAlloc estimates the amount of memory
	// that has been dedicated to particular size classes, but is
	// not currently being used. This is an upper bound on
	// fragmentation, but in general this memory can be reused
	// efficiently.
	HeapInuse uint64 `json:"heapInUse"`

	// HeapReleased is bytes of physical memory returned to the OS.
	// This counts heap memory from idle spans that was returned
	// to the OS and has not yet been reacquired for the heap.
	HeapReleased uint64 `json:"heapReleased"`

	// HeapObjects is the number of allocated heap objects.
	// Like HeapAlloc, this increases as objects are allocated and
	// decreases as the heap is swept and unreachable objects are
	// freed.
	HeapObjects uint64 `json:"heapObjects"`

	// StackInuse is bytes in stack spans.
	// In-use stack spans have at least one stack in them. These
	// spans can only be used for other stacks of the same size.
	// There is no StackIdle because unused stack spans are
	// returned to the heap (and hence counted toward HeapIdle).
	StackInuse uint64 `json:"stackInUse"`

	// StackSys is bytes of stack memory obtained from the OS.
	// StackSys is StackInuse, plus any memory obtained directly
	// from the OS for OS thread stacks (which should be minimal).
	StackSys uint64 `json:"stackSys"`

	// MSpanInuse is bytes of allocated m-span structures.
	MSpanInuse uint64 `json:"mSpanInUse"`

	// MSpanSys is bytes of memory obtained from the OS for m-span
	// structures.
	MSpanSys uint64 `json:"mSpanSys"`

	// MCacheInuse is bytes of allocated m-cache structures.
	MCacheInuse uint64 `json:"MCacheInUse"`

	// MCacheSys is bytes of memory obtained from the OS for
	// m-cache structures.
	MCacheSys uint64 `json:"mCacheSys"`

	// BuckHashSys is bytes of memory in profiling bucket hash tables.
	BuckHashSys uint64 `json:"buckHashSys"`

	// GCSys is bytes of memory in garbage collection metadata.
	GCSys uint64 `json:"gcSys"`

	// OtherSys is bytes of memory in miscellaneous off-heap
	// runtime allocations.
	OtherSys uint64 `json:"otherSys"`

	// NextGC is the target heap size of the next GC cycle.
	// The garbage collector's goal is to keep HeapAlloc ≤ NextGC.
	// At the end of each GC cycle, the target for the next cycle
	// is computed based on the amount of reachable data and the
	// value of GO GC.
	NextGC uint64 `json:"nextGC"`

	// LastGC is the time the last garbage collection finished, as
	// nanoseconds since 1970 (the UNIX epoch).
	LastGC uint64 `json:"lastGC"`

	// PauseTotalNs is the cumulative nanoseconds in GC
	// stop-the-world pauses since the program started.
	// During a stop-the-world pause, all goroutines are paused
	// and only the garbage collector can run.
	PauseTotalNs uint64 `json:"pauseTotalNs"`

	// PauseNs is a circular buffer of recent GC stop-the-world
	// pause times in nanoseconds.
	//
	// The most recent pause is at PauseNs[(NumGC+255)%256]. In
	// general, PauseNs[N%256] records the time paused in the most
	// recent N%256th GC cycle. There may be multiple pauses per
	// GC cycle; this is the sum of all pauses during a cycle.
	PauseNs [256]uint64 `json:"pauseNs"`

	// PauseEnd is a circular buffer of recent GC pause end times,
	// as nanoseconds since 1970 (the UNIX epoch).
	// This buffer is filled the same way as PauseNs. There may be
	// multiple pauses per GC cycle; this records the end of the
	// last pause in a cycle.
	PauseEnd [256]uint64 `json:"pauseEnd"`

	// NumGC is the number of completed GC cycles.
	NumGC uint32 `json:"numGC"`

	// NumForcedGC is the number of GC cycles that were forced by
	// the application calling the GC function.
	NumForcedGC uint32 `json:"numForcedGC"`

	// GCCPUFraction is the fraction of this program's available
	// CPU time used by the GC since the program started.
	//
	// GCCPUFraction is expressed as a number between 0 and 1,
	// where 0 means GC has consumed none of this program's CPU. A
	// program's available CPU time is defined as the integral of
	// GO MAX PROCESSES since the program started. That is, if
	// GO MAX PROCESSES is 2 and a program has been running for 10
	// seconds, its "available CPU" is 20 seconds. GCCPUFraction
	// does not include CPU time used for write barrier activity.
	//
	// This is the same as the fraction of CPU reported by
	// GO DEBUG = gc trace = 1.
	GCCPUFraction float64 `json:"gcCPUFraction"`

	// EnableGC indicates that GC is enabled. It is always true,
	// even if GO GC = off.
	EnableGC bool `json:"enableGC"`

	// DebugGC is currently unused.
	DebugGC bool `json:"debugGC"`

	// BySize reports per-size class allocation statistics.
	// BySize[N] gives statistics for allocations of size S where
	// BySize[N-1].Size < S ≤ BySize[N].Size.
	// This does not report allocations larger than BySize[60].Size.
	BySize []BySizeElement
}

MemStats is the memory statistics for the current running application

type MetricsResponse

type MetricsResponse struct {
	CpuStats    CpuStats    `json:"cpu"`
	ThreadStats ThreadStats `json:"threadstats"`
	MemStats    MemStats    `json:"memory"`
}

MetricsResponse is the response for the metrics endpoint

type ThreadStats added in v0.9.3

type ThreadStats struct {
	GoRoutines int `json:"goRoutines"`
	Threads    int `json:"threads"`
}

Jump to

Keyboard shortcuts

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