-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
110 lines (90 loc) · 1.96 KB
/
setup.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
package main
import (
"context"
"os"
"runtime/pprof"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/xmidt-org/arrange"
"github.com/xmidt-org/sallust"
"go.uber.org/zap"
)
type Profiling struct {
CPU string
Memory string
cpuFile *os.File
}
func (p *Profiling) Start(context.Context) (err error) {
if len(p.CPU) > 0 {
p.cpuFile, err = os.Create(p.CPU)
if err != nil {
return
}
if err = pprof.StartCPUProfile(p.cpuFile); err != nil {
p.cpuFile.Close()
return
}
}
return
}
func (p *Profiling) Stop(context.Context) (err error) {
if p.cpuFile != nil {
pprof.StopCPUProfile()
p.cpuFile.Close()
p.cpuFile = nil
}
if len(p.Memory) > 0 {
var memFile *os.File
if memFile, err = os.Create(p.Memory); err != nil {
return
}
defer memFile.Close()
err = pprof.WriteHeapProfile(memFile)
}
return
}
func newViper() (*viper.Viper, error) {
var configLocations = []string{
".",
"$HOME/.labweek",
"/etc/labweek",
}
v := viper.New()
v.SetConfigName("labweek")
for _, location := range configLocations {
v.AddConfigPath(location)
}
return v, v.ReadInConfig()
}
func parseCmdLine(args []string, v *viper.Viper) (l *zap.Logger, p *Profiling, err error) {
p = new(Profiling)
fs := pflag.NewFlagSet("labweek", pflag.ExitOnError)
fs.StringVar(&p.CPU, "cpuprofile", "", "turns on cpu profiling and writes it to the given file")
fs.StringVar(&p.Memory, "memprofile", "", "turns on memory profiling and writes it to the given file")
fs.Parse(args)
if err == nil {
var c sallust.Config
if err = v.UnmarshalKey("logging", &c, arrange.DefaultDecodeHooks); err == nil {
l, err = c.Build()
}
}
if l != nil {
l.Info(
"bootstrap successful",
zap.String("configFile", v.ConfigFileUsed()),
)
if len(p.CPU) > 0 {
l.Info(
"writing CPU profile",
zap.String("file", p.CPU),
)
}
if len(p.Memory) > 0 {
l.Info(
"writing memory profile",
zap.String("file", p.Memory),
)
}
}
return
}