forked from open-telemetry/opentelemetry-collector
/
main.go
173 lines (150 loc) · 5.23 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
// Copyright 2020 OpenTelemetry 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 builder
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"text/template"
"time"
"github.com/open-telemetry/opentelemetry-collector-builder/internal/scaffold"
)
var (
// ErrFailedToGenerateSourceFromTemplate indicates a failure in writing the final contents to the destination file
ErrFailedToGenerateSourceFromTemplate = errors.New("failed to generate source from template")
// ErrGoNotFound is returned when a Go binary hasn't been found
ErrGoNotFound = errors.New("Go binary not found")
)
// GenerateAndCompile will generate the source files based on the given configuration, update go mod, and will compile into a binary
func GenerateAndCompile(cfg Config) error {
if err := Generate(cfg); err != nil {
return err
}
// run go get to update go.mod and go.sum files
if err := GetModules(cfg); err != nil {
return err
}
return Compile(cfg)
}
// Generate assembles a new distribution based on the given configuration
func Generate(cfg Config) error {
// create a warning message for non-aligned builder and collector base
if cfg.Distribution.OtelColVersion != defaultOtelColVersion {
cfg.Logger.Info("You're building a distribution with non-aligned version of the builder. Compilation may fail due to API changes. Please upgrade your builder or API", "builder-version", defaultOtelColVersion)
}
// if the file does not exist, try to create it
if _, err := os.Stat(cfg.Distribution.OutputPath); os.IsNotExist(err) {
if err := os.Mkdir(cfg.Distribution.OutputPath, 0755); err != nil {
return fmt.Errorf("failed to create output path: %w", err)
}
} else if err != nil {
// something else happened
return fmt.Errorf("failed to create output path: %w", err)
}
for _, file := range []struct {
outFile string
tmpl string
}{
{
"main.go",
scaffold.Main,
},
// components.go
{
"components.go",
scaffold.Components,
},
{
"go.mod",
scaffold.Gomod,
},
} {
if err := processAndWrite(cfg, file.tmpl, file.outFile, cfg); err != nil {
return fmt.Errorf("failed to generate source file with destination %q, source: %q: %w", file.outFile, file.tmpl, err)
}
}
cfg.Logger.Info("Sources created", "path", cfg.Distribution.OutputPath)
return nil
}
// Compile generates a binary from the sources based on the configuration
func Compile(cfg Config) error {
if cfg.SkipCompilation {
cfg.Logger.Info("Generating source codes only, the distribution will not be compiled.")
return nil
}
// first, we test to check if we have Go at all
goBinary, err := getGoPath(cfg)
if err != nil {
return err
}
cfg.Logger.Info("Compiling")
cmd := exec.Command(goBinary, "build", "-ldflags=-s -w", "-trimpath", "-o", cfg.Distribution.ExeName)
cmd.Dir = cfg.Distribution.OutputPath
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to compile the OpenTelemetry Collector distribution: %w. Output: %q", err, out)
}
cfg.Logger.Info("Compiled", "binary", fmt.Sprintf("%s/%s", cfg.Distribution.OutputPath, cfg.Distribution.ExeName))
return nil
}
// GetModules retrieves the go modules, updating go.mod and go.sum in the process
func GetModules(cfg Config) error {
// first, we test to check if we have Go at all
goBinary, err := getGoPath(cfg)
if err != nil {
return err
}
cfg.Logger.Info("Getting go modules")
// basic retry if error from go mod command (in case of transient network error). This could be improved
// retry 3 times with 5 second spacing interval
retries := 3
failReason := "unknown"
for i := 1; i <= retries; i++ {
cmd := exec.Command(goBinary, "mod", "download", "all")
cmd.Dir = cfg.Distribution.OutputPath
if out, err := cmd.CombinedOutput(); err != nil {
failReason = fmt.Sprintf("%s. Output: %q", err, out)
cfg.Logger.Info("Failed modules download", "retry", fmt.Sprintf("%d/%d", i, retries))
time.Sleep(5 * time.Second)
continue
}
return nil
}
return fmt.Errorf("failed to download go modules: %s", failReason)
}
// getGoPath checks if go is present and correct, and returns a useable go bin location
func getGoPath(cfg Config) (string, error) {
goBinary := cfg.Distribution.Go
if _, err := exec.Command(goBinary, "env").CombinedOutput(); err != nil {
path, err := exec.LookPath("go")
if err != nil {
return "", ErrGoNotFound
}
goBinary = path
cfg.Logger.Info("Using go from PATH", "Go executable", path)
}
return goBinary, nil
}
func processAndWrite(cfg Config, tmpl string, outFile string, tmplParams interface{}) error {
t, err := template.New("template").Parse(tmpl)
if err != nil {
return err
}
out, err := os.Create(filepath.Join(cfg.Distribution.OutputPath, outFile))
if err != nil {
return err
}
return t.Execute(out, tmplParams)
}