-
Notifications
You must be signed in to change notification settings - Fork 143
/
cmd.go
196 lines (172 loc) · 5.06 KB
/
cmd.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Copyright 2020 The PipeCD Authors.
//
// 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 cli
import (
"context"
"io"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"cloud.google.com/go/profiler"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/expfmt"
"github.com/spf13/cobra"
"go.uber.org/zap"
"google.golang.org/api/option"
"github.com/pipe-cd/pipecd/pkg/log"
"github.com/pipe-cd/pipecd/pkg/version"
)
type Input struct {
Logger *zap.Logger
Flags TelemetryFlags
Stdin io.Reader
}
type Runner func(ctx context.Context, input Input) error
func WithContext(runner Runner) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(ch)
return runWithContext(cmd, ch, runner)
}
}
func runWithContext(cmd *cobra.Command, signalCh <-chan os.Signal, runner Runner) error {
flags, err := parseTelemetryFlags(cmd.Flags())
if err != nil {
return err
}
input := Input{
Flags: flags,
Stdin: cmd.InOrStdin(),
}
service := extractServiceName(cmd)
version := version.Get()
// Initialize logger.
logger, err := newLogger(service, version.Version, flags.LogLevel, flags.LogEncoding)
if err != nil {
return err
}
defer logger.Sync()
input.Logger = logger
// Start running profiler.
if flags.Profile {
if err := startProfiler(service, version.Version, flags.ProfilerCredentialsFile, flags.ProfileDebugLogging, logger); err != nil {
logger.Error("failed to run profiler", zap.Error(err))
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
select {
case s := <-signalCh:
logger.Info("stopping due to signal", zap.Any("signal", s))
cancel()
case <-ctx.Done():
}
}()
return runner(ctx, input)
}
func newLogger(service, version, level, encoding string) (*zap.Logger, error) {
configs := log.DefaultConfigs
configs.ServiceContext = &log.ServiceContext{
Service: service,
Version: version,
}
configs.Level = level
configs.Encoding = log.EncodingType(encoding)
return log.NewLogger(configs)
}
func startProfiler(service, version, credentialsFile string, debugLogging bool, logger *zap.Logger) error {
var options []option.ClientOption
if credentialsFile != "" {
options = append(options, option.WithCredentialsFile(credentialsFile))
}
config := profiler.Config{
Service: service,
ServiceVersion: version,
DebugLogging: debugLogging,
}
logger.Info("start running profiler", zap.String("service", service))
return profiler.Start(config, options...)
}
func (t Input) PrometheusMetricsHandler() http.Handler {
if t.Flags.Metrics {
return promhttp.Handler()
}
var empty http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
}
return empty
}
func (t Input) PrometheusMetricsHandlerFor(r *prometheus.Registry) http.Handler {
if t.Flags.Metrics {
return promhttp.HandlerFor(r, promhttp.HandlerOpts{})
}
var empty http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
}
return empty
}
type MetricsBuilder interface {
Build() (io.Reader, error)
}
func (t Input) CustomMetricsHandlerFor(reg prometheus.Gatherer, mb MetricsBuilder) http.Handler {
if !t.Flags.Metrics {
var empty http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
}
return empty
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mfs, err := reg.Gather()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Currently, use the encoder with default format expfmt.FmtText as of
// the prometheus exporter handler will returns that format in case
// no specific format type is set.
enc := expfmt.NewEncoder(w, expfmt.FmtText)
for _, mf := range mfs {
if err := enc.Encode(mf); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if closer, ok := enc.(expfmt.Closer); ok {
if err := closer.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
rc, err := mb.Build()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = io.Copy(w, rc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
return h
}
func extractServiceName(cmd *cobra.Command) string {
return strings.Replace(cmd.CommandPath(), " ", ".", -1)
}