-
Notifications
You must be signed in to change notification settings - Fork 133
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
Add GitHub dispatch provider #369
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -9,7 +9,7 @@ Spec: | |||||
```go | ||||||
type ProviderSpec struct { | ||||||
// Type of provider | ||||||
// +kubebuilder:validation:Enum=slack;discord;msteams;rocket;generic;github;gitlab;bitbucket;azuredevops;googlechat;webex;sentry;azureeventhub;telegram;lark;matrix;opsgenie | ||||||
// +kubebuilder:validation:Enum=slack;discord;msteams;rocket;generic;github;gitlab;bitbucket;azuredevops;googlechat;webex;sentry;azureeventhub;telegram;lark;matrix;opsgenie;githubdispatch | ||||||
// +required | ||||||
Type string `json:"type"` | ||||||
|
||||||
|
@@ -45,23 +45,24 @@ type ProviderSpec struct { | |||||
|
||||||
Notification providers: | ||||||
|
||||||
| Provider | Type | | ||||||
| --------------- | ------------- | | ||||||
| Alertmanager | alertmanager | | ||||||
| Azure Event Hub | azureeventhub | | ||||||
| Discord | discord | | ||||||
| Generic webhook | generic | | ||||||
| Google Chat | googlechat | | ||||||
| Grafana | grafana | | ||||||
| Lark | lark | | ||||||
| Matrix | matrix | | ||||||
| Microsoft Teams | msteams | | ||||||
| Opsgenie | opsgenie | | ||||||
| Rocket | rocket | | ||||||
| Sentry | sentry | | ||||||
| Slack | slack | | ||||||
| Telegram | telegram | | ||||||
| WebEx | webex | | ||||||
| Provider | Type | | ||||||
| --------------- | -------------- | | ||||||
| Alertmanager | alertmanager | | ||||||
| Azure Event Hub | azureeventhub | | ||||||
| Discord | discord | | ||||||
| Generic webhook | generic | | ||||||
| GitHub dispatch | githubdispatch | | ||||||
| Google Chat | googlechat | | ||||||
| Grafana | grafana | | ||||||
| Lark | lark | | ||||||
| Matrix | matrix | | ||||||
| Microsoft Teams | msteams | | ||||||
| Opsgenie | opsgenie | | ||||||
| Rocket | rocket | | ||||||
| Sentry | sentry | | ||||||
| Slack | slack | | ||||||
| Telegram | telegram | | ||||||
| WebEx | webex | | ||||||
|
||||||
Git commit status providers: | ||||||
|
||||||
|
@@ -123,7 +124,8 @@ kubectl create secret generic webhook-url \ | |||||
Note that the secret must contain an `address` field. | ||||||
|
||||||
The provider type can be: `slack`, `msteams`, `rocket`, `discord`, `googlechat`, `webex`, `sentry`, | ||||||
`telegram`, `lark`, `matrix`, `azureeventhub`, `opsgenie`, `alertmanager`, `grafana` or `generic`. | ||||||
`telegram`, `lark`, `matrix`, `azureeventhub`, `opsgenie`, `alertmanager`, `grafana`, | ||||||
`githubdispatch` or `generic`. | ||||||
|
||||||
Some networks need to use an authenticated proxy to access external services. Therefore, the authentication can be stored as a secret to hide parameters like the username and password. | ||||||
|
||||||
|
@@ -730,3 +732,134 @@ kubectl create secret generic webhook-url \ | |||||
--from-literal=address="Endpoint=sb://fluxv2.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yoursaskeygeneatedbyazure" | ||||||
``` | ||||||
|
||||||
### GitHub repository dispatch | ||||||
|
||||||
The `githubdispatch` webhook triggers a GitHub webhook event called [`repository_dispatch`](https://docs.github.com/en/rest/reference/repos#create-a-repository-dispatch-event) for the selected repository. The `repository_dispatch` event can be used to trigger a GitHub Actions workflow with tests for the deployed service. | ||||||
|
||||||
The request includes the `event_type` and `client_payload` fields: | ||||||
|
||||||
* The `event_type` is generated by GitHub Dispatch provider by combining the Kind, Name and Namespace of the involved object in the format `{Kind}/{Name}.{Namespace}`. For example, the `event_type` for Kustomization resource named `podinfo` in the `default` namespace looks like this: `Kustomization/podinfo.default` | ||||||
|
||||||
* The `client_payload` contains the event data from the notification controller and looks like this: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
```yaml | ||||||
{ | ||||||
involvedObject: { | ||||||
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2, | ||||||
kind: Kustomization, | ||||||
name: podinfo, | ||||||
namespace: flux-system, | ||||||
resourceVersion: 426573, | ||||||
uid: b9b8554d-be26-4a3d-a97f-65f3276a097a | ||||||
}, | ||||||
message: Deployment/podinfo/podinfo configured, | ||||||
metadata: { | ||||||
revision: main/96139968ca46b53462d1bf94de410a811d2026a1 | ||||||
}, | ||||||
reason: Progressing, | ||||||
reportingController: kustomize-controller, | ||||||
reportingInstance: kustomize-controller-79464d8dc5-nb9c4, | ||||||
severity: info, | ||||||
timestamp: 2022-04-20T12:20:28Z | ||||||
} | ||||||
``` | ||||||
|
||||||
#### Setting up a GitHub workflow | ||||||
|
||||||
You need to add `repository_dispatch` trigger to trigger your GitHub workflow. You can use a wildcard for `types` value to use only the required information from the `event_type` value in the webhook. For example, you can use only Kustomization name: | ||||||
|
||||||
```yaml | ||||||
name: test-github-dispatch-provider | ||||||
on: | ||||||
repository_dispatch: | ||||||
types: | ||||||
- "*podinfo*" | ||||||
``` | ||||||
|
||||||
Assuming that we deploy all Flux kustomization resources in the same namespace, it will be useful to have a unique kustomization resource name for each application in each environment. This will allow you to use only `event_type` to trigger tests for a exact application in the desired environment. | ||||||
|
||||||
Let's say we have following folder structure for applications kustomization manifests: | ||||||
|
||||||
```bash | ||||||
app1/ | ||||||
overlays/ | ||||||
staging/ | ||||||
production/ | ||||||
app2/ | ||||||
overlays/ | ||||||
staging/ | ||||||
production/ | ||||||
``` | ||||||
|
||||||
You can then create a flux kustomization resource for each overlay to have unique `event_type` looks like this, for example, for app1 and the staging overlay: `Kustomization/app1-staging.default`. | ||||||
|
||||||
The kustomization manifest for app1/staging: | ||||||
|
||||||
```yaml | ||||||
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2 | ||||||
kind: Kustomization | ||||||
metadata: | ||||||
name: app1-staging | ||||||
namespace: default | ||||||
spec: | ||||||
path: "./app1/staging" | ||||||
``` | ||||||
|
||||||
You can the trigger tests for app1 in a staging environment when the app1 resources defined in `./app1/staging/` are configured by Flux: | ||||||
|
||||||
```yaml | ||||||
name: test-github-dispatch-provider | ||||||
on: | ||||||
repository_dispatch: | ||||||
types: | ||||||
- "*app1-staging*" | ||||||
``` | ||||||
|
||||||
If the information from `event_type` is not enough to get the necessary information about the configured resources, you can get more information from `client_payload`. For example, you can get the message from the payload in the workfow job step: | ||||||
stefanprodan marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
```yaml | ||||||
name: test-dispatch-provider | ||||||
on: | ||||||
repository_dispatch: | ||||||
types: | ||||||
- "*app1-staging*" | ||||||
jobs: | ||||||
echo: | ||||||
runs-on: ubuntu-18.04 | ||||||
steps: | ||||||
- name: Get client_payload message | ||||||
run: 'echo "message: ${{ toJson(github.event.client_payload.message) }}"' | ||||||
``` | ||||||
|
||||||
### Setting up the GitHub dispatch provider | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's move this before "Setting up a GitHub workflow" please. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed |
||||||
|
||||||
```yaml | ||||||
apiVersion: notification.toolkit.fluxcd.io/v1beta1 | ||||||
kind: Provider | ||||||
metadata: | ||||||
name: podinfo | ||||||
namespace: default | ||||||
spec: | ||||||
type: githubdispatch | ||||||
address: https://github.com/stefanprodan/podinfo | ||||||
secretRef: | ||||||
name: api-token | ||||||
``` | ||||||
|
||||||
The `address` is the address of your repository where you want to send webhooks to trigger GitHub workflows. | ||||||
|
||||||
GitHub uses personal access tokens for authentication with its API: | ||||||
|
||||||
* [GitHub personal access token](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token) | ||||||
|
||||||
The provider requires a secret in the same format, with the personal access token as the value for the token key: | ||||||
|
||||||
```yaml | ||||||
apiVersion: v1 | ||||||
kind: Secret | ||||||
metadata: | ||||||
name: api-token | ||||||
namespace: default | ||||||
data: | ||||||
token: <personal-access-tokens> | ||||||
``` |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,121 @@ | ||||||
/* | ||||||
Copyright 2020 The Flux authors | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
you may not use this file except in compliance with the License. | ||||||
You may obtain a copy of the License at | ||||||
|
||||||
http://www.apache.org/licenses/LICENSE-2.0 | ||||||
|
||||||
Unless required by applicable law or agreed to in writing, software | ||||||
distributed under the License is distributed on an "AS IS" BASIS, | ||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
See the License for the specific language governing permissions and | ||||||
limitations under the License. | ||||||
*/ | ||||||
|
||||||
package notifier | ||||||
|
||||||
import ( | ||||||
"context" | ||||||
"crypto/tls" | ||||||
"crypto/x509" | ||||||
"encoding/json" | ||||||
"errors" | ||||||
"fmt" | ||||||
"net/http" | ||||||
"net/url" | ||||||
"strings" | ||||||
"time" | ||||||
|
||||||
"github.com/fluxcd/pkg/runtime/events" | ||||||
|
||||||
"github.com/google/go-github/v41/github" | ||||||
"golang.org/x/oauth2" | ||||||
) | ||||||
|
||||||
type GitHubDispatch struct { | ||||||
Owner string | ||||||
Repo string | ||||||
Client *github.Client | ||||||
} | ||||||
|
||||||
func NewGitHubDispatch(addr string, token string, certPool *x509.CertPool) (*GitHubDispatch, error) { | ||||||
if len(token) == 0 { | ||||||
return nil, errors.New("github token cannot be empty") | ||||||
} | ||||||
|
||||||
host, id, err := parseGitAddress(addr) | ||||||
if err != nil { | ||||||
return nil, err | ||||||
} | ||||||
|
||||||
baseUrl, err := url.Parse(host) | ||||||
if err != nil { | ||||||
return nil, err | ||||||
} | ||||||
|
||||||
comp := strings.Split(id, "/") | ||||||
if len(comp) != 2 { | ||||||
return nil, fmt.Errorf("invalid repository id %q", id) | ||||||
} | ||||||
|
||||||
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) | ||||||
tc := oauth2.NewClient(context.Background(), ts) | ||||||
client := github.NewClient(tc) | ||||||
if baseUrl.Host != "github.com" { | ||||||
if certPool != nil { | ||||||
tr := &http.Transport{ | ||||||
TLSClientConfig: &tls.Config{ | ||||||
RootCAs: certPool, | ||||||
}, | ||||||
} | ||||||
hc := &http.Client{Transport: tr} | ||||||
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, hc) | ||||||
tc = oauth2.NewClient(ctx, ts) | ||||||
} | ||||||
|
||||||
client, err = github.NewEnterpriseClient(host, host, tc) | ||||||
if err != nil { | ||||||
return nil, fmt.Errorf("could not create enterprise GitHub client: %v", err) | ||||||
} | ||||||
} | ||||||
|
||||||
return &GitHubDispatch{ | ||||||
Owner: comp[0], | ||||||
Repo: comp[1], | ||||||
Client: client, | ||||||
}, nil | ||||||
} | ||||||
|
||||||
// Post GitHub Repository Dispatch webhook | ||||||
func (g *GitHubDispatch) Post(event events.Event) error { | ||||||
// Skip any update events | ||||||
if isCommitStatus(event.Metadata, "update") { | ||||||
return nil | ||||||
} | ||||||
|
||||||
eventType := fmt.Sprintf("%s/%s.%s", | ||||||
event.InvolvedObject.Kind, event.InvolvedObject.Name, event.InvolvedObject.Namespace) | ||||||
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) | ||||||
defer cancel() | ||||||
|
||||||
eventData, err := json.Marshal(event) | ||||||
if err != nil { | ||||||
return fmt.Errorf("Failed to marshal object into json: %w", err) | ||||||
} | ||||||
eventDataRaw := json.RawMessage(eventData) | ||||||
|
||||||
opts := github.DispatchRequestOptions{ | ||||||
EventType: eventType, | ||||||
ClientPayload: &eventDataRaw, | ||||||
} | ||||||
_, _, err = g.Client.Repositories.Dispatch(ctx, g.Owner, g.Repo, opts) | ||||||
|
||||||
if err != nil { | ||||||
return fmt.Errorf("Could not send github repository dispatch webhook: %v", err) | ||||||
} | ||||||
|
||||||
return nil | ||||||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.