/
generate.go
694 lines (612 loc) · 17.9 KB
/
generate.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
package generate
import (
"errors"
"fmt"
"github.com/netapp/harvest/v2/cmd/tools/grafana"
"github.com/netapp/harvest/v2/cmd/tools/rest"
"github.com/netapp/harvest/v2/pkg/api/ontapi/zapi"
"github.com/netapp/harvest/v2/pkg/auth"
"github.com/netapp/harvest/v2/pkg/color"
"github.com/netapp/harvest/v2/pkg/conf"
"github.com/netapp/harvest/v2/pkg/logging"
"github.com/netapp/harvest/v2/third_party/tidwall/sjson"
"github.com/spf13/cobra"
"github.com/tidwall/gjson"
"io"
"log"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"text/template"
"time"
)
type PollerInfo struct {
ServiceName string
PollerName string
Port int
ConfigFile string
LogLevel int
Image string
ContainerName string
ShowPorts bool
IsFull bool
CertDir string
Mounts []string
}
type AdminInfo struct {
ServiceName string
Port int
ConfigFile string
Image string
ContainerName string
Enabled bool
CertDir string
}
type PollerTemplate struct {
Pollers []PollerInfo
Admin AdminInfo
}
type PromTemplate struct {
GrafanaPort int
PromPort int
}
type options struct {
Poller string
loglevel int
image string
filesdPath string
showPorts bool
outputPath string
certDir string
promPort int
grafanaPort int
mounts []string
configPath string
confPath string
}
var metricRe = regexp.MustCompile(`(\w+)\{`)
var opts = &options{
loglevel: 2,
image: "harvest:latest",
}
var Cmd = &cobra.Command{
Use: "generate",
Short: "Generate Harvest related files",
Long: "Generate Harvest related files",
}
var systemdCmd = &cobra.Command{
Use: "systemd",
Short: "generate Harvest systemd target for all pollers defined in config",
Run: doSystemd,
}
var dockerCmd = &cobra.Command{
Use: "docker",
Short: "generate Harvest docker-compose.yml target for all pollers defined in config",
Run: doDockerCompose,
}
var fullCmd = &cobra.Command{
Use: "full",
Short: "generate Harvest, Grafana, Prometheus docker-compose.yml target for all pollers defined in config",
Run: doDockerFull,
}
var metricCmd = &cobra.Command{
Use: "metrics",
Short: "generate Harvest metrics documentation",
Hidden: true,
Run: doGenerateMetrics,
}
var descCmd = &cobra.Command{
Use: "desc",
Short: "generate Description of panels",
Hidden: true,
Run: doDescription,
}
func doDockerFull(cmd *cobra.Command, _ []string) {
addRootOptions(cmd)
generateDocker(full)
}
func doSystemd(cmd *cobra.Command, _ []string) {
addRootOptions(cmd)
generateSystemd()
}
func doDockerCompose(cmd *cobra.Command, _ []string) {
addRootOptions(cmd)
generateDocker(harvest)
}
func doGenerateMetrics(cmd *cobra.Command, _ []string) {
addRootOptions(cmd)
counters, cluster := generateMetrics()
generateCounterTemplate(counters, cluster.Version)
}
func doDescription(cmd *cobra.Command, _ []string) {
addRootOptions(cmd)
counters, _ := generateMetrics()
grafana.VisitDashboards(
[]string{"grafana/dashboards/cmode"},
func(path string, data []byte) {
generateDescription(path, data, counters)
})
}
func addRootOptions(cmd *cobra.Command) {
opts.configPath = conf.ConfigPath(cmd.Root().PersistentFlags().Lookup("config").Value.String())
opts.confPath = cmd.Root().PersistentFlags().Lookup("confpath").Value.String()
}
const (
full = 0
harvest = 1
harvestAdminService = "harvest-admin.service"
)
func normalizeContainerNames(name string) string {
re := regexp.MustCompile("[._]")
return strings.ToLower(re.ReplaceAllString(name, "-"))
}
func generateDocker(kind int) {
var (
pollerTemplate PollerTemplate
configFilePath string
certDirPath string
out *os.File
)
pollerTemplate = PollerTemplate{}
promTemplate := PromTemplate{
opts.grafanaPort,
opts.promPort,
}
_, err := conf.LoadHarvestConfig(opts.configPath)
if err != nil {
logErrAndExit(err)
}
configFilePath = asComposePath(opts.configPath)
certDirPath = asComposePath(opts.certDir)
filesd := make([]string, 0, len(conf.Config.PollersOrdered))
for _, v := range conf.Config.PollersOrdered {
port, _ := conf.GetPrometheusExporterPorts(v, true)
pollerInfo := PollerInfo{
ServiceName: normalizeContainerNames(v),
PollerName: v,
ConfigFile: configFilePath,
Port: port,
LogLevel: opts.loglevel,
Image: opts.image,
ContainerName: normalizeContainerNames("poller_" + v),
ShowPorts: opts.showPorts,
IsFull: kind == full,
CertDir: certDirPath,
Mounts: makeMounts(v),
}
pollerTemplate.Pollers = append(pollerTemplate.Pollers, pollerInfo)
filesd = append(filesd, fmt.Sprintf("- targets: ['%s:%d']", pollerInfo.ServiceName, pollerInfo.Port))
}
t, err := template.New("docker-compose.tmpl").ParseFiles("container/onePollerPerContainer/docker-compose.tmpl")
if err != nil {
logErrAndExit(err)
}
color.DetectConsole("")
out, err = os.Create(opts.outputPath)
if err != nil {
logErrAndExit(err)
}
if kind == harvest {
// generate admin service if configuration is present in harvest config
if conf.Config.Admin.Httpsd.Listen != "" {
httpsd := conf.Config.Admin.Httpsd.Listen
adminPort := 8887
if s := strings.Split(httpsd, ":"); len(s) == 2 {
adminPort, err = strconv.Atoi(s[1])
if err != nil {
logErrAndExit(errors.New("invalid httpsd listen configuration. Valid configuration are <<addr>>:PORT or :PORT"))
}
} else {
logErrAndExit(errors.New("invalid httpsd listen configuration. Valid configuration are <<addr>>:PORT or :PORT"))
}
pollerTemplate.Admin = AdminInfo{
ServiceName: "admin",
ConfigFile: configFilePath,
Port: adminPort,
Image: opts.image,
ContainerName: "admin",
Enabled: true,
CertDir: certDirPath,
}
}
} else {
pt, err := template.New("prom-stack.tmpl").ParseFiles("prom-stack.tmpl")
if err != nil {
logErrAndExit(err)
}
promStackOut, err := os.Create("prom-stack.yml")
if err != nil {
logErrAndExit(err)
}
err = pt.Execute(promStackOut, promTemplate)
if err != nil {
logErrAndExit(err)
}
}
err = t.Execute(out, pollerTemplate)
if err != nil {
logErrAndExit(err)
}
f, err := os.Create(opts.filesdPath)
if err != nil {
logErrAndExit(err)
}
defer silentClose(f)
for _, line := range filesd {
_, _ = fmt.Fprintln(f, line)
}
_, _ = fmt.Fprintf(os.Stderr, "Wrote file_sd targets to %s\n", opts.filesdPath)
if os.Getenv("HARVEST_DOCKER") != "" {
srcFolder := "/opt/harvest"
destFolder := "/opt/temp"
err = copyFiles(srcFolder, destFolder)
if err != nil {
logErrAndExit(err)
}
}
if kind == harvest {
_, _ = fmt.Fprintf(os.Stderr,
"Start containers with:\n"+
color.Colorize("docker-compose -f "+opts.outputPath+" up -d --remove-orphans\n", color.Green))
}
if kind == full {
_, _ = fmt.Fprintf(os.Stderr,
"Start containers with:\n"+
color.Colorize("docker-compose -f prom-stack.yml -f "+opts.outputPath+" up -d --remove-orphans\n", color.Green))
}
}
// setup mount(s) for the confpath and any CLI-passed mounts
func makeMounts(pollerName string) []string {
var mounts = opts.mounts
p, err := conf.PollerNamed(pollerName)
if err != nil {
logErrAndExit(err)
}
confPath := opts.confPath
if confPath == "conf" {
confPath = p.ConfPath
}
if confPath == "" {
mounts = append(mounts, toMount("./conf"))
} else {
paths := strings.Split(confPath, ":")
for _, path := range paths {
mounts = append(mounts, toMount(path))
}
}
return mounts
}
func toMount(hostPath string) string {
hostPath = asComposePath(hostPath)
if strings.HasPrefix(hostPath, "./") {
return hostPath + ":" + "/opt/harvest/" + hostPath[2:]
}
return hostPath + ":" + hostPath
}
func copyFiles(srcPath, destPath string) error {
filesToExclude := map[string]bool{
"harvest.yml": true,
"harvest.yml.example": true,
"prom-stack.tmpl": true,
}
dirsToExclude := map[string]bool{
"bin": true,
"autosupport": true,
"onePollerPerContainer": true,
}
// requires specific permissions
dirsPermissions := map[string]os.FileMode{
"container": 0755,
"grafana": 0755,
}
// requires specific permissions
filePermissionsInDir := map[string]os.FileMode{
"container": 0644,
"prometheus": 0644,
"grafana": 0644,
}
return filepath.Walk(srcPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Generate the destination path
relPath, err := filepath.Rel(srcPath, path)
if err != nil {
return err
}
dest := filepath.Join(destPath, relPath)
if info.IsDir() {
// Skip excluded directories
if dirsToExclude[info.Name()] {
return filepath.SkipDir
}
// Check if the current directory or any of its parent directories are in dirsPermissions
dirCreated := false
for dir, perm := range dirsPermissions {
if strings.HasPrefix(relPath, dir) {
err = os.MkdirAll(dest, perm)
if err != nil {
return err
}
dirCreated = true
break
}
}
if !dirCreated {
err = os.MkdirAll(dest, 0750)
if err != nil {
return err
}
}
err = changeOwner(dest)
if err != nil {
return err
}
return nil
}
// Skip excluded files
if filesToExclude[info.Name()] {
return nil
}
// Check if the file is under a directory in the filePermissions map
for dir, perm := range filePermissionsInDir {
if strings.HasPrefix(relPath, dir) {
return copyFile(path, dest, perm)
}
}
return copyFile(path, dest, 0600)
})
}
func copyFile(srcPath, destPath string, perm os.FileMode) error {
srcFile, err := os.Open(srcPath)
if err != nil {
return err
}
defer silentClose(srcFile)
destFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer silentClose(destFile)
_, err = io.Copy(destFile, srcFile)
if err != nil {
return err
}
err = changeOwner(destPath)
if err != nil {
return err
}
return nil
}
func changeOwner(path string) error {
// Get the UID and GID from the environment variables
uidStr := os.Getenv("UID")
gidStr := os.Getenv("GID")
// If the UID and GID are set, change the owner and group of the file
if uidStr != "" && gidStr != "" {
uid, err := strconv.Atoi(uidStr)
if err != nil {
return err
}
gid, err := strconv.Atoi(gidStr)
if err != nil {
return err
}
err = os.Chown(path, uid, gid)
if err != nil {
return err
}
}
return nil
}
func asComposePath(path string) string {
if strings.HasPrefix(path, "/") || strings.HasPrefix(path, "./") {
return path
}
return "./" + path
}
func logErrAndExit(err error) {
fmt.Printf("%v\n", err)
os.Exit(1)
}
func silentClose(body io.ReadCloser) {
_ = body.Close()
}
func generateSystemd() {
var adminService string
_, err := conf.LoadHarvestConfig(opts.configPath)
if err != nil {
logErrAndExit(err)
}
if conf.Config.Pollers == nil {
return
}
t, err := template.New("target.tmpl").ParseFiles("service/contrib/target.tmpl")
if err != nil {
logErrAndExit(err)
}
color.DetectConsole("")
println("Save the following to " + color.Colorize("/etc/systemd/system/harvest.target", color.Green) +
" or " + color.Colorize("| sudo tee /etc/systemd/system/harvest.target", color.Green))
if conf.Config.Admin.Httpsd.Listen != "" {
adminService = harvestAdminService + " "
println("and " + color.Colorize("cp "+harvestAdminService+" /etc/systemd/system/", color.Green))
}
println("and then run " + color.Colorize("systemctl daemon-reload", color.Green))
writeAdminSystemd(opts.configPath)
// reorder list of pollers so that unix collectors are last, see https://github.com/NetApp/harvest/issues/643
pollers := make([]string, 0)
unixPollers := make([]string, 0)
pollers = append(pollers, conf.Config.PollersOrdered...)
// iterate over the pollers backwards, so we don't skip any when removing
for i := len(pollers) - 1; i >= 0; i-- {
pollerName := pollers[i]
poller, ok := conf.Config.Pollers[pollerName]
if !ok || poller == nil {
continue
}
// if unix is in the poller's list of collectors, remove it from the list of pollers
for _, c := range poller.Collectors {
if c.Name == "Unix" {
pollers = append(pollers[:i], pollers[i+1:]...)
unixPollers = append(unixPollers, pollerName)
break
}
}
}
pollers = append(pollers, unixPollers...)
err = t.Execute(os.Stdout, struct {
Admin string
PollersOrdered []string
}{
Admin: adminService,
PollersOrdered: pollers,
})
if err != nil {
logErrAndExit(err)
}
}
func writeAdminSystemd(configFp string) {
if conf.Config.Admin.Httpsd.Listen == "" {
return
}
t, err := template.New("httpsd.tmpl").ParseFiles("service/contrib/httpsd.tmpl")
if err != nil {
logErrAndExit(err)
}
f, err := os.Create(harvestAdminService)
if err != nil {
logErrAndExit(err)
}
defer silentClose(f)
configAbsPath, err := filepath.Abs(configFp)
if err != nil {
configAbsPath = "/opt/harvest/harvest.yml"
}
_ = t.Execute(f, configAbsPath)
println(color.Colorize("✓", color.Green) + " HTTP SD file: " + harvestAdminService + " created")
}
func generateMetrics() (map[string]Counter, rest.Cluster) {
var (
poller *conf.Poller
err error
restClient *rest.Client
zapiClient *zapi.Client
)
_, err = conf.LoadHarvestConfig(opts.configPath)
if err != nil {
logErrAndExit(err)
}
if poller, _, err = rest.GetPollerAndAddr(opts.Poller); err != nil {
logErrAndExit(err)
}
timeout, _ := time.ParseDuration(rest.DefaultTimeout)
credentials := auth.NewCredentials(poller, logging.Get())
if restClient, err = rest.New(poller, timeout, credentials); err != nil {
fmt.Printf("error creating new client %+v\n", err)
os.Exit(1)
}
if err = restClient.Init(2); err != nil {
fmt.Printf("error init rest client %+v\n", err)
os.Exit(1)
}
if zapiClient, err = zapi.New(poller, credentials); err != nil {
fmt.Printf("error creating new client %+v\n", err)
os.Exit(1)
}
swaggerBytes = readSwaggerJSON()
restCounters := processRestCounters(restClient)
zapiCounters := processZapiCounters(zapiClient)
counters := mergeCounters(restCounters, zapiCounters)
counters = processExternalCounters(counters)
return counters, restClient.Cluster()
}
func generateDescription(dPath string, data []byte, counters map[string]Counter) {
var err error
dashPath := grafana.ShortPath(dPath)
panelDescriptionMap := make(map[string]string)
ignoreDashboards := []string{
"cmode/health.json", "cmode/headroom.json",
}
if slices.Contains(ignoreDashboards, dashPath) {
return
}
grafana.VisitAllPanels(data, func(path string, _, value gjson.Result) {
kind := value.Get("type").String()
if kind == "row" || kind == "text" {
return
}
description := value.Get("description").String()
targetsSlice := value.Get("targets").Array()
if description == "" {
if len(targetsSlice) == 1 {
expr := targetsSlice[0].Get("expr").String()
if !(strings.Contains(expr, "/") || strings.Contains(expr, "+") || strings.Contains(expr, "-") || strings.Contains(expr, "on")) {
allMatches := metricRe.FindAllStringSubmatch(expr, -1)
for _, match := range allMatches {
m := match[1]
if m == "" {
continue
}
expr = m
}
panelPath, updatedDescription := generatePanelPathWithDescription(path, counters[expr].Description)
panelDescriptionMap[panelPath] = updatedDescription
}
}
} else if !strings.HasPrefix(description, "$") && !strings.HasSuffix(description, ".") {
// Few panels have description text from variable, which would be ignored.
panelPath, updatedDescription := generatePanelPathWithDescription(path, description)
panelDescriptionMap[panelPath] = updatedDescription
}
})
// Update the dashboard with description
for path, value := range panelDescriptionMap {
data, err = sjson.SetBytes(data, path, value)
if err != nil {
log.Fatalf("error while updating the panel in dashboard %s err: %+v", dPath, err)
}
}
// Sorted json
result := gjson.GetBytes(data, `@pretty:{"sortKeys":true, "indent":" ", "width":0}`)
if err = os.WriteFile(dPath, []byte(result.Raw), grafana.GPerm); err != nil {
log.Fatalf("failed to write dashboard=%s err=%v\n", dPath, err)
}
}
func generatePanelPathWithDescription(path string, desc string) (string, string) {
if desc != "" && !strings.HasSuffix(desc, ".") {
desc += "."
}
return strings.ReplaceAll(strings.ReplaceAll(path, "[", "."), "]", ".") + "description", desc
}
func init() {
Cmd.AddCommand(systemdCmd)
Cmd.AddCommand(metricCmd)
Cmd.AddCommand(descCmd)
Cmd.AddCommand(dockerCmd)
dockerCmd.AddCommand(fullCmd)
dFlags := dockerCmd.PersistentFlags()
fFlags := fullCmd.PersistentFlags()
flags := metricCmd.PersistentFlags()
flags.StringVarP(&opts.Poller, "poller", "p", "sar", "name of poller, e.g. 10.193.48.154")
_ = metricCmd.MarkPersistentFlagRequired("poller")
flag := descCmd.PersistentFlags()
flag.StringVarP(&opts.Poller, "poller", "p", "sar", "name of poller, e.g. 10.193.48.154")
_ = descCmd.MarkPersistentFlagRequired("poller")
dFlags.IntVarP(&opts.loglevel, "loglevel", "l", 2,
"logging level (0=trace, 1=debug, 2=info, 3=warning, 4=error, 5=critical)",
)
dFlags.StringVar(&opts.image, "image", "ghcr.io/netapp/harvest:latest", "Harvest image. Use rahulguptajss/harvest:latest to pull from Docker Hub")
dFlags.StringVar(&opts.certDir, "certdir", "./cert", "Harvest certificate dir path")
dFlags.StringVarP(&opts.outputPath, "output", "o", "", "Output file path. ")
dFlags.BoolVarP(&opts.showPorts, "port", "p", true, "Expose poller ports to host machine")
_ = dockerCmd.MarkPersistentFlagRequired("output")
dFlags.StringSliceVar(&opts.mounts, "volume", []string{}, "Additional volume mounts to include in compose file")
fFlags.StringVar(&opts.filesdPath, "filesdpath", "container/prometheus/harvest_targets.yml",
"Prometheus file_sd target path. Written when the --output is set")
fFlags.IntVar(&opts.promPort, "promPort", 9090, "Prometheus Port")
fFlags.IntVar(&opts.grafanaPort, "grafanaPort", 3000, "Grafana Port")
}