-
Notifications
You must be signed in to change notification settings - Fork 273
feat: add auto-triage via Backstage #2240
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
simaarfania
wants to merge
16
commits into
main
Choose a base branch
from
simaarfania/add-autotriaging-gha
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
563eb41
feat: add auto-triage via Backstage
simaarfania b55e769
Fix security issues
spinillos cfd91cb
Update hashes
spinillos 4d50719
Get secrets from vault
spinillos f7cf66e
Login with service account
spinillos f072690
Remove login to gar
spinillos d85eb98
fix(backstage-lookup): traverse relations to look for GitHub projects
Duologic b6ae38e
Merge branch 'main' into simaarfania/add-autotriaging-gha
simaarfania d8ed195
fix: source backstage URL from secrets vault
simaarfania a563d41
Pass access token to the script as env
spinillos dea3970
feat: add functions to add issues to GitHub projects
Duologic 92685f8
refactor: use go-backstage lib instead of homegrown
Duologic 574b393
docs: fix variable name
Duologic 51f823e
feat: add verbose error handling
simaarfania 9351133
feat: add dry-run flag
Duologic c00e772
fix: allow overriding the groupRef
Duologic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| name: autoassign | ||
|
|
||
| on: | ||
| issues: | ||
| types: [opened] | ||
|
|
||
| permissions: | ||
| issues: write | ||
| contents: read | ||
| repository-projects: write | ||
|
|
||
| jobs: | ||
| auto-assign: | ||
| runs-on: ubuntu-latest | ||
| if: contains(github.event.issue.body, 'Affected Resource(s)') | ||
| steps: | ||
| - name: Checkout repository | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Set up Go | ||
| uses: actions/setup-go@v4 | ||
| with: | ||
| go-version: '1.21' | ||
|
|
||
| - name: Build backstage-lookup tool | ||
| run: | | ||
| cd scripts/backstage-lookup | ||
| go build -o ../../backstage-lookup | ||
|
|
||
| - name: Parse issue form | ||
| uses: stefanbuck/github-issue-parser@v3 | ||
| id: issue-parser | ||
| with: | ||
| template-path: .github/ISSUE_TEMPLATE/3-bug-report-enhanced.yml | ||
|
|
||
| - name: Lookup team ownership | ||
| id: backstage-lookup | ||
| env: | ||
| BACKSTAGE_URL: ${{ vars.BACKSTAGE_URL || 'https://enghub.grafana-ops.net' }} | ||
| TERRAFORM_AUTOMATION_TOKEN: ${{ secrets.TERRAFORM_AUTOMATION_TOKEN }} # TODO: confirm this works | ||
| run: | | ||
| RESOURCES=$(echo '${{ steps.issue-parser.outputs.jsonString }}' | jq -r '.["affected-resources"] // empty' | tr '\n' ' ') | ||
|
|
||
| if [[ -z "$RESOURCES" ]]; then | ||
| echo "projects=" >> $GITHUB_OUTPUT | ||
| echo "teams=" >> $GITHUB_OUTPUT | ||
| exit 0 | ||
| fi | ||
|
|
||
| echo "Resources: $RESOURCES" | ||
| ./backstage-lookup $RESOURCES >> $GITHUB_OUTPUT || { | ||
| echo "projects=" >> $GITHUB_OUTPUT | ||
| echo "teams=" >> $GITHUB_OUTPUT | ||
| } | ||
|
|
||
| - name: Assign to projects and add labels | ||
| if: steps.backstage-lookup.outputs.teams != '' | ||
| env: | ||
| GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} | ||
| run: | | ||
| # Add to projects | ||
| for project in ${{ steps.backstage-lookup.outputs.projects }}; do | ||
| [[ -n "$project" ]] && gh project item-add $project --url ${{ github.event.issue.html_url }} | ||
| done | ||
|
|
||
| # Add team labels | ||
| for team in ${{ steps.backstage-lookup.outputs.teams }}; do | ||
| [[ -n "$team" ]] && gh issue edit ${{ github.event.issue.number }} --add-label "team/$team" | ||
| done | ||
|
||
|
|
||
| - name: Add comment | ||
| uses: actions/github-script@v7 | ||
| with: | ||
| script: | | ||
| const teams = '${{ steps.backstage-lookup.outputs.teams }}'.split(' ').filter(t => t); | ||
| const projects = '${{ steps.backstage-lookup.outputs.projects }}'.split(' ').filter(p => p); | ||
|
|
||
| const message = teams.length > 0 | ||
| ? `🤖 **Auto-assigned to:** ${teams.map(t => `@grafana/${t}`).join(' ')}\n**Projects:** ${projects.join(', ') || 'none'}` | ||
| : `🔍 **Manual triage needed** - no team ownership found. Please mention \`@grafana/platform-monitoring\``; | ||
|
|
||
| await github.rest.issues.createComment({ | ||
| issue_number: context.issue.number, | ||
| owner: context.repo.owner, | ||
| repo: context.repo.repo, | ||
| body: message | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| module backstage-lookup | ||
|
|
||
| go 1.21 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "net/http" | ||
| "os" | ||
| "regexp" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
||
| // Constants for API and configuration | ||
| const ( | ||
| defaultURL = "https://enghub.grafana-ops.net" | ||
spinillos marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| defaultTimeout = 30 * time.Second | ||
| groupPrefix = "group:" | ||
| ) | ||
|
|
||
| // Environment variable names | ||
| const ( | ||
| EnvBackstageURL = "BACKSTAGE_URL" | ||
| EnvToken = "TERRAFORM_AUTOMATION_TOKEN" | ||
| ) | ||
|
|
||
| // API response types | ||
| type Component struct { | ||
| Spec struct { | ||
| Owner string `json:"owner"` | ||
| } `json:"spec"` | ||
| } | ||
|
|
||
| type Group struct { | ||
| Metadata struct { | ||
| Links []struct { | ||
| Type string `json:"type"` | ||
| URL string `json:"url"` | ||
| } `json:"links"` | ||
| } `json:"metadata"` | ||
| } | ||
|
|
||
| // Result represents the lookup result | ||
| type Result struct { | ||
| Projects []string | ||
| Teams []string | ||
| } | ||
|
|
||
| // BackstageLookup handles API interactions with Backstage | ||
| type BackstageLookup struct { | ||
| client *http.Client | ||
| baseURL string | ||
| token string | ||
| projectRegex *regexp.Regexp | ||
| } | ||
|
|
||
| // NewBackstageLookup creates a new Backstage API client | ||
| func NewBackstageLookup(baseURL, token string) *BackstageLookup { | ||
| if baseURL == "" { | ||
| baseURL = defaultURL | ||
| } | ||
| return &BackstageLookup{ | ||
| client: &http.Client{Timeout: defaultTimeout}, | ||
| baseURL: baseURL, | ||
| token: token, | ||
| projectRegex: regexp.MustCompile(`/projects/(\d+)`), | ||
| } | ||
| } | ||
|
|
||
| // get performs an authenticated HTTP request to Backstage API | ||
| func (b *BackstageLookup) get(url string) ([]byte, error) { | ||
| req, err := http.NewRequest(http.MethodGet, url, nil) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("creating request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Authorization", "Bearer "+b.token) | ||
| req.Header.Set("Accept", "application/json") | ||
|
|
||
| resp, err := b.client.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("executing request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("status %d", resp.StatusCode) | ||
| } | ||
|
|
||
| return io.ReadAll(resp.Body) | ||
| } | ||
|
|
||
| // findOwner retrieves the owner of a component by trying different prefixes and namespaces | ||
| func (b *BackstageLookup) findOwner(resource string) string { | ||
| endpoints := []string{ | ||
| "default/resource-", "default/datasource-", | ||
| "backstage-catalog/resource-", "backstage-catalog/datasource-", | ||
| } | ||
|
|
||
| for _, endpoint := range endpoints { | ||
| url := fmt.Sprintf("%s/api/catalog/entities/by-name/component/%s%s", b.baseURL, endpoint, resource) | ||
|
|
||
| data, err := b.get(url) | ||
| if err != nil { | ||
| continue | ||
| } | ||
|
|
||
| var comp Component | ||
| if json.Unmarshal(data, &comp) == nil && comp.Spec.Owner != "" { | ||
| return comp.Spec.Owner | ||
| } | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // findProject retrieves GitHub project information for a group | ||
| func (b *BackstageLookup) findProject(namespace, team string) string { | ||
| url := fmt.Sprintf("%s/api/catalog/entities/by-name/group/%s/%s", b.baseURL, namespace, team) | ||
|
|
||
| data, err := b.get(url) | ||
| if err != nil { | ||
| return "" | ||
| } | ||
|
|
||
| var group Group | ||
| if json.Unmarshal(data, &group) != nil { | ||
| return "" | ||
| } | ||
|
|
||
| for _, link := range group.Metadata.Links { | ||
| if link.Type == "github_project" { | ||
| if matches := b.projectRegex.FindStringSubmatch(link.URL); len(matches) >= 2 { | ||
| return matches[1] | ||
| } | ||
| } | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // parseOwner parses a group owner string into namespace and name | ||
| func parseOwner(owner string) (namespace, team string) { | ||
| if !strings.HasPrefix(owner, groupPrefix) { | ||
| return "", "" | ||
| } | ||
|
|
||
| parts := strings.Split(strings.TrimPrefix(owner, groupPrefix), "/") | ||
| if len(parts) == 2 { | ||
| return parts[0], parts[1] | ||
| } | ||
| return "", "" | ||
| } | ||
|
|
||
| // LookupResource looks up project and team information for a Terraform resource | ||
| func (b *BackstageLookup) LookupResource(resource string) (projects, teams []string) { | ||
| if resource == "Other (please describe in the issue)" { | ||
| return nil, nil | ||
| } | ||
|
|
||
| log.Printf("Processing: %s", resource) | ||
|
|
||
| owner := b.findOwner(resource) | ||
| if owner == "" { | ||
| log.Printf("No owner found for %s - manual triage needed", resource) | ||
| return nil, nil | ||
| } | ||
|
|
||
| namespace, team := parseOwner(owner) | ||
| if namespace == "" || team == "" { | ||
| log.Printf("Invalid owner %s for %s - manual triage needed", owner, resource) | ||
| return nil, nil | ||
| } | ||
|
|
||
| log.Printf("Found owner %s for %s", owner, resource) | ||
|
|
||
| if project := b.findProject(namespace, team); project != "" { | ||
| log.Printf("Found project %s for team %s", project, team) | ||
| return []string{project}, []string{team} | ||
| } | ||
|
|
||
| log.Printf("No project found for team %s", team) | ||
| return nil, []string{team} | ||
| } | ||
|
|
||
| func unique(slice []string) []string { | ||
| seen := make(map[string]bool) | ||
| result := make([]string, 0, len(slice)) | ||
| for _, item := range slice { | ||
| if !seen[item] { | ||
| seen[item] = true | ||
| result = append(result, item) | ||
| } | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| func main() { | ||
| log.SetFlags(log.LstdFlags | log.Lshortfile) | ||
|
|
||
| if len(os.Args) < 2 { | ||
| log.Fatal("Usage: backstage-lookup <resource1> [resource2] ...") | ||
| } | ||
|
|
||
| baseURL := os.Getenv("BACKSTAGE_URL") | ||
| token := os.Getenv("TERRAFORM_AUTOMATION_TOKEN") | ||
| if token == "" { | ||
| log.Fatal("TERRAFORM_AUTOMATION_TOKEN required") | ||
| } | ||
|
|
||
| lookup := NewBackstageLookup(baseURL, token) | ||
|
|
||
| var allProjects, allTeams []string | ||
| for _, resource := range os.Args[1:] { | ||
| if resource = strings.TrimSpace(resource); resource != "" { | ||
| // Clean resource name | ||
| resource = strings.TrimSuffix(strings.TrimSuffix(resource, " (resource)"), " (data source)") | ||
| projects, teams := lookup.LookupResource(resource) | ||
| allProjects = append(allProjects, projects...) | ||
| allTeams = append(allTeams, teams...) | ||
| } | ||
| } | ||
|
|
||
| fmt.Printf("projects=%s\n", strings.Join(unique(allProjects), " ")) | ||
| fmt.Printf("teams=%s\n", strings.Join(unique(allTeams), " ")) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.