Skip to content

Commit

Permalink
feat: initial merge for compgen (#220)
Browse files Browse the repository at this point in the history
* Iintial commit for compgen

* Updating compgen scraper templates

* Compgen's receiver scraper is now functional

* fix: remove extra package from scrapper template

* Update build launch.json

* Add unmarshal() to compgen's dummy receiver

* Simplify sample config data in the dummy receiver

* Correcting a whoopsie

* Fixing configKey in compgen's dummy receiver

* Renaming PostProcessing() to CompleteModule()

* update: config.go and config_test.go template

* remove: MyAwesomeReceiver2 generated code

* Updated compgen documentation

* add: test for config.go file

* More test cases for compgen receiver template

* update: template files and testdata

* Compgen makefile cleanup

* Cleanup compgen launch.json files

* fix: factory template

* Compgen documentation changes from PR feedback

* Restore build/.vscode/launch.json

* Simplified common.go in compgen

* update: add more comments to config_test.go template

* Refactored compgen

* Remove Gen() from compgen

* Added compgen test for common.Tidy()

* Add tests for common.Render() in compgen

* Add test cases for receiver.go in compgen

* Remove pkg references from compgen

* Upgrade compgen and templates to go 1.21 and otel 0.91.0

* Appeasing linter

* Whitespace fix

* Cleanup unnecessary comment in compgen

* Removing receiver.Init() from compgen. It isn't needed

* Simplify go.mod.tmpl in compgen templates

* Use temp directory for debugging compgen

* Updated comments for compgen. Changed "templates" accessibility

* First pass at complete copmgen documentation

* remove: stoof ambiguous name and changed to empty and dummy

* Refactored away the use of panic

* Copmgen template cleanup

* Add contributing instructions to compgen regarding Makefile.Common

* Moving .debug reference to top-level .gitignore file

---------

Co-authored-by: densellp <[email protected]>
  • Loading branch information
acramsay and densellp committed Dec 15, 2023
1 parent e8b980f commit acd1d4e
Show file tree
Hide file tree
Showing 33 changed files with 1,039 additions and 15 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
*.dll
*.so
*.dylib
__debug_bin*

# Temp directory for debugging compgen
.debug

# Test binary, built with `go test -c`
*.test
Expand Down
20 changes: 18 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ We love your input! We want to make contributing to this project as easy and tra

We use GitHub to host code, to track issues and feature requests, as well as accept pull requests.

## We Use [Coding Conventions, e.g., PEP8], So Pull Requests Need To Pass This.
## We Use [Coding Conventions, e.g., PEP8], So Pull Requests Need To Pass This

TODO: Include information about the coding style guide or conventions that you use. If there are any tools that they should use or any checks that their code needs to pass, detail them here.

Expand Down Expand Up @@ -50,6 +50,22 @@ Great Bug Reports tend to have:

TODO: Detail the style guide and coding conventions further, if needed.

## Running Checks

After making a code change, run the following commands and validate that each runs successfully:

```sh
make generate
make tidy-all
make lint-all
make test-all
make fmt-all
```

## Adding New Components

New compponents can be created by running compgen. See compgen's [README](./cmd/compgen/READEME.md) for instructions and guidance.

## License

By contributing, you agree that your contributions will be licensed under its [License Name].
Expand All @@ -58,4 +74,4 @@ By contributing, you agree that your contributions will be licensed under its [L

Include any references or resources that might be helpful for the contributor.

Thank you for considering contributing to liatrio-otel-collector!
Thank you for considering contributing to liatrio-otel-collector!
30 changes: 18 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ GORELEASER_VERSION = 1.20.0
GOLANGCI_LINT_VERSION ?= v1.53.2

# Arguments for getting directories & executing commands against them
# PKG_RECEIVER_DIRS = $(shell find ./receiver/* -type f -name "go.mod" -print -exec dirname {} \; | sort | uniq)
PKG_RECEIVER_DIRS = $(shell find ./receiver/* -type f -name '*go.mod*' | sed -r 's|/[^/]+$$||' |sort | uniq )
PKG_DIRS = $(shell find ./* -not -path "./build/*" -not -path "./tmp/*" -type f -name "go.mod" -exec dirname {} \; | sort | grep -E '^./')
CHECKS = prep lint-all genqlient-all metagen-all test-all tidy-all fmt-all

# set ARCH var based on output
Expand Down Expand Up @@ -65,20 +64,26 @@ install-tools:
go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)
go install github.com/Khan/genqlient@latest

.PHONY: lint-all $(PKG_RECEIVER_DIRS)
lint-all: $(PKG_RECEIVER_DIRS)

$(PKG_RECEIVER_DIRS):
$(MAKE) -j 4 -C $@ lint
.PHONY: for-all
for-all:
@set -e; for dir in $(DIRS); do \
(cd "$${dir}" && \
echo "running $${CMD} in $${dir}" && \
$${CMD} ); \
done

.PHONY: lint-all
lint-all:
$(MAKE) for-all DIRS="$(PKG_DIRS)" CMD="$(MAKE) lint"

.PHONY: generate
generate: check-prep install-tools
cd tmp/opentelemetry-collector-contrib/cmd/mdatagen && go install .
$(MAKE) -j 4 -C $(PKG_RECEIVER_DIRS) gen
cd $(OCB_PATH)/opentelemetry-collector-contrib/cmd/mdatagen && go install .
$(MAKE) for-all DIRS="$(PKG_DIRS)" CMD="$(MAKE) gen"

.PHONY: test-all
test-all:
$(MAKE) -j 4 -C $(PKG_RECEIVER_DIRS) test
$(MAKE) for-all DIRS="$(PKG_DIRS)" CMD="$(MAKE) test"

.PHONY: cibuild
cibuild: check-prep
Expand All @@ -91,11 +96,11 @@ dockerbuild:

.PHONY: tidy-all
tidy-all:
$(MAKE) -j 4 -C $(PKG_RECEIVER_DIRS) tidy
$(MAKE) for-all DIRS="$(PKG_DIRS)" CMD="$(MAKE) tidy"

.PHONY: fmt-all
fmt-all:
$(MAKE) -j 4 -C $(PKG_RECEIVER_DIRS) fmt
$(MAKE) for-all DIRS="$(PKG_DIRS)" CMD="$(MAKE) fmt"

.PHONY: checks
checks:
Expand All @@ -106,3 +111,4 @@ checks:
else \
echo "completed successfully."; \
fi
fi
2 changes: 1 addition & 1 deletion build/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
"envFile": "${workspaceFolder}/../.debug.env"
}
]
}
}
29 changes: 29 additions & 0 deletions cmd/compgen/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Run Compgen",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}",
"args": [
"receiver",
"github.com/myreceiver",
"${workspaceFolder}/.debug/"
],
"preLaunchTask": "createDebugDir",
"postDebugTask": "deleteDebugDir"
},
{
"name": "Debug Current Test File",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}/${relativeFileDirname}",
}
]
}
25 changes: 25 additions & 0 deletions cmd/compgen/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "createDebugDir",
"type": "shell",
"command": "mkdir",
"args": [
"-p",
"${workspaceFolder}/.debug"
]
},
{
"label": "deleteDebugDir",
"type": "shell",
"command": "rm",
"args": [
"-r",
"${workspaceFolder}/.debug"
]
}
]
}
2 changes: 2 additions & 0 deletions cmd/compgen/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include ../../Makefile.Common

90 changes: 90 additions & 0 deletions cmd/compgen/READEME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Compgen

Compgen is a tool for building new otel components. The following component types are currently supported:

- [Receivers](https://opentelemetry.io/docs/collector/configuration/#receivers)
- Pull (Scraper)
- [ ] Logs
- [x] Metrics
- [ ] Traces
- Push
- [ ] Logs
- [ ] Metrics
- [ ] Traces
- [ ] [Processors](https://opentelemetry.io/docs/collector/configuration/#processors)
- [ ] [Exporters](https://opentelemetry.io/docs/collector/configuration/#exporters)

## Usage

```sh
Compgen is a tool for building new receivers, processors, and exporters for Open Telemetry.

Usage:
compgen [command]

Available Commands:
completion Generate the autocompletion script for the specified shell
help Help about any command
receiver Build a new Open Telemetry receiver component

Flags:
-h, --help help for compgen

Use "compgen [command] --help" for more information about a command.
```

## Naming Conventions for Open Telemetry Components

New component names are passed to compgen via command line arguments. These are expected to be a full [module paths](https://go.dev/ref/mod#glos-module-path) from which compgen will extract a short name to use in code generation.

For example, if you wish to build a new receiver with a short name of `myreceiver`, then supply this string to the receiver subcommand: `github.com/liatrio/liatrio-otel-collector/receiver/myreceiver`

## After Running Compgen

### Makefile

Components are expected to pass a series of tests defined by Makefile.Common. Your component's Makefile must import Makefile.common. An example is provided as a commment.

### Metadata.yaml

Compgen's includes templates for metadata.yaml. This file is used by [mdatagen](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/cmd/mdatagen) to generate aditional code for the component. See the [README](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/cmd/mdatagen/README.md) for details on how to use mdatagen.

You can run mdatagen by running `make gen`.

### Build Component Logic

Compgen's component template are very limited by design. They are intended to supply the minimum amount of code required to compile, start, and run the component in a collector. Component developers are required to add all functionality to fulfill the component's purpose. See [OpenTelemetry's Building Custom Components](https://opentelemetry.io/docs/collector/building/) page for detailed information and examples of how to build new components.

### Building Into The OTEL Binary

When ready, you can compile your new component into Open Telemetry using OCB. Update `config/manifest.yaml` with configurations appropriate for your component. For example, a new receiver named `myreceiver` may require this added yaml:

```yaml
receivers:
- gomod: github.com/liatrio/liatrio-otel-collector/receiver/myreceiver v0.1.0
```
This will instruct OCB to include `myreceiver` when compiling Open Telemetry. Continuing the example, include the following configuration to instruct OCB to use the local code:

```yaml
replaces:
- github.com/liatrio/liatrio-otel-collector/receiver/myreceiver => ../receiver/myreceiver/
```

See [OpenTelemetry's Building a Custom Collector](https://opentelemetry.io/docs/collector/custom-collector/) documentation for additional guidance.

## Contributing to Compgen

### Adding Commands to Compgen

Compgen is built on the [Cobra](https://github.com/spf13/cobra) library. While new commands can be added manually, it may be easier to use the [cobra-cli](https://github.com/spf13/cobra-cli/blob/main/README.md) instead. New commands can be added to compgen by running the following shell commands:

```sh
cd cmd/compgen
cobra-cli add [command-name]
cobra-cli add [command-name] -p [parent-command-name]
```

### Adding Templates to Compgen

New compgen commands are expected to be paired with new templates for Open Telemetry compnents. These templates should include the minimum functionality required to compile, start, and run the component in a collector. Conversely, these templates should include the maximum supporting code expected for the component, such as README and Makefile templates.
77 changes: 77 additions & 0 deletions cmd/compgen/cmd/common/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package cmd

import (
"errors"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
)

type TemplateData struct {
Name string
PackageName string
}

func Tidy(path string) error {
cmd := exec.Command("go", "mod", "tidy", "-e")
cmd.Dir = path
output, err := cmd.CombinedOutput()
if err != nil {
return errors.New(string(output))
}
return nil
}

func Render(source fs.FS, destination string, data TemplateData) error {
// Iterate over all files/folders in 'source' and execute func() for entry found
return fs.WalkDir(source, "templates", func(path string, entry fs.DirEntry, err error) error {
// There was an error reading the fs. So we return the error to stop execution
if err != nil {
return err
}

// WalkDir starts with the root directory passed. So we skip the first iteration
if path == "templates" {
return nil
}

// We remove the top-level 'templates' directory
// E.g. "templates/main.go.tmpl" becomes "main.go.tmpl"
newFilename, err := filepath.Rel("templates", path)
if err != nil {
return err
}

newFilename = filepath.Join(destination, strings.TrimSuffix(newFilename, ".tmpl"))

// Copy directories
if entry.IsDir() {
return os.MkdirAll(newFilename, os.ModePerm)
}

// Note that 'path' is not unmodified
if strings.HasSuffix(path, ".tmpl") {
content, err := fs.ReadFile(source, path)
if err != nil {
return err
}

file, err := os.Create(newFilename)
if err != nil {
return err
}
defer file.Close()

// The template is finally rendered and immediately written to file
tmpl := template.Must(template.New(newFilename).Parse(string(content)))
return tmpl.Execute(file, data)
}

// The entry is not a directory and its name does not match *.tmpl
// Do nothing with these entries and continue iterating.
return nil
})
}
Loading

0 comments on commit acd1d4e

Please sign in to comment.