AppPlatform: Introduce experimental Github integration for dashboard configuration management (#96329)

* [Provisioning] Pay back some technical debt (#100720)

* Handle pagination in github client

* Add some unit test coverage

* Remove unknown repository

* Remove unknown leftover

* Revert "Add some unit test coverage"

This reverts commit 420c9674d2.

* Revert "Revert "Add some unit test coverage""

This reverts commit f7eca41957.

* Revert unit tests in github package

* Remove S3 case as it's now deprecated

* [Provisioning] Consolidate job status report in JobProgressRecorder (#100718)

* Log also successful operation

* Consolidate stop logic under TooManyErrors

* Use error for TooManyErrors

* Pass the progress recorder

* Define JobProgressRecorder interface

* Do not expect workers to return status

* Remove scenarios due to pointers

* Use recorder to manage the entire state

* Provisioning: Support rotating secrets (#100705)

* Provisioning: Refactor webhook to another interface (#100733)

* POC/Provisioning: Remove S3 references (#100734)

* Remove unused script

* Remove s3 references

* Provisioning: Keep the existing k8s name if it is specified in metadata (#100672)

* keep name

* keep name

* Revert "keep name"

This reverts commit 29f87bcaeb.

* Commit stale go.mod

* Keep name also for sync deletions

---------

Co-authored-by: Roberto Jimenez Sanchez <roberto.jimenez@grafana.com>

* Update preview banner copy

* Query Library: Move backend to enterprise (#100371)

* Fix wire

* Fix jobs table re-renders

* Provisioning: Refactor history to its own interface (#100735)

* Provisioning: Refactor history to its own interface

* refactor: use VersionedRepository

* Update API

* Provisioning: Test the GitHub client directly (#100808)

* Provisioning: Test the GitHub client directly

Instead of mocking the abstracted client, test it as well by mocking the underlying GitHub client. This also lets us
remove the mock for the abstracted client.

* refactor: move out helpers

* chore: set dependency owner

* Provisioning: Better clone/push error support (#100854)

* Provisioning: Replace searcher with one that knows about modes (#100857)

* Provisioning: Start in "mode5" when nothing exists in legacy (#100862)

* [Provisioning] Fix duplicate sync jobs triggered in controller (#100870)

* Improve logging on reasons why the controller triggered

* Fix messaging for sync job

* fix lint

* Provisioning: Move legacy export/import into a single migrate job (#100865)

* [Provisioning] Miscellanenous bug fixes and improvements (#100976)

* Error if found duplicate ID

* Fix issue with manual test button

* Fix issue with health errors not going away

* Display status in sync overview

* Use patch operations instead

* Trigger sync job after status update

* Convert Export Tab into modal

* Remove unused FieldSet import

* Only last 8 jobs

* Remove Links card

* Use button for Github Source Code

* Add actions to resources page

* Add resource column to Repository Resources

* Display Job Spec in RecentJobs

* Display dates in history page

* Display Avatar if available

* Improve styling of the avatar

* Update betterer

* Remove duplicate history header in history

* Commit betterer

* Address code styling issues

* update flags

* github v69

* v69

* POC/Provisioning: Add wizard (#100596)

* Chore: make update-workspace

* Chore: Fix lints (#101039)

* Provisioning: Workflows as write access (#101031)

* workflow as write access

* workflow as write access

* workflow as write access

* Update pkg/registry/apis/provisioning/repository/test.go

Co-authored-by: Mariell Hoversholm <mariell.hoversholm@grafana.com>

* POC/Provisioning: Add wizard (#100596)

* update refs

* update refs

* lint fix

* lint fix

* lint fix

* default everythign to read only

* reuse form components

* remove main

---------

Co-authored-by: Mariell Hoversholm <mariell.hoversholm@grafana.com>
Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* merge main

* Fix workflow types

* Betterer

* [Provisioning] Fix webhook and finalizer issues (#101052)

Fix webhook and finalizer issue

The maximum number of webhooks per repository is 20

* [Provisioning] Fix issue with last ref (#101056)

* Fix issue with last ref

* Update frontend code

* Fix the local tmp test

* Use lastRef

* POC/Provisioning: Simplify connect step (#101064)

* Fix sending workflows

* Use write for local

* Move connect action to the next step

* Remove wizard props

* Typo

* Redirect to wizard

* Show repo link after successful export

* Provisioning: Avoid starting sync jobs when using legacy storage (#101114)

* avoid starting sync jobs on legacy

* newlines

* Provisioning: Onboarding landing page (#101112)

* add landing page before wizard

* Update onboarding page

* Update URL

* Remove unused

* Add deleteAll button

* Improved text

* betterer

---------

Co-authored-by: Clarity-89 <homes89@ukr.net>

* Provisioning: use the sync job to finish the migrate job (#101107)

* Provisioning: Show progress more often (#101128)

* show progress bar earlier

* show progress bar earlier

* update wording to be less specific

* POC/Provisioning: Enable sync (#101131)

* update preview banner

* actualy remove and don't crash without provisioning flag

* Update db banner

* Provisioning: Export oldest items first (#101189)

* Provisioning: better branch handling (#101188)

* add missing file

* Provisioning: Fix tests (#101197)

* Provisioning: Refactor tests to be multiple functions

* Provisioning: Fix tests

* fix: make github-example sync

* fix misspell

* Provisioning: avoid migration wizard if things are already in unified storage (#101204)

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* more lint

* POC/Provisioning: Handle connect step errors (#101192)

* Provisioning: Unify status handling in repository and migrate steps

* Refactor: Move WorkflowsField outside RepositoryStep and use proper type

* Refactor: Improve repository verification error handling and UI

* Refactor: Simplify repository verification error handling

* Refactor: Simplify RepositoryStep component structure

* Refactor: Improve error handling in RepositoryStep

* Refactor: Remove redundant repository creation logic from ProvisioningWizard

* Refactor: Simplify RequestErrorAlert component

* show github error

* now will verify

* test .git

* recover from bad config

* Update error handling

* Remove unused prop

* merge upstream

* Show migration summary

* Update text

* Improve text

* Betterer

* [Provisioning] Review controller changes (#101216)

* Review health check conditions

* Move down the logic to set up the sync status

* Skip if it's only a health check rerun

* Fix health check conditions

* Preserve last ref

* Format code

* Rename to shouldSkipSync

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>
Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>

* fix promotion step

* In the promotion pipeline, publish should depend on build

* fix promotion pipeline

* [Provisioning] Use smaller methods to process repository events (#101240)

* update codegen

* merge main

* Provisioning: Avoid localhost error loop (#101253)

* Provisioning: Update the recent jobs formatting (#101250)

format history

* [Provisioning] Refactor Pull Request & Lint worker (#101273)

* Refactor the code

* Refactor into separate files

* Consolidate linter flag in one spot

* Use global feature flags

* Commit betterer

* Remove from JSON the intermidiate flag

* Use again spec

* Clean up

* Revert changes in test

* POC/Provisioning: Remove sync confirm modal (#101281)

* [Provisioning] Remove linting from MVP (#101286)

* Remove Linting backend

* Re-generate client

* POC/Provisioning: Unify tags (#101218)

* Unify tags

* add both tags

* add tag types

* Check for the redirect only once

* Add fetch settings with delay hook

* Refetch settings

* Split hooks into separate files

* Cleanup

* Prettier

* Prettier

* Remove lint code

* Betterer

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Provisioning: Update token instructions (#101280)

* Provisioning: Use blob storage rather than local file system to save images (#101298)

* [Provisioning] Add more explicit setup warnings if webhook integration and image rendering are disabled (#101304)

* Setup warnings if renders or webhooks are not possible

* Improve display

* Use a single Alert

* Make design more compact

* Only display local config is missing critical feature toggles

* Improve styling of required flags

* Add file name to the custom ini itself

* Add copy button

* Add FeatureSection Component

* Commit betterer

* Use an interactive table

* Use a modal for instructions

* Use the same modal for example config

* Improve setup steps

* Improve stepper

* Copy code ctrl + c

* Make it more compact

* Select feature to enable

* Improve the height of alerts

* Separate components

* Better warnings

* Improve the page

* Improve the cards

* Improve cards even more

* Improve cards

* Improve cards

* Optional copy in code block

* Add side bar with steps

* Improve styling

* Style modal

* Clean up Code

* Remove index file

* Simplify Step Component

* Commit betterer

* Simplify components

* Use CodeEditor and Clipboard components

* Do not show scrollback on minimum size

* Fix positioning of footer

* Separate Component for Feature

* Use different styling

* Commit betterer

* Use more Grafana components in the FeatureCard

* Separate sidebar into own components

* Simplify sidebar code

* Commit betterer

* Remove connector

* Simplify styling further

* Use cards

* Improve code

* Use more grafana component in InstructionsModal

* Further simplify

* Simplify the code

* Simplify style

* Clean up

* Simplify the Wizard

* Use little icons

* Improve feature cards

* Improve cards

* Commit betterer

* Add description to feature setup

* Improve instructions for snapshot preview

* Move all files into Setup folder

* Commit betterer

* Clean up the warnings code

* Improve coding

* Move sidebar item to separate fiel

* Rename components

* Fix issues

* Use stack instead

* Improve style

* Don't show setup button if configured already

* Simplify again CSS

* Use secondary actions

* Style a bit more

* Improve wording

* Update warning

* Refer to docs in Image Renderer

* More clean up

* Revert changes in generated client

* Fix typos and imports

* Fix lint errors

* Provisioning: better error support (#101490)

* update openapi snapshot

* fix build

* Provisioning: Only show setup page when feature toggles are missing (#101502)

* form fixing

* form fixing

* always send UID

* Same onboarding page regarless of migration (#101557)

* backend building... frontend still broken

* rename sync with main

* Provisioning: Update dashboard badge (#101599)

* Rename to push / pull everything user-facing (#101577)

* Rename to push / pull all everything user-facing

* Use automatic pulling wording

* Provisioning: Migrate when using unified storage (#101572)

* migrate when not unified

* Update pkg/registry/apis/provisioning/register.go

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>

* variables

* merge main

---------

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>

* Add tabs and features tab to listing page (#101570)

* List features in onboarding page (#101558)

* merge main

* POC/Provisioning: Check if the instance is provisioned (#101601)

* Check if the instance is provisioned

* Fix lints

* Fix getting config for new dashboard

* Fixes after merge

* More fixes

* Show success message

* Fix default value

* Add test

* Fix lints

* Provisioning: Include URLs in ResourceWrapper response (#101511)

* Convert Migrate wizard into a Connection Wizard (#101575)

* Convert Migrate wizard into a Connection Wizard

* Remove duplicate empty state

* Allow users to select target in the first step

* Remove file created by merge

* Select target based on existing connections

* Default option for targets and explainatory alert

* Do not display connect button if single connection

* Display target as tag in repository card

* Add Pull Step

* Fix linting

* User decides if migrate or connect

* Improve style based based on review

* Provisioning: Return upsert resource when writing (#101574)

* [Provisioning] Getting Started Page and Tab (#101701)

* merge main

* fix go.mod

* Provisioning: Redirect to the new URL after save (#101757)

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* POC/Provisioning: create folder (#101619)

* Add NewProvisionedFolderForm

* Cleanup

* Add folder api

* Register API

* Do not show provisioned badge for instances

* Enable saving

* Show saved alert

* Fixes

* Fix deps

* Cleanup

* Add test

* Add test

* Updates

* Fix test

* Fix import

* [Provisioning] Display instance connection directly in home (#101720)

* Show tabs directly in home page for instance sync

* Display actions also in the home page

* Add delete button to actions

* Fix issue with files tab

* Display tabs also in instant sync

* Generate connection name for instance sync

* Fix issues when no repositories

* Set active tab

* Remove leftover

* Rename component for listing folder repository

* Fix linting issues

* Fix merge error

* Rename to HomePage

* Split folder list into separate component

* Create own component for repository card

* Improve RepositoryCard readability

* Improve RepositoryCard styling

* Make view primary button

* Fix syntax

* Fix generateName

* merge main

* Provisioning: Move folder management into its own helper (#101864)

* folder

* update folder links

* Fix test

* update

* cleanup

---------

Co-authored-by: Clarity-89 <homes89@ukr.net>

* fixed folder issue

* POC/Provisioning: Create folder from root (#101921)

* Enable creating folder at the root

* Fix test

* Add interceptor

* Provisioning: Expose stats (#101927)

* [Provisioning] Unified onboarding wizard (#101952)

* Spike the solution

* More work

* Add more situations

* Attempt to display count of dashboards and folders

* Attempt with file count

* Do not display options if not possible

* Improve styling resources

* Use another API

* Fix issue with selection

* Style a bit

* Fix more issues

* Make the sync step work

* Improve links

* Use LinkButton

* Start pull automatically

* Start migration automatically

* Fix issue with options

* Fix issues

* Fix loading error

* Improve more things

* Improve styling

* Improve messaging

* Set the autofocus

* Fix some issues

* Fix issue with disabled options

* Only resources

* Finish settings depending on configuration

* Move title to wizard

* Fix title

* Improve styling

* Badge

* Explain on hover

* Improve styling

* Disabled at the bottom

* History & identifiers

* Improve wording

* Add padding left and right disable options

* Delete repository

* Improve buttons

* Give index time to catch up

* Improve buttons

* Handle steps with only forms

* Fix issue with initial migrate or pull

* Commit betterer

* Error messages

* Use memo

* Revampt that a bit

* Attempt to simplify the state and components

* Improve the component for Migrate

* Commit betterer

* Fix issue in next button

* Clean up more

* Start for boostrap step

* Fix issue with running status

* Fix issue with loading bootstrapping

* Improve loading

* Improve more the loading

* Fix issue with loading

* Empty tree

* Handle error

* Fix issue with looping

* Remove commented out lines

* Add comment

* Remove accidental file

* Fix imports

* Improve MigrateStep and PullStep

* Use hook for step status

* JobStep component

* Refactor data fetching

* Validate with Github

* Fix issue with failed error

* Fix next on success

* Address small comments

* Separate file for WizardContent

* Fix linting

* Use step approach also for bootstrap

* Make the logic for moving between steps clearer

* Fix navigation issue

* Clean up some logic

* Use useAsync for JobStep steps

* Revert "Use useAsync for JobStep steps"

This reverts commit 242a275cc9.

* Provisioning: use service to get counts (#101972)

counts

* must migrate when using legacy storage

* Revert "Revert "Use useAsync for JobStep steps""

This reverts commit a420d0ac36.

* Fix async conditions

* Organize imports

* Separate component for BootstrapOptionCard

* BootstrapOptionsList

* Remove duplicate definitions

---------

Co-authored-by: Clarity-89 <homes89@ukr.net>
Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Merge

* Fix utils

* POC/Provisioning: Fix folder path for dashboard (#101997)

* Provisioning: Fix folder path for dashboards

* Fix isNew

* Update test

* Fix any error

* Betterer

* [Provisioning] Improve progress recording and updates (#102035)

* do not validate on delete

* Provisioning: Implement authorizer for remaining resources (#101945)

* feat: implement authorizer for remaining resources

* fix: don't allow viewers to write files

* security: harden blob id fetching

* add integration test for admin vs viewer

* feat: only Get is a valid verb for reads in our subresources

Co-Authored-By: Ryan McKinley <ryantxu@gmail.com>

* feat: allow render for all requests

* refactor: use guards

Not changing code that goes `if a { } else if b { } else { }` as the semantic meaning of the different branches is
easier to parse.

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* POC/Provisioning: Improve wizard setup (#102066)

* wizard actions

* workign better

* remove more memo

* show polling interval

* cleanup

* finalizers

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/WizardContent.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/WizardContent.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* Update public/app/features/provisioning/Wizard/BootstrapStep.tsx

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>

* updates from alex

* updates from alex

* Simplify actions

* Extract props

* history supported form legacy only (for now)

* More refactor

* change order

* Fix cleanup finalizer

* show kinds

* fix lint

---------

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>
Co-authored-by: Clarity-89 <homes89@ukr.net>
Co-authored-by: Roberto Jimenez Sanchez <roberto.jimenez@grafana.com>

* Fix resource condition (#102086)

* Fix job summary stats issue (#102084)

* merge main

* Repository link should point to configured branch (#102092)

* Add getRepoHref

* Fix random string generation

* Redirect to Home on repository deletion (#102096)

* Fix extra commas in pull request comment (#102108)

* Fix image rendering endpoint (#102107)

* POC/Provisioning: Support migrate... when starting with unified storage (#102097)

* use same clone

* now using upsert

* Fix lint

---------

Co-authored-by: Roberto Jimenez Sanchez <roberto.jimenez@grafana.com>

* Clean up unprovisioned resources after unified storage migration (#102126)

* Clean up unprovisioned resources after migrate

* Clean up unprovisioned resources after migrate

* Update pkg/registry/apis/provisioning/jobs/migrate/resources.go

* Reset summary between export and pull (#102101)

* Reset summary between export and pull

* Add reset results to unified storage migration

* Provisioning: always dirty (#102151)

* fix test version

* log the watch line

* POC/Provisioning: Disable repository list watch (#102169)

* Disable watch for repo list endpoint

* Add comment

* Remove another watch

* Provisioning: Avoid calling test on every update (#102161)

test less often

* Provisioning: Support prefixes in GitHub repositories (#101969)

* feat: add a Prefix property to GitHub repo spec

* feat: make nested folders work properly

* feat: use subdir for go-git export

* fix: placeholder for prefix should be grafana/

* feat: rename prefix to path

* fix: json name should be path, too

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* chore: regen apis

* fix: copy 'path'

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Merge

* Fix duplicate type

* Provisioning: Test export functionality (#101336)

* Provisioning: Test export functionality

* fix: use context.Background

* test: add more cases for local repo path resolving

* test: rework test inputs

* test: try to make github test work

* fix: clear global state

* Update api client imports

* Fix import

* Fix test

* Update codegen

* Provisioning: Make it green (#102271)

* chore: remove unused functions

* chore: update betterer results

* chore: update openapi spec

* chore: yarn generate-apis

* fix: specify default false if undefined

* Use AnnoKeyManagerIdentity

* Add manager kind

* POC/Provisioning: Update component structure (#102297)

* Update project structure

* Update imports

* Remove unused components

* Copy fixes

* Typo

* More copy fixes

* Betterer

* Update test

* merge main

* Provisioning: Replace hardcoded clients with discovery client (#101918)

* disco client

* discovery client

* merge main

* merge main

* keep factory

* keep factory

* find preffered version for delete factory

* use same folders request

* merge main

* with integration test

* POC/Provisioning: Compare spec in test rather than raw JSON (#102352)

* compare spec not json

* compare spec not json

* [Provisioning] Add in-code TODOs in API Server area (#102360)

* Add TODOs for files endpoint

* Add TODO history endpoint

* Add TODO to move files logic to resource package

* Add TODO to not use private fields directly

* Remove unnecessary checks in list connector

* Add pagination TODO in lister

* Add TODO to rename resources

* Add todo about cloning too early

* Add TODO to propose to merge sync and migrate endpoints

* Add TODOs in register

* Add more TODOs in connectors & routes

* Add TODOs about prefix

* Change it to remove

* Update pkg/registry/apis/provisioning/test.go

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* POC/Provisioning: Switch folders to use managedBy (#102362)

* Folders: Switch to managedBy

* Fix create folder

* Fix tests

* Do not allow changing folder from dashboard settings

* Update imports

* Update provisioned meta

* Do not show provisioned badge for child folders

* Fix folder title

* Update folder actions

* Update new provisioned folder form

* Remove unused code

* Fix condition

* Reset default values on change

* Remove duplicate nav item

* Add managedBy to DashboardQueryResult

* Provisioning: support watch over live (in feature branch) (#102408)

* Provisioning: watch cleanup (#102424)

* fix lint

* Provisioning: Add basic usage stats (#102405)

* [Provisioning] Add limitations to Github Repository (#102451)

* Put limits to Github

* File is too large

* Move constants

* Embed ListOptions again

* Remove TODO

* Provisioning: Pick a better default title (#102516)

better title

* Provisioning: sanitize pull request urls (#102517)

* [Provisioning] Clean up clone after export and migrate (#102467)

* Remove clone directory on clone failure

* Defer remove clones

* Log error if removal fails

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* [Provisioning] Limit path length and depth in APIs (#102472)

* Limit filepath length in files API calls

* Add common utility to deal with paths

* Use the existing function

* Fix import

* Update pkg/registry/apis/provisioning/safepath/limit.go

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Fix issue after website commit

* Fix linting issue in test

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Add timeout, JSON check and max body size to endpoints (#102443)

* Add timeout, JSON check and max body size to endpoints

* Use http.MaxBytesReader instead

* Use MaxBytesReader also for reading the entire body

* Add empty line

* Add unit tests

* Fix integration tests

* Update pkg/registry/apis/provisioning/render.go

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* Do not use utils :)

* Fix comment on unmarshalJSON

* 25MB for webhook events

* Remove content type check for files write

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* fix imports

* Provisioning: Remove export option from the UI (#102511)

* [Provisioning] Remove unused checkout method in go-git (#102460)

* [Provisioning] Limit max number of repositories to 10 (#102542)

* Limit to maximum 10 repositories in backend

* Change messaging

* Do not display connect button if more than 10

* Only fetch settings once

* watch repos

---------

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>

* [Provisioning] Limit size and time to git clone and push in go-git (#102458)

* Limit git clone and push time and size

* Fix linting

* Use transport instead to limit

* Remove not supported

* Add TODO to make timeout configurable

* chore: make update-workspace

* Provisioning: Implement a new job queue (#102446)

* feat: implement a new job queue

Outstanding problems:

  * Status isn't saved.
  * Progress updates don't work (due to status not being saved probably?).

* feat: properly save status

* chore: document label

* chore: assumptions do hold

* fix: support multi-tenant job drivers

* fix: use namespace=*

* fix: set resource back to pointer when updating job progress

If we don't do this, we start rejecting job progress updates as the version falls out of sync.

* feat: make job APIs read-only

* fix: complete job when worker returns

* fix: set namespace on requests from controller

* test: check historic jobs

* chore: regen apis

* feat: start augmenting frontend

* feat: add jobs to authorizer

* feat: use watch from input

* fix: make frontend subscribe to historic jobs

* fix: lint

* chore: yarn prettier:write

* fix: frontend lints

* test: allow for empty state in historicjobs

* test: set content type for export request

* fix: always set job name on insert

* fix: import

* fix: use dashes not colons

* fix: job status should expect a historic job transition

* fix: allow PR jobs from multiple PRs

* feat: same name for sync and migrate jobs

* feat: generate a job name in the store

* refactor: rename to persistentStore

* feat: remove status subresources on jobs

* feat: join jobs into one card

* chore: regen openapi snapshot

---------

Co-authored-by: Roberto Jimenez Sanchez <roberto.jimenez@grafana.com>

* Provisioning: Use a complete storage for jobs (#102605)

* feat: add a complete strategy to apiserver

* feat: use the complete storage strategy for jobs

* test: behaviour changed in main

* [Provisioning] Consolidate file path handling (#102617)

* Add more cases for validation

* Call the method dir

* Clean files endpoint

* Simplify further

* Fix issues with folder

* Add Dir function

* Use walk function in folders

* Move things from ID

* Fix some tests

* Add tree

* Sync worker and changes

* Add more TODOs

* Add normal join

* Remove things in local

* Consolidate single Join

* Call it safe

* Add new IsPathSupported action

* Move the depth to resources

* Add more cases

* Improve trie implementation

* Add tests trie

* Fix trie tests

* Improve trie tests

* Add tests for walk

* Fix linting

* Add unit tests filepath

* Remove TODO

* Remove another TODO

* Unsupported file extension error

* Add documentation for IsPathSupported

* Filepath unit tests

* Use safepath to validate github path

* Remove TODO in wrapper

* Use trailing slash in folder internal object

* Fix changes test

* Include dot

* Add TODO to explore own type for path

* Fix frontend lint

* Fix unit tests

* Fix provisioning integration tests

---------

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>
Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>
Co-authored-by: Ryan McKinley <ryantxu@gmail.com>
Co-authored-by: Clarity-89 <homes89@ukr.net>
Co-authored-by: Andrej Ocenas <mr.ocenas@gmail.com>
Co-authored-by: Kevin Minehart <kmineh0151@gmail.com>
This commit is contained in:
Mariell Hoversholm
2025-03-25 08:59:03 +01:00
committed by GitHub
co-authored by Ryan McKinley Alex Khomenko Clarity-89 Roberto Jimenez Sanchez Andrej Ocenas Kevin Minehart
parent e48ec7d6b6
commit 77fa2271be
269 changed files with 24541 additions and 1591 deletions
@@ -0,0 +1,916 @@
package repository
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"regexp"
"slices"
"strings"
"github.com/google/go-github/v69/github"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/google/uuid"
"github.com/grafana/grafana-app-sdk/logging"
provisioning "github.com/grafana/grafana/pkg/apis/provisioning/v0alpha1"
pgh "github.com/grafana/grafana/pkg/registry/apis/provisioning/repository/github"
"github.com/grafana/grafana/pkg/registry/apis/provisioning/safepath"
"github.com/grafana/grafana/pkg/registry/apis/provisioning/secrets"
)
var subscribedEvents = []string{"push", "pull_request"}
// Make sure all public functions of this struct call the (*githubRepository).logger function, to ensure the GH repo details are included.
type githubRepository struct {
config *provisioning.Repository
gh pgh.Client // assumes github.com base URL
secrets secrets.Service
webhookURL string
owner string
repo string
}
var (
_ Repository = (*githubRepository)(nil)
_ Hooks = (*githubRepository)(nil)
_ Versioned = (*githubRepository)(nil)
_ Writer = (*githubRepository)(nil)
_ Reader = (*githubRepository)(nil)
_ RepositoryWithURLs = (*githubRepository)(nil)
)
func NewGitHub(
ctx context.Context,
config *provisioning.Repository,
factory *pgh.Factory,
secrets secrets.Service,
webhookURL string,
) (*githubRepository, error) {
owner, repo, err := parseOwnerRepo(config.Spec.GitHub.URL)
if err != nil {
return nil, err
}
token := config.Spec.GitHub.Token
if token == "" {
decrypted, err := secrets.Decrypt(ctx, config.Spec.GitHub.EncryptedToken)
if err != nil {
return nil, err
}
token = string(decrypted)
}
return &githubRepository{
config: config,
gh: factory.New(ctx, token), // TODO, baseURL from config
secrets: secrets,
webhookURL: webhookURL,
owner: owner,
repo: repo,
}, nil
}
func (r *githubRepository) Config() *provisioning.Repository {
return r.config
}
// Validate implements provisioning.Repository.
func (r *githubRepository) Validate() (list field.ErrorList) {
gh := r.config.Spec.GitHub
if gh == nil {
list = append(list, field.Required(field.NewPath("spec", "github"), "a github config is required"))
return list
}
if gh.URL == "" {
list = append(list, field.Required(field.NewPath("spec", "github", "url"), "a github url is required"))
} else {
_, _, err := parseOwnerRepo(gh.URL)
if err != nil {
list = append(list, field.Invalid(field.NewPath("spec", "github", "url"), gh.URL, err.Error()))
} else if !strings.HasPrefix(gh.URL, "https://github.com/") {
list = append(list, field.Invalid(field.NewPath("spec", "github", "url"), gh.URL, "URL must start with https://github.com/"))
}
}
if gh.Branch == "" {
list = append(list, field.Required(field.NewPath("spec", "github", "branch"), "a github branch is required"))
}
if !isValidGitBranchName(gh.Branch) {
list = append(list, field.Invalid(field.NewPath("spec", "github", "branch"), gh.Branch, "invalid branch name"))
}
// TODO: Use two fields for token
if gh.Token == "" && len(gh.EncryptedToken) == 0 {
list = append(list, field.Required(field.NewPath("spec", "github", "token"), "a github access token is required"))
}
if err := safepath.IsSafe(gh.Path); err != nil {
list = append(list, field.Invalid(field.NewPath("spec", "github", "prefix"), gh.Path, err.Error()))
}
if safepath.IsAbs(gh.Path) {
list = append(list, field.Invalid(field.NewPath("spec", "github", "prefix"), gh.Path, "path must be relative"))
}
return list
}
func parseOwnerRepo(giturl string) (owner string, repo string, err error) {
parsed, e := url.Parse(strings.TrimSuffix(giturl, ".git"))
if e != nil {
err = e
return
}
parts := strings.Split(parsed.Path, "/")
if len(parts) < 3 {
err = fmt.Errorf("unable to parse repo+owner from url")
return
}
return parts[1], parts[2], nil
}
func fromError(err error, code int) *provisioning.TestResults {
statusErr, ok := err.(apierrors.APIStatus)
if ok {
s := statusErr.Status()
return &provisioning.TestResults{
Code: int(s.Code),
Success: false,
Errors: []string{s.Message},
}
}
return &provisioning.TestResults{
Code: code,
Success: false,
Errors: []string{err.Error()},
}
}
// Test implements provisioning.Repository.
func (r *githubRepository) Test(ctx context.Context) (*provisioning.TestResults, error) {
if err := r.gh.IsAuthenticated(ctx); err != nil {
return fromError(err, http.StatusUnauthorized), nil
}
owner, repo, err := parseOwnerRepo(r.config.Spec.GitHub.URL)
if err != nil {
return fromError(err, http.StatusBadRequest), nil
}
// FIXME: check token permissions
ok, err := r.gh.RepoExists(ctx, owner, repo)
if err != nil {
return fromError(err, http.StatusBadRequest), nil
}
if !ok {
return &provisioning.TestResults{
Code: http.StatusBadRequest,
Success: false,
Errors: []string{"repository does not exist"},
}, nil
}
ok, err = r.gh.BranchExists(ctx, r.owner, r.repo, r.config.Spec.GitHub.Branch)
if err != nil {
return fromError(err, http.StatusBadRequest), nil
}
if !ok {
return &provisioning.TestResults{
Code: http.StatusBadRequest,
Success: false,
Errors: []string{"branch does not exist"},
}, nil
}
return &provisioning.TestResults{
Code: http.StatusOK,
Success: true,
}, nil
}
// ReadResource implements provisioning.Repository.
func (r *githubRepository) Read(ctx context.Context, filePath, ref string) (*FileInfo, error) {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
finalPath := safepath.Join(r.config.Spec.GitHub.Path, filePath)
content, dirContent, err := r.gh.GetContents(ctx, r.owner, r.repo, finalPath, ref)
if err != nil {
if errors.Is(err, pgh.ErrResourceNotFound) {
return nil, &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: fmt.Sprintf("file not found; path=%s ref=%s", finalPath, ref),
Code: http.StatusNotFound,
},
}
}
return nil, fmt.Errorf("get contents: %w", err)
}
if dirContent != nil {
return &FileInfo{
Path: filePath,
Ref: ref,
}, nil
}
data, err := content.GetFileContent()
if err != nil {
return nil, fmt.Errorf("get content: %w", err)
}
return &FileInfo{
Path: filePath,
Ref: ref,
Data: []byte(data),
Hash: content.GetSHA(),
}, nil
}
func (r *githubRepository) ReadTree(ctx context.Context, ref string) ([]FileTreeEntry, error) {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, logger := r.logger(ctx, ref)
tree, truncated, err := r.gh.GetTree(ctx, r.owner, r.repo, r.config.Spec.GitHub.Path, ref, true)
if err != nil {
if errors.Is(err, pgh.ErrResourceNotFound) {
return nil, &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: fmt.Sprintf("tree not found; ref=%s", ref),
Code: http.StatusNotFound,
},
}
}
}
if truncated {
logger.Warn("tree from github was truncated")
}
entries := make([]FileTreeEntry, 0, len(tree))
for _, entry := range tree {
converted := FileTreeEntry{
Path: entry.GetPath(),
Size: entry.GetSize(),
Hash: entry.GetSHA(),
Blob: !entry.IsDirectory(),
}
entries = append(entries, converted)
}
return entries, nil
}
func (r *githubRepository) Create(ctx context.Context, path, ref string, data []byte, comment string) error {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, _ = r.logger(ctx, ref)
if err := r.ensureBranchExists(ctx, ref); err != nil {
return fmt.Errorf("create branch on create: %w", err)
}
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
// Create .keep file if it is a directory
if safepath.IsDir(finalPath) {
if data != nil {
return apierrors.NewBadRequest("data cannot be provided for a directory")
}
finalPath = safepath.Join(finalPath, ".keep")
data = []byte{}
}
err := r.gh.CreateFile(ctx, r.owner, r.repo, finalPath, ref, comment, data)
if errors.Is(err, pgh.ErrResourceAlreadyExists) {
return &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: "file already exists",
Code: http.StatusConflict,
},
}
}
return err
}
func (r *githubRepository) Update(ctx context.Context, path, ref string, data []byte, comment string) error {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, _ = r.logger(ctx, ref)
if err := r.ensureBranchExists(ctx, ref); err != nil {
return fmt.Errorf("create branch on update: %w", err)
}
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
file, _, err := r.gh.GetContents(ctx, r.owner, r.repo, finalPath, ref)
if err != nil {
if errors.Is(err, pgh.ErrResourceNotFound) {
return &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: "file not found",
Code: http.StatusNotFound,
},
}
}
return fmt.Errorf("get content before file update: %w", err)
}
if file.IsDirectory() {
return apierrors.NewBadRequest("cannot update a directory")
}
if err := r.gh.UpdateFile(ctx, r.owner, r.repo, finalPath, ref, comment, file.GetSHA(), data); err != nil {
return fmt.Errorf("update file: %w", err)
}
return nil
}
func (r *githubRepository) Write(ctx context.Context, path string, ref string, data []byte, message string) error {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, _ = r.logger(ctx, ref)
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
return writeWithReadThenCreateOrUpdate(ctx, r, finalPath, ref, data, message)
}
func (r *githubRepository) Delete(ctx context.Context, path, ref, comment string) error {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, _ = r.logger(ctx, ref)
if err := r.ensureBranchExists(ctx, ref); err != nil {
return fmt.Errorf("create branch on delete: %w", err)
}
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
return r.deleteRecursively(ctx, finalPath, ref, comment)
}
func (r *githubRepository) deleteRecursively(ctx context.Context, path, ref, comment string) error {
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
file, contents, err := r.gh.GetContents(ctx, r.owner, r.repo, finalPath, ref)
if err != nil {
if errors.Is(err, pgh.ErrResourceNotFound) {
return &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: "file not found",
Code: http.StatusNotFound,
},
}
}
return fmt.Errorf("finding file to delete: %w", err)
}
if file != nil && !file.IsDirectory() {
return r.gh.DeleteFile(ctx, r.owner, r.repo, finalPath, ref, comment, file.GetSHA())
}
for _, c := range contents {
if c.IsDirectory() {
if err := r.deleteRecursively(ctx, c.GetPath(), ref, comment); err != nil {
return fmt.Errorf("delete file recursive: %w", err)
}
continue
}
if err := r.gh.DeleteFile(ctx, r.owner, r.repo, c.GetPath(), ref, comment, c.GetSHA()); err != nil {
return fmt.Errorf("delete file: %w", err)
}
}
return nil
}
func (r *githubRepository) History(ctx context.Context, path, ref string) ([]provisioning.HistoryItem, error) {
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
ctx, _ = r.logger(ctx, ref)
finalPath := safepath.Join(r.config.Spec.GitHub.Path, path)
commits, err := r.gh.Commits(ctx, r.owner, r.repo, finalPath, ref)
if err != nil {
if errors.Is(err, pgh.ErrResourceNotFound) {
return nil, &apierrors.StatusError{
ErrStatus: metav1.Status{
Message: "path not found",
Code: http.StatusNotFound,
},
}
}
return nil, fmt.Errorf("get commits: %w", err)
}
ret := make([]provisioning.HistoryItem, 0, len(commits))
for _, commit := range commits {
authors := make([]provisioning.Author, 0)
if commit.Author != nil {
authors = append(authors, provisioning.Author{
Name: commit.Author.Name,
Username: commit.Author.Username,
AvatarURL: commit.Author.AvatarURL,
})
}
if commit.Committer != nil && commit.Author != nil && commit.Author.Name != commit.Committer.Name {
authors = append(authors, provisioning.Author{
Name: commit.Committer.Name,
Username: commit.Committer.Username,
AvatarURL: commit.Committer.AvatarURL,
})
}
ret = append(ret, provisioning.HistoryItem{
Ref: commit.Ref,
Message: commit.Message,
Authors: authors,
CreatedAt: commit.CreatedAt.UnixMilli(),
})
}
return ret, nil
}
// basicGitBranchNameRegex is a regular expression to validate a git branch name
// it does not cover all cases as positive lookaheads are not supported in Go's regexp
var basicGitBranchNameRegex = regexp.MustCompile(`^[a-zA-Z0-9\-\_\/\.]+$`)
// isValidGitBranchName checks if a branch name is valid.
// It uses the following regexp `^[a-zA-Z0-9\-\_\/\.]+$` to validate the branch name with some additional checks that must satisfy the following rules:
// 1. The branch name must have at least one character and must not be empty.
// 2. The branch name cannot start with `/` or end with `/`, `.`, or whitespace.
// 3. The branch name cannot contain consecutive slashes (`//`).
// 4. The branch name cannot contain consecutive dots (`..`).
// 5. The branch name cannot contain `@{`.
// 6. The branch name cannot include the following characters: `~`, `^`, `:`, `?`, `*`, `[`, `\`, or `]`.
func isValidGitBranchName(branch string) bool {
if !basicGitBranchNameRegex.MatchString(branch) {
return false
}
// Additional checks for invalid patterns
if strings.HasPrefix(branch, "/") || strings.HasSuffix(branch, "/") ||
strings.HasSuffix(branch, ".") || strings.Contains(branch, "..") ||
strings.Contains(branch, "//") || strings.HasSuffix(branch, ".lock") {
return false
}
return true
}
func (r *githubRepository) ensureBranchExists(ctx context.Context, branchName string) error {
if !isValidGitBranchName(branchName) {
return &apierrors.StatusError{
ErrStatus: metav1.Status{
Code: http.StatusBadRequest,
Message: "invalid branch name",
},
}
}
ok, err := r.gh.BranchExists(ctx, r.owner, r.repo, branchName)
if err != nil {
return fmt.Errorf("check branch exists: %w", err)
}
if ok {
logging.FromContext(ctx).Info("branch already exists", "branch", branchName)
return nil
}
srcBranch := r.config.Spec.GitHub.Branch
if err := r.gh.CreateBranch(ctx, r.owner, r.repo, srcBranch, branchName); err != nil {
if errors.Is(err, pgh.ErrResourceAlreadyExists) {
return &apierrors.StatusError{
ErrStatus: metav1.Status{
Code: http.StatusConflict,
Message: "branch already exists",
},
}
}
return fmt.Errorf("create branch: %w", err)
}
return nil
}
// Webhook implements Repository.
func (r *githubRepository) Webhook(ctx context.Context, req *http.Request) (*provisioning.WebhookResponse, error) {
if r.config.Status.Webhook == nil {
return nil, fmt.Errorf("unexpected webhook request")
}
secret, err := r.secrets.Decrypt(ctx, r.config.Status.Webhook.EncryptedSecret)
if err != nil {
return nil, fmt.Errorf("failed to decrypt secret: %w", err)
}
payload, err := github.ValidatePayload(req, secret)
if err != nil {
return nil, apierrors.NewUnauthorized("invalid signature")
}
return r.parseWebhook(github.WebHookType(req), payload)
}
// This method does not include context because it does delegate any more requests
func (r *githubRepository) parseWebhook(messageType string, payload []byte) (*provisioning.WebhookResponse, error) {
event, err := github.ParseWebHook(messageType, payload)
if err != nil {
return nil, apierrors.NewBadRequest("invalid payload")
}
switch event := event.(type) {
case *github.PushEvent:
return r.parsePushEvent(event)
case *github.PullRequestEvent:
return r.parsePullRequestEvent(event)
case *github.PingEvent:
return &provisioning.WebhookResponse{
Code: http.StatusOK,
Message: "ping received",
}, nil
}
return &provisioning.WebhookResponse{
Code: http.StatusNotImplemented,
Message: fmt.Sprintf("unsupported messageType: %s", messageType),
}, nil
}
func (r *githubRepository) parsePushEvent(event *github.PushEvent) (*provisioning.WebhookResponse, error) {
if event.GetRepo() == nil {
return nil, fmt.Errorf("missing repository in push event")
}
if event.GetRepo().GetFullName() != fmt.Sprintf("%s/%s", r.owner, r.repo) {
return nil, fmt.Errorf("repository mismatch")
}
// No need to sync if not enabled
if !r.config.Spec.Sync.Enabled {
return &provisioning.WebhookResponse{Code: http.StatusOK}, nil
}
// Skip silently if the event is not for the main/master branch
// as we cannot configure the webhook to only publish events for the main branch
if event.GetRef() != fmt.Sprintf("refs/heads/%s", r.config.Spec.GitHub.Branch) {
return &provisioning.WebhookResponse{Code: http.StatusOK}, nil
}
return &provisioning.WebhookResponse{
Code: http.StatusAccepted,
Job: &provisioning.JobSpec{
Repository: r.Config().GetName(),
Action: provisioning.JobActionSync,
Pull: &provisioning.SyncJobOptions{
Incremental: true,
},
},
}, nil
}
func (r *githubRepository) parsePullRequestEvent(event *github.PullRequestEvent) (*provisioning.WebhookResponse, error) {
if event.GetRepo() == nil {
return nil, fmt.Errorf("missing repository in pull request event")
}
cfg := r.config.Spec.GitHub
if cfg == nil {
return nil, fmt.Errorf("missing github config")
}
if event.GetRepo().GetFullName() != fmt.Sprintf("%s/%s", r.owner, r.repo) {
return nil, fmt.Errorf("repository mismatch")
}
pr := event.GetPullRequest()
if pr == nil {
return nil, fmt.Errorf("expected PR in event")
}
if pr.GetBase().GetRef() != r.config.Spec.GitHub.Branch {
return &provisioning.WebhookResponse{
Code: http.StatusOK,
Message: fmt.Sprintf("ignoring pull request event as %s is not the configured branch", pr.GetBase().GetRef()),
}, nil
}
action := event.GetAction()
if action != "opened" && action != "reopened" && action != "synchronize" {
return &provisioning.WebhookResponse{
Code: http.StatusOK, // Nothing needed
Message: fmt.Sprintf("ignore pull request event: %s", action),
}, nil
}
// Queue an async job that will parse files
return &provisioning.WebhookResponse{
Code: http.StatusAccepted, // Nothing needed
Message: fmt.Sprintf("pull request: %s", action),
Job: &provisioning.JobSpec{
Repository: r.Config().GetName(),
Action: provisioning.JobActionPullRequest,
PullRequest: &provisioning.PullRequestJobOptions{
URL: pr.GetHTMLURL(),
PR: pr.GetNumber(),
Ref: pr.GetHead().GetRef(),
Hash: pr.GetHead().GetSHA(),
},
},
}, nil
}
func (r *githubRepository) LatestRef(ctx context.Context) (string, error) {
ctx, _ = r.logger(ctx, "")
branch, err := r.gh.GetBranch(ctx, r.owner, r.repo, r.Config().Spec.GitHub.Branch)
if err != nil {
return "", fmt.Errorf("get branch: %w", err)
}
return branch.Sha, nil
}
func (r *githubRepository) CompareFiles(ctx context.Context, base, ref string) ([]VersionedFileChange, error) {
if ref == "" {
var err error
ref, err = r.LatestRef(ctx)
if err != nil {
return nil, fmt.Errorf("get latest ref: %w", err)
}
}
ctx, logger := r.logger(ctx, ref)
files, err := r.gh.CompareCommits(ctx, r.owner, r.repo, base, ref)
if err != nil {
return nil, fmt.Errorf("compare commits: %w", err)
}
changes := make([]VersionedFileChange, 0)
for _, f := range files {
// reference: https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#get-a-commit
switch f.GetStatus() {
case "added", "copied":
changes = append(changes, VersionedFileChange{
Path: f.GetFilename(),
Ref: ref,
Action: FileActionCreated,
})
case "modified", "changed":
changes = append(changes, VersionedFileChange{
Path: f.GetFilename(),
Ref: ref,
Action: FileActionUpdated,
})
case "renamed":
changes = append(changes, VersionedFileChange{
Path: f.GetFilename(),
PreviousPath: f.GetPreviousFilename(),
Ref: ref,
PreviousRef: base,
Action: FileActionRenamed,
})
case "removed":
changes = append(changes, VersionedFileChange{
Ref: base,
Path: f.GetFilename(),
Action: FileActionDeleted,
})
case "unchanged":
// do nothing
default:
logger.Error("ignore unhandled file", "file", f.GetFilename(), "status", f.GetStatus())
}
}
return changes, nil
}
// ClearAllPullRequestFileComments clears all comments on a pull request
func (r *githubRepository) ClearAllPullRequestFileComments(ctx context.Context, prNumber int) error {
ctx, _ = r.logger(ctx, "")
return r.gh.ClearAllPullRequestFileComments(ctx, r.owner, r.repo, prNumber)
}
// CommentPullRequest adds a comment to a pull request.
func (r *githubRepository) CommentPullRequest(ctx context.Context, prNumber int, comment string) error {
ctx, _ = r.logger(ctx, "")
return r.gh.CreatePullRequestComment(ctx, r.owner, r.repo, prNumber, comment)
}
// CommentPullRequestFile lints a file and comments the issues found.
func (r *githubRepository) CommentPullRequestFile(ctx context.Context, prNumber int, path, ref, comment string) error {
ctx, _ = r.logger(ctx, ref)
fileComment := pgh.FileComment{
Content: comment,
Path: path,
Position: 1, // create a top-level comment
Ref: ref,
}
// FIXME: comment with Grafana Logo
// FIXME: comment author should be written by Grafana and not the user
return r.gh.CreatePullRequestFileComment(ctx, r.owner, r.repo, prNumber, fileComment)
}
// ResourceURLs implements RepositoryWithURLs.
func (r *githubRepository) ResourceURLs(ctx context.Context, file *FileInfo) (*provisioning.ResourceURLs, error) {
cfg := r.config.Spec.GitHub
if file.Path == "" || cfg == nil {
return nil, nil
}
ref := file.Ref
if ref == "" {
ref = cfg.Branch
}
urls := &provisioning.ResourceURLs{
RepositoryURL: cfg.URL,
SourceURL: fmt.Sprintf("%s/blob/%s/%s", cfg.URL, ref, file.Path),
}
if ref != cfg.Branch {
urls.CompareURL = fmt.Sprintf("%s/compare/%s...%s", cfg.URL, cfg.Branch, ref)
// Create a new pull request
urls.NewPullRequestURL = fmt.Sprintf("%s?quick_pull=1&labels=grafana", urls.CompareURL)
}
return urls, nil
}
func (r *githubRepository) createWebhook(ctx context.Context) (pgh.WebhookConfig, error) {
secret, err := uuid.NewRandom()
if err != nil {
return pgh.WebhookConfig{}, fmt.Errorf("could not generate secret: %w", err)
}
cfg := pgh.WebhookConfig{
URL: r.webhookURL,
Secret: secret.String(),
ContentType: "json",
Events: subscribedEvents,
Active: true,
}
hook, err := r.gh.CreateWebhook(ctx, r.owner, r.repo, cfg)
if err != nil {
return pgh.WebhookConfig{}, err
}
// HACK: GitHub does not return the secret, so we need to update it manually
hook.Secret = cfg.Secret
logging.FromContext(ctx).Info("webhook created", "url", cfg.URL, "id", hook.ID)
return hook, nil
}
// updateWebhook checks if the webhook needs to be updated and updates it if necessary.
// if the webhook does not exist, it will create it.
func (r *githubRepository) updateWebhook(ctx context.Context) (pgh.WebhookConfig, bool, error) {
if r.config.Status.Webhook == nil || r.config.Status.Webhook.ID == 0 {
hook, err := r.createWebhook(ctx)
if err != nil {
return pgh.WebhookConfig{}, false, err
}
return hook, true, nil
}
hook, err := r.gh.GetWebhook(ctx, r.owner, r.repo, r.config.Status.Webhook.ID)
switch {
case errors.Is(err, pgh.ErrResourceNotFound):
hook, err := r.createWebhook(ctx)
if err != nil {
return pgh.WebhookConfig{}, false, err
}
return hook, true, nil
case err != nil:
return pgh.WebhookConfig{}, false, fmt.Errorf("get webhook: %w", err)
}
hook.Secret = r.config.Status.Webhook.Secret // we always random gen this, so don't use it for mustUpdate below.
var mustUpdate bool
if hook.URL != r.config.Status.Webhook.URL {
mustUpdate = true
hook.URL = r.webhookURL
}
if !slices.Equal(hook.Events, subscribedEvents) {
mustUpdate = true
hook.Events = subscribedEvents
}
if !mustUpdate {
return hook, false, nil
}
// Something has changed in the webhook. Let's rotate the secret as well, so as to ensure we end up with a 100% correct webhook.
secret, err := uuid.NewRandom()
if err != nil {
return pgh.WebhookConfig{}, false, fmt.Errorf("could not generate secret: %w", err)
}
hook.Secret = secret.String()
if err := r.gh.EditWebhook(ctx, r.owner, r.repo, hook); err != nil {
return pgh.WebhookConfig{}, false, fmt.Errorf("edit webhook: %w", err)
}
return hook, true, nil
}
func (r *githubRepository) deleteWebhook(ctx context.Context) error {
if r.config.Status.Webhook == nil {
return fmt.Errorf("webhook not found")
}
id := r.config.Status.Webhook.ID
if err := r.gh.DeleteWebhook(ctx, r.owner, r.repo, id); err != nil {
return fmt.Errorf("delete webhook: %w", err)
}
logging.FromContext(ctx).Info("webhook deleted", "url", r.config.Status.Webhook.URL, "id", id)
return nil
}
func (r *githubRepository) OnCreate(ctx context.Context) (*provisioning.WebhookStatus, error) {
if len(r.webhookURL) == 0 {
return nil, nil
}
ctx, _ = r.logger(ctx, "")
hook, err := r.createWebhook(ctx)
if err != nil {
return nil, err
}
return &provisioning.WebhookStatus{
ID: hook.ID,
URL: hook.URL,
Secret: hook.Secret,
SubscribedEvents: hook.Events,
}, nil
}
func (r *githubRepository) OnUpdate(ctx context.Context) (*provisioning.WebhookStatus, error) {
if len(r.webhookURL) == 0 {
return nil, nil
}
ctx, _ = r.logger(ctx, "")
hook, _, err := r.updateWebhook(ctx)
if err != nil {
return nil, err
}
return &provisioning.WebhookStatus{
ID: hook.ID,
URL: hook.URL,
Secret: hook.Secret,
SubscribedEvents: hook.Events,
}, nil
}
func (r *githubRepository) OnDelete(ctx context.Context) error {
if len(r.webhookURL) == 0 {
return nil
}
ctx, _ = r.logger(ctx, "")
return r.deleteWebhook(ctx)
}
func (r *githubRepository) logger(ctx context.Context, ref string) (context.Context, logging.Logger) {
logger := logging.FromContext(ctx)
type containsGh int
var containsGhKey containsGh
if ctx.Value(containsGhKey) != nil {
return ctx, logging.FromContext(ctx)
}
if ref == "" {
ref = r.config.Spec.GitHub.Branch
}
logger = logger.With(slog.Group("github_repository", "owner", r.owner, "name", r.repo, "ref", ref))
ctx = logging.Context(ctx, logger)
// We want to ensure we don't add multiple github_repository keys. With doesn't deduplicate the keys...
ctx = context.WithValue(ctx, containsGhKey, true)
return ctx, logger
}