forked from hipages/php-fpm_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
139 lines (116 loc) · 4.47 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright © 2018 Enrico Stahn <[email protected]>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/hipages/php-fpm_exporter/phpfpm"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/cobra"
)
// Configuration variables
var (
listeningAddress string
metricsEndpoint string
scrapeURIs []string
fixProcessCount bool
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
log.Infof("Starting server on %v with path %v", listeningAddress, metricsEndpoint)
pm := phpfpm.PoolManager{}
for _, uri := range scrapeURIs {
pm.Add(uri)
}
exporter := phpfpm.NewExporter(pm)
if fixProcessCount {
log.Info("Idle/Active/Total Processes will be calculated by php-fpm_exporter.")
exporter.CountProcessState = true
}
prometheus.MustRegister(exporter)
srv := &http.Server{
Addr: listeningAddress,
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
}
http.Handle(metricsEndpoint, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`<html>
<head><title>php-fpm_exporter</title></head>
<body>
<h1>php-fpm_exporter</h1>
<p><a href='` + metricsEndpoint + `'>Metrics</a></p>
</body>
</html>`))
if err != nil {
log.Error()
}
})
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Error(err)
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) or SIGTERM
// SIGKILL, SIGQUIT will not be caught.
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
var wait time.Duration
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Error during shutdown", err)
}
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Info("Shutting down")
os.Exit(0)
},
}
func init() {
RootCmd.AddCommand(serverCmd)
serverCmd.Flags().StringVar(&listeningAddress, "web.listen-address", ":9253", "Address on which to expose metrics and web interface.")
serverCmd.Flags().StringVar(&metricsEndpoint, "web.telemetry-path", "/metrics", "Path under which to expose metrics.")
serverCmd.Flags().StringSliceVar(&scrapeURIs, "phpfpm.scrape-uri", []string{"tcp://127.0.0.1:9000/status"}, "FastCGI address, e.g. unix:///tmp/php.sock;/status or tcp://127.0.0.1:9000/status")
serverCmd.Flags().BoolVar(&fixProcessCount, "phpfpm.fix-process-count", false, "Enable to calculate process numbers via php-fpm_exporter since PHP-FPM sporadically reports wrong active/idle/total process numbers.")
// Workaround since vipers BindEnv is currently not working as expected (see https://github.com/spf13/viper/issues/461)
envs := map[string]string{
"PHP_FPM_WEB_LISTEN_ADDRESS": "web.listen-address",
"PHP_FPM_WEB_TELEMETRY_PATH": "web.telemetry-path",
"PHP_FPM_SCRAPE_URI": "phpfpm.scrape-uri",
"PHP_FPM_FIX_PROCESS_COUNT": "phpfpm.fix-process-count",
}
mapEnvVars(envs, serverCmd)
}