| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package internal // import "go.opentelemetry.io/collector/cmd/mdatagen/internal" |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"go/format" |
| 11 |
"io/fs" |
| 12 |
"os" |
| 13 |
"path/filepath" |
| 14 |
"regexp" |
| 15 |
"runtime/debug" |
| 16 |
"slices" |
| 17 |
"sort" |
| 18 |
"strings" |
| 19 |
"text/template" |
| 20 |
|
| 21 |
"github.com/spf13/cobra" |
| 22 |
"golang.org/x/text/cases" |
| 23 |
"golang.org/x/text/language" |
| 24 |
"gopkg.in/yaml.v3" |
| 25 |
) |
| 26 |
|
| 27 |
const ( |
| 28 |
statusStart = "<!-- status autogenerated section -->" |
| 29 |
statusEnd = "<!-- end autogenerated section -->" |
| 30 |
) |
| 31 |
|
| 32 |
var nonComponents = []string{ |
| 33 |
"cmd", |
| 34 |
"converter", |
| 35 |
"pkg", |
| 36 |
"provider", |
| 37 |
} |
| 38 |
|
| 39 |
func getVersion() (string, error) { |
| 40 |
// the second returned value is a boolean, which is true if the binaries are built with module support. |
| 41 |
info, ok := debug.ReadBuildInfo() |
| 42 |
if !ok { |
| 43 |
return "", errors.New("could not read build info") |
| 44 |
} |
| 45 |
return info.Main.Version, nil |
| 46 |
} |
| 47 |
|
| 48 |
// NewCommand constructs a new cobra.Command using the given Settings. |
| 49 |
// Any URIs specified in CollectorSettings.ConfigProviderSettings.ResolverSettings.URIs |
| 50 |
// are considered defaults and will be overwritten by config flags passed as |
| 51 |
// command-line arguments to the executable. |
| 52 |
// At least one Provider must be set. |
| 53 |
func NewCommand() (*cobra.Command, error) { |
| 54 |
ver, err := getVersion() |
| 55 |
if err != nil { |
| 56 |
return nil, err |
| 57 |
} |
| 58 |
rootCmd := &cobra.Command{ |
| 59 |
Use: "mdatagen", |
| 60 |
Version: ver, |
| 61 |
SilenceUsage: true, |
| 62 |
RunE: func(_ *cobra.Command, args []string) error { |
| 63 |
return run(args[0]) |
| 64 |
}, |
| 65 |
} |
| 66 |
return rootCmd, nil |
| 67 |
} |
| 68 |
|
| 69 |
func run(ymlPath string) error { |
| 70 |
if ymlPath == "" { |
| 71 |
return errors.New("argument must be metadata.yaml file") |
| 72 |
} |
| 73 |
ymlPath, err := filepath.Abs(ymlPath) |
| 74 |
if err != nil { |
| 75 |
return fmt.Errorf("failed to get absolute path for %v: %w", ymlPath, err) |
| 76 |
} |
| 77 |
|
| 78 |
ymlDir := filepath.Dir(ymlPath) |
| 79 |
packageName := filepath.Base(ymlDir) |
| 80 |
|
| 81 |
raw, readErr := os.ReadFile(ymlPath) //nolint:gosec // G304: abs path is cleaned/validated above; safe to read |
| 82 |
if readErr != nil { |
| 83 |
return fmt.Errorf("failed reading %v: %w", ymlPath, readErr) |
| 84 |
} |
| 85 |
|
| 86 |
if err = validateYAMLKeyOrder(raw); err != nil { |
| 87 |
return fmt.Errorf("metadata.yaml ordering check failed: %w", err) |
| 88 |
} |
| 89 |
|
| 90 |
md, err := LoadMetadata(ymlPath) |
| 91 |
if err != nil { |
| 92 |
return fmt.Errorf("failed loading %v: %w", ymlPath, err) |
| 93 |
} |
| 94 |
|
| 95 |
tmplDir := "templates" |
| 96 |
|
| 97 |
codeDir := filepath.Join(ymlDir, "internal", md.GeneratedPackageName) |
| 98 |
toGenerate := map[string]string{} |
| 99 |
if md.Status != nil { |
| 100 |
if !slices.Contains(nonComponents, md.Status.Class) { |
| 101 |
toGenerate[filepath.Join(tmplDir, "status.go.tmpl")] = filepath.Join(codeDir, "generated_status.go") |
| 102 |
err = generateFile(filepath.Join(tmplDir, "component_test.go.tmpl"), |
| 103 |
filepath.Join(ymlDir, "generated_component_test.go"), md, packageName) |
| 104 |
if err != nil { |
| 105 |
return err |
| 106 |
} |
| 107 |
} else { |
| 108 |
if _, err = os.Stat(filepath.Join(codeDir, "generated_status.go")); err == nil { |
| 109 |
err = os.Remove(filepath.Join(codeDir, "generated_status.go")) |
| 110 |
if err != nil { |
| 111 |
return err |
| 112 |
} |
| 113 |
} |
| 114 |
if _, err = os.Stat(filepath.Join(ymlDir, "generated_component_test.go")); err == nil { |
| 115 |
err = os.Remove(filepath.Join(ymlDir, "generated_component_test.go")) |
| 116 |
if err != nil { |
| 117 |
return err |
| 118 |
} |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
err = generateFile(filepath.Join(tmplDir, "package_test.go.tmpl"), |
| 123 |
filepath.Join(ymlDir, "generated_package_test.go"), md, packageName) |
| 124 |
if err != nil { |
| 125 |
return err |
| 126 |
} |
| 127 |
|
| 128 |
if _, err = os.Stat(filepath.Join(ymlDir, "README.md")); err == nil { |
| 129 |
err = inlineReplace( |
| 130 |
filepath.Join(tmplDir, "readme.md.tmpl"), |
| 131 |
filepath.Join(ymlDir, "README.md"), |
| 132 |
md, statusStart, statusEnd, md.GeneratedPackageName) |
| 133 |
if err != nil { |
| 134 |
return err |
| 135 |
} |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
if len(md.Telemetry.Metrics) != 0 { // if there are telemetry metrics, generate telemetry specific files |
| 140 |
testDir := filepath.Join(ymlDir, "internal", md.GeneratedPackageName+"test") |
| 141 |
if err = os.MkdirAll(testDir, 0o700); err != nil { |
| 142 |
return fmt.Errorf("unable to create output test directory %q: %w", codeDir, err) |
| 143 |
} |
| 144 |
toGenerate[filepath.Join(tmplDir, "telemetry.go.tmpl")] = filepath.Join(codeDir, "generated_telemetry.go") |
| 145 |
toGenerate[filepath.Join(tmplDir, "telemetry_test.go.tmpl")] = filepath.Join(codeDir, "generated_telemetry_test.go") |
| 146 |
toGenerate[filepath.Join(tmplDir, "telemetrytest.go.tmpl")] = filepath.Join(testDir, "generated_telemetrytest.go") |
| 147 |
toGenerate[filepath.Join(tmplDir, "telemetrytest_test.go.tmpl")] = filepath.Join(testDir, "generated_telemetrytest_test.go") |
| 148 |
} else { |
| 149 |
if _, err = os.Stat(filepath.Join(ymlDir, "generated_telemetry.go")); err == nil { |
| 150 |
err = os.Remove(filepath.Join(ymlDir, "generated_telemetry.go")) |
| 151 |
if err != nil { |
| 152 |
return err |
| 153 |
} |
| 154 |
} |
| 155 |
if _, err = os.Stat(filepath.Join(ymlDir, "generated_telemetry_test.go")); err == nil { |
| 156 |
err = os.Remove(filepath.Join(ymlDir, "generated_telemetry_test.go")) |
| 157 |
if err != nil { |
| 158 |
return err |
| 159 |
} |
| 160 |
} |
| 161 |
if _, err = os.Stat(filepath.Join(ymlDir, "generated_telemetrytest.go")); err == nil { |
| 162 |
err = os.Remove(filepath.Join(ymlDir, "generated_telemetrytest.go")) |
| 163 |
if err != nil { |
| 164 |
return err |
| 165 |
} |
| 166 |
} |
| 167 |
if _, err = os.Stat(filepath.Join(ymlDir, "generated_telemetrytest_test.go")); err == nil { |
| 168 |
err = os.Remove(filepath.Join(ymlDir, "generated_telemetrytest_test.go")) |
| 169 |
if err != nil { |
| 170 |
return err |
| 171 |
} |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
if len(md.Metrics) != 0 || len(md.Telemetry.Metrics) != 0 || len(md.ResourceAttributes) != 0 || len(md.Events) != 0 { // if there's metrics or internal metrics or events, generate documentation for them |
| 176 |
toGenerate[filepath.Join(tmplDir, "documentation.md.tmpl")] = filepath.Join(ymlDir, "documentation.md") |
| 177 |
} |
| 178 |
|
| 179 |
if len(md.Metrics) > 0 || len(md.Events) > 0 || len(md.ResourceAttributes) > 0 { |
| 180 |
testdataDir := filepath.Join(codeDir, "testdata") |
| 181 |
if err = os.MkdirAll(filepath.Join(codeDir, "testdata"), 0o700); err != nil { |
| 182 |
return fmt.Errorf("unable to create output directory %q: %w", testdataDir, err) |
| 183 |
} |
| 184 |
|
| 185 |
toGenerate[filepath.Join(tmplDir, "testdata", "config.yaml.tmpl")] = filepath.Join(testdataDir, "config.yaml") |
| 186 |
toGenerate[filepath.Join(tmplDir, "config.go.tmpl")] = filepath.Join(codeDir, "generated_config.go") |
| 187 |
toGenerate[filepath.Join(tmplDir, "config_test.go.tmpl")] = filepath.Join(codeDir, "generated_config_test.go") |
| 188 |
} |
| 189 |
|
| 190 |
if len(md.ResourceAttributes) > 0 { // only generate resource files if resource attributes are configured |
| 191 |
toGenerate[filepath.Join(tmplDir, "resource.go.tmpl")] = filepath.Join(codeDir, "generated_resource.go") |
| 192 |
toGenerate[filepath.Join(tmplDir, "resource_test.go.tmpl")] = filepath.Join(codeDir, "generated_resource_test.go") |
| 193 |
} |
| 194 |
|
| 195 |
if len(md.Metrics) > 0 { // only generate metrics if metrics are present |
| 196 |
toGenerate[filepath.Join(tmplDir, "metrics.go.tmpl")] = filepath.Join(codeDir, "generated_metrics.go") |
| 197 |
toGenerate[filepath.Join(tmplDir, "metrics_test.go.tmpl")] = filepath.Join(codeDir, "generated_metrics_test.go") |
| 198 |
} |
| 199 |
|
| 200 |
if md.supportsSignal("logs") && |
| 201 |
(md.Status.Class == "receiver" || md.Status.Class == "scraper") { |
| 202 |
toGenerate[filepath.Join(tmplDir, "logs.go.tmpl")] = filepath.Join(codeDir, "generated_logs.go") |
| 203 |
toGenerate[filepath.Join(tmplDir, "logs_test.go.tmpl")] = filepath.Join(codeDir, "generated_logs_test.go") |
| 204 |
} |
| 205 |
|
| 206 |
// If at least one file to generate, will need the codeDir |
| 207 |
if len(toGenerate) > 0 { |
| 208 |
if err = os.MkdirAll(codeDir, 0o700); err != nil { |
| 209 |
return fmt.Errorf("unable to create output directory %q: %w", codeDir, err) |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
for tmpl, dst := range toGenerate { |
| 214 |
if err := generateFile(tmpl, dst, md, md.GeneratedPackageName); err != nil { |
| 215 |
return err |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
return nil |
| 220 |
} |
| 221 |
|
| 222 |
func templatize(tmplFile string, md Metadata) *template.Template { |
| 223 |
return template.Must( |
| 224 |
template. |
| 225 |
New(filepath.Base(tmplFile)). |
| 226 |
Option("missingkey=error"). |
| 227 |
Funcs(map[string]any{ |
| 228 |
"publicVar": func(s string) (string, error) { |
| 229 |
return FormatIdentifier(s, true) |
| 230 |
}, |
| 231 |
"attributeInfo": func(an AttributeName) Attribute { |
| 232 |
return md.Attributes[an] |
| 233 |
}, |
| 234 |
"getEventConditionalAttributes": func(attrs map[AttributeName]Attribute) []AttributeName { |
| 235 |
seen := make(map[AttributeName]bool) |
| 236 |
used := make([]AttributeName, 0) |
| 237 |
|
| 238 |
for _, event := range md.Events { |
| 239 |
for _, attribute := range event.Attributes { |
| 240 |
v, exists := attrs[attribute] |
| 241 |
if exists && v.IsConditional() && !seen[attribute] { |
| 242 |
used = append(used, attribute) |
| 243 |
seen[attribute] = true |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
sort.Slice(used, func(i, j int) bool { return string(used[i]) < string(used[j]) }) |
| 248 |
|
| 249 |
return used |
| 250 |
}, |
| 251 |
"getMetricConditionalAttributes": func(attrs map[AttributeName]Attribute) []AttributeName { |
| 252 |
seen := make(map[AttributeName]bool) |
| 253 |
used := make([]AttributeName, 0) |
| 254 |
|
| 255 |
for _, event := range md.Metrics { |
| 256 |
for _, attribute := range event.Attributes { |
| 257 |
v, exists := attrs[attribute] |
| 258 |
if exists && v.IsConditional() && !seen[attribute] { |
| 259 |
used = append(used, attribute) |
| 260 |
seen[attribute] = true |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
sort.Slice(used, func(i, j int) bool { return string(used[i]) < string(used[j]) }) |
| 265 |
|
| 266 |
return used |
| 267 |
}, |
| 268 |
"metricInfo": func(mn MetricName) Metric { |
| 269 |
return md.Metrics[mn] |
| 270 |
}, |
| 271 |
"eventInfo": func(en EventName) Event { |
| 272 |
return md.Events[en] |
| 273 |
}, |
| 274 |
"telemetryInfo": func(mn MetricName) Metric { |
| 275 |
return md.Telemetry.Metrics[mn] |
| 276 |
}, |
| 277 |
"parseImportsRequired": func(metrics map[MetricName]Metric) bool { |
| 278 |
for _, m := range metrics { |
| 279 |
if m.Data().HasMetricInputType() { |
| 280 |
return true |
| 281 |
} |
| 282 |
} |
| 283 |
return false |
| 284 |
}, |
| 285 |
"stringsJoin": strings.Join, |
| 286 |
"stringsSplit": strings.Split, |
| 287 |
"userLinks": func(elems []string) []string { |
| 288 |
result := make([]string, len(elems)) |
| 289 |
for i, elem := range elems { |
| 290 |
if elem == "open-telemetry/collector-approvers" { |
| 291 |
result[i] = "[@open-telemetry/collector-approvers](https://github.com/orgs/open-telemetry/teams/collector-approvers)" |
| 292 |
} else { |
| 293 |
result[i] = fmt.Sprintf("[@%s](https://www.github.com/%s)", elem, elem) |
| 294 |
} |
| 295 |
} |
| 296 |
return result |
| 297 |
}, |
| 298 |
"casesTitle": cases.Title(language.English).String, |
| 299 |
"toLowerCase": strings.ToLower, |
| 300 |
"toCamelCase": func(s string) string { |
| 301 |
caser := cases.Title(language.English).String |
| 302 |
parts := strings.Split(s, "_") |
| 303 |
var result strings.Builder |
| 304 |
for _, part := range parts { |
| 305 |
fmt.Fprintf(&result, "%s", caser(part)) |
| 306 |
} |
| 307 |
return result.String() |
| 308 |
}, |
| 309 |
"inc": func(i int) int { return i + 1 }, |
| 310 |
"distroURL": distroURL, |
| 311 |
"isExporter": func() bool { |
| 312 |
return md.Status.Class == "exporter" |
| 313 |
}, |
| 314 |
"isProcessor": func() bool { |
| 315 |
return md.Status.Class == "processor" |
| 316 |
}, |
| 317 |
"isReceiver": func() bool { |
| 318 |
return md.Status.Class == "receiver" |
| 319 |
}, |
| 320 |
"isExtension": func() bool { |
| 321 |
return md.Status.Class == "extension" |
| 322 |
}, |
| 323 |
"isConnector": func() bool { |
| 324 |
return md.Status.Class == "connector" |
| 325 |
}, |
| 326 |
"isScraper": func() bool { |
| 327 |
return md.Status.Class == "scraper" |
| 328 |
}, |
| 329 |
"isCommand": func() bool { |
| 330 |
return md.Status.Class == "cmd" |
| 331 |
}, |
| 332 |
"supportsLogs": func() bool { return md.supportsSignal("logs") }, |
| 333 |
"supportsMetrics": func() bool { return md.supportsSignal("metrics") }, |
| 334 |
"supportsTraces": func() bool { return md.supportsSignal("traces") }, |
| 335 |
"supportsLogsToLogs": func() bool { return md.supportsSignal("logs_to_logs") }, |
| 336 |
"supportsLogsToMetrics": func() bool { return md.supportsSignal("logs_to_metrics") }, |
| 337 |
"supportsLogsToTraces": func() bool { return md.supportsSignal("logs_to_traces") }, |
| 338 |
"supportsMetricsToLogs": func() bool { return md.supportsSignal("metrics_to_logs") }, |
| 339 |
"supportsMetricsToMetrics": func() bool { return md.supportsSignal("metrics_to_metrics") }, |
| 340 |
"supportsMetricsToTraces": func() bool { return md.supportsSignal("metrics_to_traces") }, |
| 341 |
"supportsTracesToLogs": func() bool { return md.supportsSignal("traces_to_logs") }, |
| 342 |
"supportsTracesToMetrics": func() bool { return md.supportsSignal("traces_to_metrics") }, |
| 343 |
"supportsTracesToTraces": func() bool { return md.supportsSignal("traces_to_traces") }, |
| 344 |
"expectConsumerError": func() bool { |
| 345 |
return md.Tests.ExpectConsumerError |
| 346 |
}, |
| 347 |
// ParseFS delegates the parsing of the files to `Glob` |
| 348 |
// which uses the `\` as a special character. |
| 349 |
// Meaning on windows based machines, the `\` needs to be replaced |
| 350 |
// with a `/` for it to find the file. |
| 351 |
}).ParseFS(TemplateFS, "templates/helper.tmpl", strings.ReplaceAll(tmplFile, "\\", "/"))) |
| 352 |
} |
| 353 |
|
| 354 |
func executeTemplate(tmplFile string, md Metadata, goPackage string) ([]byte, error) { |
| 355 |
tmpl := templatize(tmplFile, md) |
| 356 |
buf := bytes.Buffer{} |
| 357 |
|
| 358 |
if err := tmpl.Execute(&buf, TemplateContext{Metadata: md, Package: goPackage}); err != nil { |
| 359 |
return []byte{}, fmt.Errorf("failed executing template: %w", err) |
| 360 |
} |
| 361 |
return buf.Bytes(), nil |
| 362 |
} |
| 363 |
|
| 364 |
func inlineReplace(tmplFile, outputFile string, md Metadata, start, end, goPackage string) error { |
| 365 |
var readmeContents []byte |
| 366 |
var err error |
| 367 |
if readmeContents, err = os.ReadFile(outputFile); err != nil { //nolint:gosec |
| 368 |
return err |
| 369 |
} |
| 370 |
|
| 371 |
re := regexp.MustCompile(fmt.Sprintf("%s[\\s\\S]*%s", start, end)) |
| 372 |
if !re.Match(readmeContents) { |
| 373 |
return nil |
| 374 |
} |
| 375 |
|
| 376 |
if md.GithubProject == "" { |
| 377 |
md.GithubProject = "open-telemetry/opentelemetry-collector-contrib" |
| 378 |
} |
| 379 |
|
| 380 |
buf, err := executeTemplate(tmplFile, md, goPackage) |
| 381 |
if err != nil { |
| 382 |
return err |
| 383 |
} |
| 384 |
|
| 385 |
s := re.ReplaceAllString(string(readmeContents), string(buf)) |
| 386 |
if err := os.WriteFile(outputFile, []byte(s), 0o600); err != nil { |
| 387 |
return fmt.Errorf("failed writing %q: %w", outputFile, err) |
| 388 |
} |
| 389 |
|
| 390 |
return nil |
| 391 |
} |
| 392 |
|
| 393 |
func generateFile(tmplFile, outputFile string, md Metadata, goPackage string) error { |
| 394 |
if err := os.Remove(outputFile); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 395 |
return fmt.Errorf("unable to remove generated file %q: %w", outputFile, err) |
| 396 |
} |
| 397 |
|
| 398 |
result, err := executeTemplate(tmplFile, md, goPackage) |
| 399 |
if err != nil { |
| 400 |
return err |
| 401 |
} |
| 402 |
var formatErr error |
| 403 |
if strings.HasSuffix(outputFile, ".go") { |
| 404 |
if formatted, err := format.Source(result); err == nil { |
| 405 |
result = formatted |
| 406 |
} else { |
| 407 |
formatErr = fmt.Errorf("failed formatting %s:%w", outputFile, err) |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
if err := os.WriteFile(outputFile, result, 0o600); err != nil { |
| 412 |
return fmt.Errorf("failed writing %q: %w", outputFile, err) |
| 413 |
} |
| 414 |
|
| 415 |
return formatErr |
| 416 |
} |
| 417 |
|
| 418 |
func validateMappingKeysSorted(root *yaml.Node, path ...string) error { |
| 419 |
// unwrap doc |
| 420 |
n := root |
| 421 |
if n.Kind == yaml.DocumentNode && len(n.Content) > 0 { |
| 422 |
n = n.Content[0] |
| 423 |
} |
| 424 |
// follow path |
| 425 |
for _, seg := range path { |
| 426 |
if n.Kind != yaml.MappingNode { |
| 427 |
return nil |
| 428 |
} |
| 429 |
var next *yaml.Node |
| 430 |
for i := 0; i < len(n.Content); i += 2 { |
| 431 |
if n.Content[i].Value == seg { |
| 432 |
next = n.Content[i+1] |
| 433 |
break |
| 434 |
} |
| 435 |
} |
| 436 |
if next == nil { |
| 437 |
return nil |
| 438 |
} |
| 439 |
n = next |
| 440 |
} |
| 441 |
if n.Kind != yaml.MappingNode { |
| 442 |
return nil |
| 443 |
} |
| 444 |
|
| 445 |
// collect keys |
| 446 |
keys := make([]string, 0, len(n.Content)/2) |
| 447 |
for i := 0; i < len(n.Content); i += 2 { |
| 448 |
keys = append(keys, n.Content[i].Value) |
| 449 |
} |
| 450 |
|
| 451 |
if !slices.IsSorted(keys) { |
| 452 |
return fmt.Errorf("%v keys are not sorted: %v", path, keys) |
| 453 |
} |
| 454 |
return nil |
| 455 |
} |
| 456 |
|
| 457 |
// ValidateYAMLKeyOrder checks the sections we care about. |
| 458 |
func validateYAMLKeyOrder(raw []byte) error { |
| 459 |
var doc yaml.Node |
| 460 |
if err := yaml.Unmarshal(raw, &doc); err != nil { |
| 461 |
return err |
| 462 |
} |
| 463 |
for _, p := range [][]string{ |
| 464 |
{"resource_attributes"}, |
| 465 |
{"entities"}, |
| 466 |
{"attributes"}, |
| 467 |
{"metrics"}, |
| 468 |
{"events"}, |
| 469 |
{"telemetry", "metrics"}, |
| 470 |
} { |
| 471 |
if err := validateMappingKeysSorted(&doc, p...); err != nil { |
| 472 |
return err |
| 473 |
} |
| 474 |
} |
| 475 |
return nil |
| 476 |
} |