-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
270 lines (252 loc) · 8.17 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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2023-present Datadog, Inc.
package main
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime/pprof"
"runtime/trace"
"slices"
"strconv"
"strings"
"github.com/DataDog/orchestrion/internal/cmd"
"github.com/DataDog/orchestrion/internal/jobserver/client"
"github.com/DataDog/orchestrion/internal/log"
"github.com/DataDog/orchestrion/internal/version"
"github.com/urfave/cli/v2"
)
const (
envVarOrchestrionLogFile = "ORCHESTRION_LOG_FILE"
envVarOrchestrionLogLevel = "ORCHESTRION_LOG_LEVEL"
envVarOrchestrionProfilePath = "ORCHESTRION_PROFILE_PATH"
envVarOrchestrionEnabledProfiles = "ORCHESTRION_ENABLED_PROFILES"
envVarToolexecImportPath = "TOOLEXEC_IMPORTPATH"
)
func main() {
// Setup the logger
log.SetContext("ORCHESTRION", version.Tag)
log.SetContext("PID", strconv.FormatInt(int64(os.Getpid()), 10))
if val := os.Getenv(envVarToolexecImportPath); val != "" {
log.SetContext(envVarToolexecImportPath, val)
}
defer log.Close()
var (
cpuProfile *os.File
executionTrace *os.File
)
// Setup the CLI application
app := cli.App{
Name: "orchestrion",
Usage: "Automatic compile-time instrumentation of Go code",
Description: "Orchestrion automatically adds instrumentation to Go applications at compile-time by interfacing with the standard Go toolchain using the -toolexec mechanism to re-write source code before it is passed to the compiler.\n\nFor more information, visit https://datadoghq.dev/orchestrion",
Copyright: "2023-present Datadog, Inc.",
HideVersion: true,
Flags: []cli.Flag{
&cli.StringFlag{
Category: "Advanced",
Name: "C",
Usage: "Change to the specified directory before proceeding with the rest of the command.",
Hidden: true, // Users don't normally need to use this.
Action: func(_ *cli.Context, dir string) error {
return os.Chdir(dir)
},
},
&cli.StringFlag{
Category: "Advanced",
Name: "job-server-url",
EnvVars: []string{client.EnvVarJobserverURL},
Usage: "Set the job server URL",
Hidden: true, // Users don't normally need to use this.
Action: func(_ *cli.Context, url string) error {
// Forward the value to the environment variable, so that all child processes see it.
return os.Setenv(client.EnvVarJobserverURL, url)
},
},
&cli.StringFlag{
Category: "Logging",
Name: "log-level",
EnvVars: []string{envVarOrchestrionLogLevel},
Usage: "Set the log level (NONE, OFF, ERROR, WARN, INFO, DEBUG, TRACE)",
Value: "NONE",
Action: actionSetLogLevel,
},
&cli.StringFlag{
Category: "Logging",
Name: "log-file",
EnvVars: []string{envVarOrchestrionLogFile},
Usage: "Send logging output to a file instead of STDERR. Unless --log-level is also specified, the default log level changed to WARN.",
Action: actionSetLogFile,
},
&cli.StringFlag{
Category: "Profiling",
Name: "profile-path",
EnvVars: []string{envVarOrchestrionProfilePath},
Usage: "Path for profiling data. Defaults to the current working directory",
Hidden: true,
},
&cli.StringSliceFlag{
Category: "Profiling",
Name: "profile",
EnvVars: []string{envVarOrchestrionEnabledProfiles},
Usage: "Enable the given profiler. Valid options are \"cpu\", \"heap\", and \"trace\". Can be specified multiple times.",
Hidden: true,
},
},
Commands: []*cli.Command{
cmd.Go,
cmd.Pin,
cmd.Toolexec,
cmd.Version,
cmd.Server,
},
Before: func(ctx *cli.Context) error {
profiles := ctx.StringSlice("profile")
if len(profiles) == 0 {
return nil
}
profilePath, err := filepath.Abs(ctx.String("profile-path"))
if err != nil {
return err
}
if err := os.MkdirAll(profilePath, 0775); err != nil && !errors.Is(err, fs.ErrExist) {
return err
}
if err := os.Setenv(envVarOrchestrionProfilePath, profilePath); err != nil {
return cli.Exit(fmt.Errorf("setting environment %s: %w", envVarOrchestrionProfilePath, err), 1)
}
for _, p := range profiles {
var err error
switch p {
case "heap":
// Nothing to do; this is dealt with only in After
case "cpu":
cpuProfile, err = startCPUProfiling(profilePath)
case "trace":
executionTrace, err = startExecutionTracing(profilePath)
default:
return fmt.Errorf("unrecognized profile type %s", p)
}
if err != nil {
return fmt.Errorf("enabling profile %s: %w", p, err)
}
}
if err := os.Setenv(envVarOrchestrionEnabledProfiles, strings.Join(profiles, ",")); err != nil {
return cli.Exit(fmt.Errorf("setting environment %s: %w", envVarOrchestrionEnabledProfiles, err), 1)
}
return nil
},
After: func(ctx *cli.Context) error {
// Stop profiling, execution tracing, if they were started
if cpuProfile != nil {
pprof.StopCPUProfile()
if err := cpuProfile.Close(); err != nil {
log.Warnf("Failed to close CPU profile: %v\n", err)
}
}
if executionTrace != nil {
trace.Stop()
if err := executionTrace.Close(); err != nil {
log.Warnf("Failed to close execution trace: %v\n", err)
}
}
if slices.Contains(ctx.StringSlice("profile"), "heap") {
filename := profilePath(ctx.String("profile-path"), "orchestrion-heap-%d.pprof")
f, err := profileToFile(filename, func(w io.Writer) error {
return pprof.Lookup("heap").WriteTo(w, 0)
})
if err != nil {
return fmt.Errorf("writing heap profile: %w", err)
}
if err := f.Close(); err != nil {
log.Warnf("Failed to close heap profile: %v\n", err)
}
}
return nil
},
}
// Run the CLI application
if err := app.Run(os.Args); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(-1)
}
}
var logLevelSet bool
func actionSetLogLevel(_ *cli.Context, level string) error {
if err := os.Setenv(envVarOrchestrionLogLevel, level); err != nil {
return cli.Exit(fmt.Errorf("setting environment %s: %w", envVarOrchestrionLogLevel, err), 1)
}
if level, valid := log.LevelNamed(level); valid {
logLevelSet = true
log.SetLevel(level)
return nil
}
return fmt.Errorf("invalid log level specified: %q", level)
}
func actionSetLogFile(_ *cli.Context, path string) error {
if !filepath.IsAbs(path) {
if wd, err := os.Getwd(); err == nil {
path = filepath.Join(wd, path)
}
}
if err := os.Setenv(envVarOrchestrionLogFile, path); err != nil {
return cli.Exit(fmt.Errorf("setting environment %s: %w", envVarOrchestrionLogFile, err), 1)
}
filename := os.Expand(path, func(name string) string {
switch name {
case "PID":
log.SetContext("PID", "")
return strconv.FormatInt(int64(os.Getpid()), 10)
default:
return fmt.Sprintf("$%s", name)
}
})
if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
return err
}
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return err
}
log.SetOutput(file)
if !logLevelSet {
log.SetLevel(log.LevelWarn)
}
return nil
}
func profilePath(path string, nameFormat string) string {
return filepath.Join(path, fmt.Sprintf(nameFormat, os.Getpid()))
}
func profileToFile(filename string, collect func(io.Writer) error) (*os.File, error) {
f, err := os.Create(filename)
if err != nil {
return nil, fmt.Errorf("creating file %s: %w", filename, err)
}
if err := collect(f); err != nil {
err = errors.Join(err, f.Close())
err = errors.Join(err, os.Remove(filename))
return nil, fmt.Errorf("starting collection: %w", err)
}
return f, nil
}
func startCPUProfiling(prefix string) (*os.File, error) {
filename := profilePath(prefix, "orchestrion-cpu-%d.pprof")
f, err := profileToFile(filename, pprof.StartCPUProfile)
if err != nil {
return nil, fmt.Errorf("starting CPU profiling: %w", err)
}
return f, nil
}
func startExecutionTracing(prefix string) (*os.File, error) {
filename := profilePath(prefix, "orchestrion-%d.trace")
f, err := profileToFile(filename, trace.Start)
if err != nil {
return nil, fmt.Errorf("starting execution tracing: %w", err)
}
return f, nil
}