A common pattern in Go libraries is to take advantage of init functions to do things like settings up defaults in loggers, automatic metrics instrumentation, flag values, debugging tools or database drivers. With monorepo culture prevalent in larger microservices based projects, this can lead to a few easily preventable problems:
There is an environment variable in Linux libc's called
LD_PRELOAD that will
load arbitrary shared objects into ram before anything else is started. This
has been used for good and evil, but the
behavior is the same basic idea as underscore imports in Go.
To use this, add
gopreload to your application's imports:
// gopreload.go package main /* This file is separate to make it very easy to both add into an application, but also very easy to remove. */ import _ "github.com/Xe/gopreload"
and then compile
$ go get -d github.com/Xe/gopreload/manhole $ go build -buildmode plugin -o $GOPATH/manhole.so github.com/Xe/gopreload/manhole
then run your program with
GO_PRELOAD set to the path of
$ export GO_PRELOAD=$GOPATH/manhole.so $ go run *.go 2017/03/25 10:56:22 gopreload: trying to open: /home/xena/go/manhole.so 2017/03/25 10:56:22 manhole: Now listening on http://127.0.0.2:37588
That endpoint has pprof and a few other fun tools set up, making it a good stopgap "manhole" into the performance of a service.
This package assumes that programs run using it are never started with environment
variables that are set by unauthenticated users. Any errors in loading the plugins
will be logged using the standard library logger
log and ignored.
This has about the same security implications as
LD_PRELOAD does in most
Linux distributions, but the risk is minimal compared to the massive benefit for
being able to have arbitrary background services all be able to be dug into using
the same tooling or being able to have metric submission be completely separated
from the backend metric creation. Common logging setup processes can be always
loaded, making the default logger settings into the correct settings.
This article was posted on M03 25 2017. Facts and circumstances may have changed since publication. Please contact me before jumping to conclusions if something seems wrong or unclear.