From d28ca541292c5fa9230c153999ec729eac98a611 Mon Sep 17 00:00:00 2001 From: Johannes Grassler Date: Tue, 28 Nov 2017 18:16:38 +0100 Subject: [PATCH] Use systemd notification where applicable With this change in place, the grafana service will signal readiness to serve by writing "READY=1" to the path specified through the NOTIFY_SOCKET environment variable. If this environment variable is not present or empty, no notification will happen. This notification is the standard systemd mechanism for indicating a service is ready to serve. For Grafana this may be a couple of seconds from startup due to database migrations. This change also adjusts the Grafana systemd service definition to make use of this feature. --- packaging/rpm/systemd/grafana-server.service | 2 +- pkg/cmd/grafana-server/server.go | 2 ++ pkg/util/sdnotify.go | 34 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 pkg/util/sdnotify.go diff --git a/packaging/rpm/systemd/grafana-server.service b/packaging/rpm/systemd/grafana-server.service index 3e018e8b176..b23e5196e17 100644 --- a/packaging/rpm/systemd/grafana-server.service +++ b/packaging/rpm/systemd/grafana-server.service @@ -9,7 +9,7 @@ After=postgresql.service mariadb.service mysql.service EnvironmentFile=/etc/sysconfig/grafana-server User=grafana Group=grafana -Type=simple +Type=notify Restart=on-failure WorkingDirectory=/usr/share/grafana RuntimeDirectory=grafana diff --git a/pkg/cmd/grafana-server/server.go b/pkg/cmd/grafana-server/server.go index 1d3ac092734..476eb2f433f 100644 --- a/pkg/cmd/grafana-server/server.go +++ b/pkg/cmd/grafana-server/server.go @@ -29,6 +29,7 @@ import ( "github.com/grafana/grafana/pkg/social" "github.com/grafana/grafana/pkg/tracing" + "github.com/grafana/grafana/pkg/util" ) func NewGrafanaServer() models.GrafanaServer { @@ -96,6 +97,7 @@ func (g *GrafanaServerImpl) Start() { return } + util.SdNotify("READY=1") g.startHttpServer() } diff --git a/pkg/util/sdnotify.go b/pkg/util/sdnotify.go new file mode 100644 index 00000000000..b5cd4a4a45d --- /dev/null +++ b/pkg/util/sdnotify.go @@ -0,0 +1,34 @@ +package util + +import ( + "errors" + "net" + "os" +) + +var NoNotifySocket = errors.New("NOTIFY_SOCKET environment variable empty or unset.") + +func SdNotify(state string) error { + notifySocket := os.Getenv("NOTIFY_SOCKET") + + if notifySocket == "" { + return NoNotifySocket + } + + socketAddr := &net.UnixAddr{ + Name: notifySocket, + Net: "unixgram", + } + + conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) + + if err != nil { + return err + } + + _, err = conn.Write([]byte(state)) + + conn.Close() + + return err +}