-
Notifications
You must be signed in to change notification settings - Fork 59
/
main.go
396 lines (336 loc) · 10.6 KB
/
main.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/openshift/operator-framework-olm/pkg/profiling/config"
)
const (
profileConfigMapLabelKey = "olm.openshift.io/pprof"
pprofSecretName = "pprof-cert"
validity = 24 * time.Hour
minValidity = 15 * time.Minute
)
var (
rootCmd = newCmd()
// Used for flags
namespace string
configMountPath string
certMountPath string
)
func init() {
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "default", "The Kubernetes namespace where the generated configMaps should exist. Defaults to \"default\".")
rootCmd.MarkFlagRequired("namespace")
rootCmd.PersistentFlags().StringVarP(&configMountPath, "config-mount-path", "c", "/etc/config", "The path to the collect-profiles configuration file.")
rootCmd.MarkFlagRequired("config-mount-path")
rootCmd.PersistentFlags().StringVarP(&certMountPath, "cert-mount-path", "", "/var/run/secrets/serving-cert", "The path to the tls cert used by the client making https requests against the pprof URLs.")
}
func main() {
Execute()
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
logrus.Fatal(err)
os.Exit(1)
}
}
func getTruePointer() *bool {
trueBool := true
return &trueBool
}
func newCmd() *cobra.Command {
var cfg config.Configuration
return &cobra.Command{
Use: "collect-profiles configMapName:url",
Short: "Retrieves the pprof data from a URL and stores it in a configMap.",
Long: `The collect-profiles command makes https requests against pprof URLs
provided as arguments and stores that information in immutable configMaps.
# Example command with multiple arguments
./collect-profiles -n - openshift-operator-lifecycle-manager \
- --config-mount-path \
- /etc/config \
- --cert-mount-path \
- /var/run/secrets/serving-cert \
- olm-operator-heap-:https://olm-operator-metrics:8443/debug/pprof/heap \
- catalog-operator-heap-:https://catalog-operator-metrics:8443/debug/pprof/heap
`,
SilenceUsage: true,
PersistentPreRunE: func(*cobra.Command, []string) error {
return cfg.Load()
},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
logrus.Info("No arguments provided, exiting")
return nil
}
jobConfig, err := config.GetConfig(configMountPath)
if err != nil {
logrus.Infof("error retrieving job config")
return err
}
// Exit if job is disabled
if jobConfig.Disabled {
logrus.Infof("CronJob disabled, exiting")
return nil
}
// Validate input
validatedArguments := make([]*argument, len(args))
for i, arg := range args {
a, err := newArgument(arg)
if err != nil {
return err
}
validatedArguments[i] = a
}
// Get existing configmaps
existingConfigMaps := &corev1.ConfigMapList{}
if err := cfg.Client.List(cmd.Context(), existingConfigMaps, client.InNamespace(namespace), client.HasLabels{profileConfigMapLabelKey}); err != nil {
return err
}
newestConfigMaps, expiredConfigMaps := separateConfigMapsIntoNewestAndExpired(existingConfigMaps.Items)
// Attempt to delete all but the newest configMaps generated by this job
errs := []error{}
for _, cm := range expiredConfigMaps {
if err := cfg.Client.Delete(cmd.Context(), &cm); err != nil {
errs = append(errs, err)
continue
}
logrus.Infof("Successfully deleted configMap %s/%s", cm.GetNamespace(), cm.GetName())
}
// If a delete call failed, abort to avoid creating new configMaps
if len(errs) != 0 {
return fmt.Errorf("error deleting expired pprof configMaps: %v", errs)
}
certPath := filepath.Join(certMountPath, corev1.TLSCertKey)
keyPath := filepath.Join(certMountPath, corev1.TLSPrivateKeyKey)
var tlsCert *tls.Certificate
if tlsCert, err = verifyCertAndKey(certPath, keyPath); err != nil {
logrus.Infof("error verifying provided cert and key: %v", err)
logrus.Info("generating a new cert and key")
if tlsCert, err = populateServingCert(cmd.Context(), cfg.Client); err != nil {
return err
}
// Continue with new certificate/keypair
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
Certificates: []tls.Certificate{*tlsCert},
},
},
}
// Track successfully created configMaps by generateName for each endpoint being scrapped.
createdCM := map[string]struct{}{}
for _, a := range validatedArguments {
b, err := requestURLBody(httpClient, a.url)
if err != nil {
logrus.Infof("error retrieving pprof profile: %v", err)
continue
}
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
GenerateName: a.generateName,
Namespace: namespace,
Labels: map[string]string{
profileConfigMapLabelKey: "",
},
},
Immutable: getTruePointer(),
BinaryData: map[string][]byte{
"profile.pb.gz": b,
},
}
if err := cfg.Client.Create(cmd.Context(), cm); err != nil {
logrus.Errorf("error created configMap %s/%s: %v", cm.GetNamespace(), cm.GetName(), err)
continue
}
logrus.Infof("Successfully created configMap %s/%s", cm.GetNamespace(), cm.GetName())
createdCM[a.generateName] = struct{}{}
}
// Delete the configMaps which are no longer the newest
for _, cm := range newestConfigMaps {
// Don't delete ConfigMaps that were not replaced
// Also prevents deletes of configMaps with generateNames not included in command
if _, ok := createdCM[cm.GenerateName]; !ok {
continue
}
if err := cfg.Client.Delete(cmd.Context(), &cm); err != nil {
errs = append(errs, err)
continue
}
logrus.Infof("Successfully deleted configMap %s/%s", cm.GetNamespace(), cm.GetName())
}
if len(errs) != 0 {
return fmt.Errorf("error deleting existing pprof configMaps: %v", errs)
}
return nil
},
}
}
func verifyCertAndKey(certPath, keyPath string) (*tls.Certificate, error) {
fi, err := os.Stat(certPath)
if err != nil {
return nil, err
}
if fi.Size() == 0 {
return nil, fmt.Errorf("cert file should not be empty")
}
fi, err = os.Stat(keyPath)
if err != nil {
return nil, err
}
if fi.Size() == 0 {
return nil, fmt.Errorf("key file should not be empty")
}
tlsCert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
if err != nil {
return nil, err
}
now := time.Now()
if x509Cert.NotAfter.Before(now) {
return nil, fmt.Errorf("certificate has expired")
}
// Since this cron runs every 15 minutes, we assume that the job takes less
// than 15 minutes, so make sure there's still 15 minutes of validity left
if x509Cert.NotAfter.Before(now.Add(minValidity)) {
return nil, fmt.Errorf("certificate expires in less than 15 minutes")
}
return &tlsCert, nil
}
func separateConfigMapsIntoNewestAndExpired(configMaps []corev1.ConfigMap) (newestCMs []corev1.ConfigMap, expiredCMs []corev1.ConfigMap) {
// Group ConfigMaps by GenerateName
newestConfigMaps := map[string]corev1.ConfigMap{}
for _, cm := range configMaps {
if _, ok := newestConfigMaps[cm.GenerateName]; !ok {
newestConfigMaps[cm.GenerateName] = cm
continue
}
if cm.CreationTimestamp.After(newestConfigMaps[cm.GenerateName].CreationTimestamp.Time) {
newestConfigMaps[cm.GenerateName], cm = cm, newestConfigMaps[cm.GenerateName]
}
expiredCMs = append(expiredCMs, cm)
}
for _, v := range newestConfigMaps {
newestCMs = append(newestCMs, v)
}
return newestCMs, expiredCMs
}
type argument struct {
generateName string
url *url.URL
}
func newArgument(s string) (*argument, error) {
splitStrings := strings.SplitN(s, ":", 2)
if len(splitStrings) != 2 {
return nil, fmt.Errorf("%s is an invalid argument, should match configMapName:url", s)
}
url, err := url.Parse(splitStrings[1])
if err != nil {
return nil, err
}
if strings.ToLower(url.Scheme) != "https" {
return nil, fmt.Errorf("URL Scheme must be HTTPS")
}
arg := &argument{
generateName: splitStrings[0],
url: url,
}
return arg, nil
}
func requestURLBody(httpClient *http.Client, u *url.URL) ([]byte, error) {
response, err := httpClient.Do(&http.Request{
Method: http.MethodGet,
URL: u,
})
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s responded with %d status code instead of %d", u, response.StatusCode, http.StatusOK)
}
var b bytes.Buffer
if _, err := io.Copy(&b, response.Body); err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
return b.Bytes(), nil
}
func populateServingCert(ctx context.Context, client client.Client) (*tls.Certificate, error) {
secret := &corev1.Secret{}
err := client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: pprofSecretName}, secret)
if err != nil {
return nil, err
}
certPEMBytes, privKeyPEMBytes, err := generateCertAndKey()
if err != nil {
return nil, err
}
secret.Data[corev1.TLSCertKey] = certPEMBytes
secret.Data[corev1.TLSPrivateKeyKey] = privKeyPEMBytes
if err = client.Update(ctx, secret); err != nil {
return nil, err
}
// Create tlsCert for client use
tlsCert, err := tls.X509KeyPair(certPEMBytes, privKeyPEMBytes)
if err != nil {
return nil, err
}
return &tlsCert, nil
}
func generateCertAndKey() ([]byte, []byte, error) {
now := time.Now()
cert := &x509.Certificate{
SerialNumber: big.NewInt(1658),
Subject: pkix.Name{
Organization: []string{"Red Hat, Inc."},
},
NotBefore: now,
NotAfter: now.Add(validity),
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}
keyPair, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return nil, nil, err
}
// Generate a DER-encoded self-signed certificate
certDER, err := x509.CreateCertificate(rand.Reader, cert, cert, &keyPair.PublicKey, keyPair)
if err != nil {
return nil, nil, err
}
certPEM := new(bytes.Buffer)
pem.Encode(certPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
})
privKeyPEM := new(bytes.Buffer)
pem.Encode(privKeyPEM, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(keyPair),
})
return certPEM.Bytes(), privKeyPEM.Bytes(), nil
}