Skip to content
Commits on Source (31)
......@@ -16,14 +16,15 @@ jobs:
strategy:
matrix:
# Keep this list up-to-date with https://endoflife.date/kubernetes
KUBERNETES_VERSION: [ 1.23.13, 1.24.7, 1.25.3 ]
# Check which versions are available on DockerHub with 'crane ls kindest/node'
KUBERNETES_VERSION: [ 1.24.7, 1.25.3, 1.26.0 ]
steps:
- name: Checkout
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Prepare
id: prep
run: |
......
......@@ -15,18 +15,18 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Checkout
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Restore Go cache
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0 # v3.2.6
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go1.18-${{ hashFiles('**/go.sum') }}
key: ${{ runner.os }}-go1.20-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go1.18-
${{ runner.os }}-go1.20-
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Setup Flux CLI
run: |
make build
......
......@@ -16,26 +16,29 @@ jobs:
if: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && github.actor != 'dependabot[bot]'
steps:
- name: Checkout
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Restore Go cache
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0 # v3.2.6
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go1.18-${{ hashFiles('**/go.sum') }}
key: ${{ runner.os }}-go1.20-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go1.18-
${{ runner.os }}-go1.20-
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Setup Kubernetes
uses: helm/kind-action@d8ccf8fb623ce1bb360ae2f45f323d9d5c5e9f00 # v1.5.0
with:
version: v0.17.0
cluster_name: kind
node_image: kindest/node:v1.25.2
# The versions below should target the newest Kubernetes version
# Keep this up-to-date with https://endoflife.date/kubernetes
node_image: kindest/node:v1.26.0
kubectl_version: v1.26.2
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
uses: fluxcd/pkg/actions/kustomize@main
- name: Build
run: |
make cmd/flux/.manifests.done
......
......@@ -20,31 +20,34 @@ jobs:
- 5000:5000
steps:
- name: Checkout
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Restore Go cache
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0
uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0 # v3.2.6
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go1.18-${{ hashFiles('**/go.sum') }}
key: ${{ runner.os }}-go1.20-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go1.18-
${{ runner.os }}-go1.20-
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Setup Kubernetes
uses: helm/kind-action@d8ccf8fb623ce1bb360ae2f45f323d9d5c5e9f00 # v1.5.0
with:
version: v0.17.0
cluster_name: kind
config: .github/kind/config.yaml # disable KIND-net
node_image: kindest/node:v1.23.13
# The versions below should target the newest Kubernetes version
# Keep this up-to-date with https://endoflife.date/kubernetes
node_image: kindest/node:v1.26.0
kubectl_version: v1.26.2
- name: Setup Calico for network policy
run: |
kubectl apply -f https://docs.projectcalico.org/v3.20/manifests/calico.yaml
kubectl apply -f https://docs.projectcalico.org/v3.25/manifests/calico.yaml
kubectl -n kube-system set env daemonset/calico-node FELIX_IGNORELOOSERPF=true
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
uses: fluxcd/pkg/actions/kustomize@main
- name: Run tests
run: make test
- name: Run e2e tests
......@@ -78,12 +81,12 @@ jobs:
run: |
/tmp/flux create source git podinfo \
--url https://github.com/stefanprodan/podinfo \
--tag-semver=">=3.2.3"
--tag-semver=">=6.3.5"
- name: flux create source git export apply
run: |
/tmp/flux create source git podinfo-export \
--url https://github.com/stefanprodan/podinfo \
--tag-semver=">=3.2.3" \
--tag-semver=">=6.3.5" \
--export | kubectl apply -f -
/tmp/flux delete source git podinfo-export --silent
- name: flux get sources git
......@@ -140,7 +143,7 @@ jobs:
--target-namespace=default \
--source=HelmRepository/podinfo.flux-system \
--chart=podinfo \
--chart-version=">4.0.0 <5.0.0"
--chart-version=">6.0.0 <7.0.0"
- name: flux create helmrelease --source=GitRepository/podinfo
run: |
/tmp/flux create hr podinfo-git \
......@@ -184,11 +187,11 @@ jobs:
run: |
/tmp/flux create source oci podinfo-oci \
--url oci://ghcr.io/stefanprodan/manifests/podinfo \
--tag-semver 6.1.x \
--tag-semver 6.3.x \
--interval 10m
/tmp/flux create kustomization podinfo-oci \
--source=OCIRepository/podinfo-oci \
--path="./kustomize" \
--path="./" \
--prune=true \
--interval=5m \
--target-namespace=default \
......@@ -209,7 +212,7 @@ jobs:
/tmp/flux -n apps create hr podinfo-helm \
--source=HelmRepository/podinfo \
--chart=podinfo \
--chart-version="5.0.x" \
--chart-version="6.3.x" \
--service-account=dev-team
- name: flux2-kustomize-helm-example
run: |
......
......@@ -16,32 +16,32 @@ jobs:
packages: write # needed for ghcr access
steps:
- name: Checkout
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Unshallow
run: git fetch --prune --unshallow
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Setup QEMU
uses: docker/setup-qemu-action@e81a89b1732b9c48d79cd809d8d81d79c4647a18 # v2
uses: docker/setup-qemu-action@e81a89b1732b9c48d79cd809d8d81d79c4647a18 # v2.1.0
- name: Setup Docker Buildx
id: buildx
uses: docker/setup-buildx-action@f03ac48505955848960e80bbb68046aa35c7b9e7 # v2
uses: docker/setup-buildx-action@f03ac48505955848960e80bbb68046aa35c7b9e7 # v2.4.1
- name: Setup Syft
uses: anchore/sbom-action/download-syft@07978da4bdb4faa726e52dfc6b1bed63d4b56479 # v0.13.3
- name: Setup Cosign
uses: sigstore/cosign-installer@9becc617647dfa20ae7b1151972e9b3a2c338a2b # v2.8.1
uses: sigstore/cosign-installer@c3667d99424e7e6047999fb6246c0da843953c65 # v3.0.1
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
uses: fluxcd/pkg/actions/kustomize@main
- name: Login to GitHub Container Registry
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2.1.0
with:
registry: ghcr.io
username: fluxcdbot
password: ${{ secrets.GHCR_TOKEN }}
- name: Login to Docker Hub
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2.1.0
with:
username: fluxcdbot
password: ${{ secrets.DOCKER_FLUXCD_PASSWORD }}
......@@ -54,7 +54,7 @@ jobs:
run: |
kustomize build manifests/crds > all-crds.yaml
- name: Generate OpenAPI JSON schemas from CRDs
uses: fluxcd/pkg//actions/crdjsonschema@main
uses: fluxcd/pkg/actions/crdjsonschema@main
with:
crd: all-crds.yaml
output: schemas
......@@ -73,7 +73,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@f82d6c1c344bcacabba2c841718984797f664a6b # v3
uses: goreleaser/goreleaser-action@f82d6c1c344bcacabba2c841718984797f664a6b # v4.2.0
with:
version: latest
args: release --release-notes=output/notes.md --skip-validate
......@@ -88,7 +88,7 @@ jobs:
id-token: write
packages: write
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Setup Kustomize
uses: fluxcd/pkg/actions/kustomize@main
- name: Setup Flux CLI
......@@ -99,13 +99,13 @@ jobs:
VERSION=$(flux version --client | awk '{ print $NF }')
echo "version=${VERSION}" >> $GITHUB_OUTPUT
- name: Login to GHCR
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2.1.0
with:
registry: ghcr.io
username: fluxcdbot
password: ${{ secrets.GHCR_TOKEN }}
- name: Login to DockerHub
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2.1.0
with:
username: fluxcdbot
password: ${{ secrets.DOCKER_FLUXCD_PASSWORD }}
......@@ -133,13 +133,13 @@ jobs:
--path="./flux-system" \
--source=${{ github.repositoryUrl }} \
--revision="${{ github.ref_name }}@sha1:${{ github.sha }}"
- uses: sigstore/cosign-installer@9becc617647dfa20ae7b1151972e9b3a2c338a2b # v2.8.1
- uses: sigstore/cosign-installer@c3667d99424e7e6047999fb6246c0da843953c65 # v3.0.1
- name: Sign manifests
env:
COSIGN_EXPERIMENTAL: 1
run: |
cosign sign ghcr.io/fluxcd/flux-manifests:${{ steps.prep.outputs.version }}
cosign sign docker.io/fluxcd/flux-manifests:${{ steps.prep.outputs.version }}
cosign sign --yes ghcr.io/fluxcd/flux-manifests:${{ steps.prep.outputs.version }}
cosign sign --yes docker.io/fluxcd/flux-manifests:${{ steps.prep.outputs.version }}
- name: Tag manifests
run: |
flux tag artifact oci://ghcr.io/fluxcd/flux-manifests:${{ steps.prep.outputs.version }} \
......
......@@ -17,9 +17,9 @@ jobs:
runs-on: ubuntu-latest
if: github.actor != 'dependabot[bot]'
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Run FOSSA scan and upload build data
uses: fossa-contrib/fossa-action@6728dc6fe9a068c648d080c33829ffbe56565023 # v1
uses: fossa-contrib/fossa-action@6728dc6fe9a068c648d080c33829ffbe56565023 # v2.0.0
with:
# FOSSA Push-Only API Token
fossa-api-key: 5ee8bf422db1471e0bcf2bcb289185de
......@@ -31,13 +31,13 @@ jobs:
security-events: write
if: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && github.actor != 'dependabot[bot]'
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
uses: fluxcd/pkg/actions/kustomize@main
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Download modules and build manifests
run: |
make tidy
......@@ -50,7 +50,7 @@ jobs:
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
- name: Upload result to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
uses: github/codeql-action/upload-sarif@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2.2.5
with:
sarif_file: snyk.sarif
......@@ -61,16 +61,16 @@ jobs:
if: github.actor != 'dependabot[bot]'
steps:
- name: Checkout repository
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Set up Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Initialize CodeQL
uses: github/codeql-action/init@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
uses: github/codeql-action/init@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2.2.5
with:
languages: go
- name: Autobuild
uses: github/codeql-action/autobuild@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
uses: github/codeql-action/autobuild@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2.2.5
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
uses: github/codeql-action/analyze@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2.2.5
......@@ -18,11 +18,11 @@ jobs:
pull-requests: write
steps:
- name: Check out code
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- name: Setup Go
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568
uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0
with:
go-version: 1.19.x
go-version: 1.20.x
- name: Update component versions
id: update
run: |
......@@ -81,7 +81,7 @@ jobs:
- name: Create Pull Request
id: cpr
uses: peter-evans/create-pull-request@2b011faafdcbc9ceb11414d64d0573f37c774b04 # v4
uses: peter-evans/create-pull-request@2b011faafdcbc9ceb11414d64d0573f37c774b04 # v4.2.3
with:
token: ${{ secrets.BOT_GITHUB_TOKEN }}
commit-message: |
......
......@@ -65,6 +65,7 @@ signs:
certificate: '${artifact}.pem'
args:
- sign-blob
- "--yes"
- '--output-certificate=${certificate}'
- '--output-signature=${signature}'
- '${artifact}'
......@@ -175,6 +176,7 @@ docker_signs:
- COSIGN_EXPERIMENTAL=1
args:
- sign
- "--yes"
- '${artifact}'
artifacts: all
output: true
......@@ -67,7 +67,7 @@ for source changes.
Prerequisites:
* go >= 1.19
* go >= 1.20
* kubectl >= 1.20
* kustomize >= 4.4
* coreutils (on Mac OS)
......
......@@ -3,7 +3,7 @@ FROM alpine:3.17 as builder
RUN apk add --no-cache ca-certificates curl
ARG ARCH=linux/amd64
ARG KUBECTL_VER=1.26.1
ARG KUBECTL_VER=1.26.2
RUN curl -sL https://storage.googleapis.com/kubernetes-release/release/v${KUBECTL_VER}/bin/${ARCH}/kubectl \
-o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl && \
......
......@@ -17,8 +17,8 @@ rwildcard=$(foreach d,$(wildcard $(addsuffix *,$(1))),$(call rwildcard,$(d)/,$(2
all: test build
tidy:
go mod tidy -compat=1.19
cd tests/azure && go mod tidy -compat=1.19
go mod tidy -compat=1.20
cd tests/azure && go mod tidy -compat=1.20
fmt:
go fmt ./...
......
......@@ -200,7 +200,7 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
}
if helmReleaseArgs.kubeConfigSecretRef != "" {
helmRelease.Spec.KubeConfig = &helmv2.KubeConfig{
helmRelease.Spec.KubeConfig = &meta.KubeConfigReference{
SecretRef: meta.SecretKeyReference{
Name: helmReleaseArgs.kubeConfigSecretRef,
},
......
......@@ -38,12 +38,12 @@ func TestCreateSourceOCI(t *testing.T) {
},
{
name: "export manifest",
args: "create source oci podinfo --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.1.6 --interval 10m --export",
args: "create source oci podinfo --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.3.5 --interval 10m --export",
assertFunc: assertGoldenFile("./testdata/oci/export.golden"),
},
{
name: "export manifest with secret",
args: "create source oci podinfo --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.1.6 --interval 10m --secret-ref=creds --export",
args: "create source oci podinfo --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.3.5 --interval 10m --secret-ref=creds --export",
assertFunc: assertGoldenFile("./testdata/oci/export_with_secret.golden"),
},
}
......
/*
Copyright 2023 The Kubernetes Authors.
Copyright 2023 The Flux authors
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 main
import (
"context"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/duration"
"k8s.io/apimachinery/pkg/watch"
runtimeresource "k8s.io/cli-runtime/pkg/resource"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"sigs.k8s.io/controller-runtime/pkg/client"
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta2"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta2"
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta2"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta2"
"github.com/fluxcd/flux2/internal/utils"
"github.com/fluxcd/flux2/pkg/printers"
)
var eventsCmd = &cobra.Command{
Use: "events",
Short: "Display Kubernetes events for Flux resources",
Long: "The events sub-command shows Kubernetes events from Flux resources",
Example: ` # Display events for flux resources in default namespace
flux events -n default
# Display events for flux resources in all namespaces
flux events -A
# Display events for flux resources
flux events --for Kustomization/podinfo
`,
RunE: eventsCmdRun,
}
type eventFlags struct {
allNamespaces bool
watch bool
forSelector string
filterTypes []string
}
var eventArgs eventFlags
func init() {
eventsCmd.Flags().BoolVarP(&eventArgs.allNamespaces, "all-namespaces", "A", false,
"display events from Flux resources across all namespaces")
eventsCmd.Flags().BoolVarP(&eventArgs.watch, "watch", "w", false,
"indicate if the events should be streamed")
eventsCmd.Flags().StringVar(&eventArgs.forSelector, "for", "",
"get events for a particular object")
eventsCmd.Flags().StringSliceVar(&eventArgs.filterTypes, "types", []string{}, "filter events for certain types")
rootCmd.AddCommand(eventsCmd)
}
func eventsCmdRun(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()
kubeclient, err := utils.KubeClient(kubeconfigArgs, kubeclientOptions)
if err != nil {
return err
}
namespace := *kubeconfigArgs.Namespace
if eventArgs.allNamespaces {
namespace = ""
}
var diffRefNs bool
clientListOpts := getListOpt(namespace, eventArgs.forSelector)
var refListOpts [][]client.ListOption
if eventArgs.forSelector != "" {
refs, err := getObjectRef(ctx, kubeclient, eventArgs.forSelector, *kubeconfigArgs.Namespace)
if err != nil {
return err
}
for _, ref := range refs {
kind, name, refNs := utils.ParseObjectKindNameNamespace(ref)
if refNs != namespace {
diffRefNs = true
}
refSelector := fmt.Sprintf("%s/%s", kind, name)
refListOpts = append(refListOpts, getListOpt(refNs, refSelector))
}
}
showNamespace := namespace == "" || diffRefNs
if eventArgs.watch {
return eventsCmdWatchRun(ctx, kubeclient, clientListOpts, refListOpts, showNamespace)
}
rows, err := getRows(ctx, kubeclient, clientListOpts, refListOpts, showNamespace)
if len(rows) == 0 {
if eventArgs.allNamespaces {
logger.Failuref("No events found.")
} else {
logger.Failuref("No events found in %s namespace.", *kubeconfigArgs.Namespace)
}
return nil
}
headers := getHeaders(showNamespace)
err = printers.TablePrinter(headers).Print(cmd.OutOrStdout(), rows)
return err
}
func getRows(ctx context.Context, kubeclient client.Client, clientListOpts []client.ListOption, refListOpts [][]client.ListOption, showNs bool) ([][]string, error) {
el := &corev1.EventList{}
if err := addEventsToList(ctx, kubeclient, el, clientListOpts); err != nil {
return nil, err
}
for _, refOpts := range refListOpts {
if err := addEventsToList(ctx, kubeclient, el, refOpts); err != nil {
return nil, err
}
}
sort.Sort(SortableEvents(el.Items))
var rows [][]string
for _, item := range el.Items {
if ignoreEvent(item) {
continue
}
rows = append(rows, getEventRow(item, showNs))
}
return rows, nil
}
func addEventsToList(ctx context.Context, kubeclient client.Client, el *corev1.EventList, clientListOpts []client.ListOption) error {
listOpts := &metav1.ListOptions{}
err := runtimeresource.FollowContinue(listOpts,
func(options metav1.ListOptions) (runtime.Object, error) {
newEvents := &corev1.EventList{}
err := kubeclient.List(ctx, newEvents, clientListOpts...)
if err != nil {
return nil, fmt.Errorf("error getting events: %w", err)
}
el.Items = append(el.Items, newEvents.Items...)
return newEvents, nil
})
return err
}
func getListOpt(namespace, selector string) []client.ListOption {
clientListOpts := []client.ListOption{client.Limit(cmdutil.DefaultChunkSize), client.InNamespace(namespace)}
if selector != "" {
kind, name := utils.ParseObjectKindName(selector)
sel := fields.AndSelectors(
fields.OneTermEqualSelector("involvedObject.kind", kind),
fields.OneTermEqualSelector("involvedObject.name", name))
clientListOpts = append(clientListOpts, client.MatchingFieldsSelector{Selector: sel})
}
return clientListOpts
}
func eventsCmdWatchRun(ctx context.Context, kubeclient client.WithWatch, listOpts []client.ListOption, refListOpts [][]client.ListOption, showNs bool) error {
event := &corev1.EventList{}
eventWatch, err := kubeclient.Watch(ctx, event, listOpts...)
if err != nil {
return err
}
firstIteration := true
handleEvent := func(e watch.Event) error {
if e.Type == watch.Deleted {
return nil
}
event, ok := e.Object.(*corev1.Event)
if !ok {
return nil
}
if ignoreEvent(*event) {
return nil
}
rows := getEventRow(*event, showNs)
var hdr []string
if firstIteration {
hdr = getHeaders(showNs)
firstIteration = false
}
err = printers.TablePrinter(hdr).Print(os.Stdout, [][]string{rows})
if err != nil {
return err
}
return nil
}
for _, refOpts := range refListOpts {
refEventWatch, err := kubeclient.Watch(ctx, event, refOpts...)
if err != nil {
return err
}
go func() {
err := receiveEventChan(ctx, refEventWatch, handleEvent)
if err != nil {
logger.Failuref("error watching events: %s", err.Error())
}
}()
}
return receiveEventChan(ctx, eventWatch, handleEvent)
}
func receiveEventChan(ctx context.Context, eventWatch watch.Interface, f func(e watch.Event) error) error {
defer eventWatch.Stop()
for {
select {
case e, ok := <-eventWatch.ResultChan():
if !ok {
return nil
}
err := f(e)
if err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
func getHeaders(showNs bool) []string {
headers := []string{"Last seen", "Type", "Reason", "Object", "Message"}
if showNs {
headers = append(namespaceHeader, headers...)
}
return headers
}
func getEventRow(e corev1.Event, showNs bool) []string {
var row []string
if showNs {
row = []string{e.Namespace}
}
row = append(row, getLastSeen(e), e.Type, e.Reason, fmt.Sprintf("%s/%s", e.InvolvedObject.Kind, e.InvolvedObject.Name), e.Message)
return row
}
// getObjectRef is used to get the metadata of a resource that the selector(in the format <kind/name>) references.
// It returns an empty string if the resource doesn't reference any resource
// and a string with the format `<kind>/<name>.<namespace>` if it does.
func getObjectRef(ctx context.Context, kubeclient client.Client, selector string, ns string) ([]string, error) {
kind, name := utils.ParseObjectKindName(selector)
ref, err := fluxKindMap.getRefInfo(kind)
if err != nil {
return nil, fmt.Errorf("error getting groupversion: %w", err)
}
// the resource has no source ref
if len(ref.field) == 0 {
return nil, nil
}
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(schema.GroupVersionKind{
Kind: kind,
Version: ref.gv.Version,
Group: ref.gv.Group,
})
objName := types.NamespacedName{
Namespace: ns,
Name: name,
}
err = kubeclient.Get(ctx, objName, obj)
if err != nil {
return nil, err
}
var ok bool
refKind := ref.kind
if refKind == "" {
kindField := append(ref.field, "kind")
refKind, ok, err = unstructured.NestedString(obj.Object, kindField...)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("field '%s' for '%s' not found", strings.Join(kindField, "."), objName)
}
}
nameField := append(ref.field, "name")
refName, ok, err := unstructured.NestedString(obj.Object, nameField...)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("field '%s' for '%s' not found", strings.Join(nameField, "."), objName)
}
var allRefs []string
refNamespace := ns
if ref.crossNamespaced {
namespaceField := append(ref.field, "namespace")
namespace, ok, err := unstructured.NestedString(obj.Object, namespaceField...)
if err != nil {
return nil, err
}
if ok {
refNamespace = namespace
}
}
allRefs = append(allRefs, fmt.Sprintf("%s/%s.%s", refKind, refName, refNamespace))
if ref.otherRefs != nil {
for _, otherRef := range ref.otherRefs(ns, name) {
allRefs = append(allRefs, fmt.Sprintf("%s.%s", otherRef, refNamespace))
}
}
return allRefs, nil
}
type refMap map[string]refInfo
func (r refMap) getRefInfo(kind string) (refInfo, error) {
for key, ref := range r {
if strings.EqualFold(key, kind) {
return ref, nil
}
}
return refInfo{}, fmt.Errorf("'%s' is not a recognized Flux kind", kind)
}
func (r refMap) hasKind(kind string) bool {
_, err := r.getRefInfo(kind)
return err == nil
}
type refInfo struct {
gv schema.GroupVersion
kind string
crossNamespaced bool
otherRefs func(namespace, name string) []string
field []string
}
var fluxKindMap = refMap{
kustomizev1.KustomizationKind: {
gv: kustomizev1.GroupVersion,
crossNamespaced: true,
field: []string{"spec", "sourceRef"},
},
helmv2.HelmReleaseKind: {
gv: helmv2.GroupVersion,
crossNamespaced: true,
otherRefs: func(namespace, name string) []string {
return []string{fmt.Sprintf("%s/%s-%s", sourcev1.HelmChartKind, namespace, name)}
},
field: []string{"spec", "chart", "spec", "sourceRef"},
},
notificationv1.AlertKind: {
gv: notificationv1.GroupVersion,
kind: notificationv1.ProviderKind,
crossNamespaced: false,
field: []string{"spec", "providerRef"},
},
notificationv1.ReceiverKind: {gv: notificationv1.GroupVersion},
notificationv1.ProviderKind: {gv: notificationv1.GroupVersion},
imagev1.ImagePolicyKind: {
gv: imagev1.GroupVersion,
kind: imagev1.ImageRepositoryKind,
crossNamespaced: true,
field: []string{"spec", "imageRepositoryRef"},
},
sourcev1.GitRepositoryKind: {gv: sourcev1.GroupVersion},
sourcev1.OCIRepositoryKind: {gv: sourcev1.GroupVersion},
sourcev1.BucketKind: {gv: sourcev1.GroupVersion},
sourcev1.HelmRepositoryKind: {gv: sourcev1.GroupVersion},
sourcev1.HelmChartKind: {gv: sourcev1.GroupVersion},
autov1.ImageUpdateAutomationKind: {gv: autov1.GroupVersion},
imagev1.ImageRepositoryKind: {gv: imagev1.GroupVersion},
}
func ignoreEvent(e corev1.Event) bool {
if !fluxKindMap.hasKind(e.InvolvedObject.Kind) {
return true
}
if len(eventArgs.filterTypes) > 0 {
_, equal := utils.ContainsEqualFoldItemString(eventArgs.filterTypes, e.Type)
if !equal {
return true
}
}
return false
}
// The functions below are copied from: https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/events/events.go#L347
// SortableEvents implements sort.Interface for []api.Event by time
type SortableEvents []corev1.Event
func (list SortableEvents) Len() int {
return len(list)
}
func (list SortableEvents) Swap(i, j int) {
list[i], list[j] = list[j], list[i]
}
// Return the time that should be used for sorting, which can come from
// various places in corev1.Event.
func eventTime(event corev1.Event) time.Time {
if event.Series != nil {
return event.Series.LastObservedTime.Time
}
if !event.LastTimestamp.Time.IsZero() {
return event.LastTimestamp.Time
}
return event.EventTime.Time
}
func (list SortableEvents) Less(i, j int) bool {
return eventTime(list[i]).Before(eventTime(list[j]))
}
func getLastSeen(e corev1.Event) string {
var interval string
firstTimestampSince := translateMicroTimestampSince(e.EventTime)
if e.EventTime.IsZero() {
firstTimestampSince = translateTimestampSince(e.FirstTimestamp)
}
if e.Series != nil {
interval = fmt.Sprintf("%s (x%d over %s)", translateMicroTimestampSince(e.Series.LastObservedTime), e.Series.Count, firstTimestampSince)
} else if e.Count > 1 {
interval = fmt.Sprintf("%s (x%d over %s)", translateTimestampSince(e.LastTimestamp), e.Count, firstTimestampSince)
} else {
interval = firstTimestampSince
}
return interval
}
// translateMicroTimestampSince returns the elapsed time since timestamp in
// human-readable approximation.
func translateMicroTimestampSince(timestamp metav1.MicroTime) string {
if timestamp.IsZero() {
return "<unknown>"
}
return duration.HumanDuration(time.Since(timestamp.Time))
}
// translateTimestampSince returns the elapsed time since timestamp in
// human-readable approximation.
func translateTimestampSince(timestamp metav1.Time) string {
if timestamp.IsZero() {
return "<unknown>"
}
return duration.HumanDuration(time.Since(timestamp.Time))
}
/*
Copyright 2023 The Kubernetes Authors.
Copyright 2023 The Flux authors
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 main
import (
"context"
"fmt"
"strings"
"testing"
"github.com/fluxcd/flux2/internal/utils"
helmv2beta1 "github.com/fluxcd/helm-controller/api/v2beta1"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta2"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta2"
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta2"
eventv1 "github.com/fluxcd/pkg/apis/event/v1beta1"
"github.com/fluxcd/pkg/ssa"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta2"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
var objects = `
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: flux-system
namespace: flux-system
spec:
interval: 5m0s
path: ./infrastructure/
prune: true
sourceRef:
kind: GitRepository
name: flux-system
---
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
name: podinfo
namespace: default
spec:
interval: 5m0s
path: ./infrastructure/
prune: true
sourceRef:
kind: GitRepository
name: flux-system
namespace: flux-system
---
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: GitRepository
metadata:
name: flux-system
namespace: flux-system
spec:
interval: 5m0s
ref:
branch: main
secretRef:
name: flux-system
timeout: 1m0s
url: ssh://git@github.com/example/repo
---
apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
name: podinfo
namespace: default
spec:
chart:
spec:
chart: podinfo
reconcileStrategy: ChartVersion
sourceRef:
kind: HelmRepository
name: podinfo
namespace: flux-system
version: '*'
interval: 5m0s
---
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
name: podinfo
namespace: flux-system
spec:
interval: 1m0s
url: https://stefanprodan.github.io/podinfo
---
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmChart
metadata:
name: default-podinfo
namespace: flux-system
spec:
chart: podinfo
interval: 1m0s
reconcileStrategy: ChartVersion
sourceRef:
kind: HelmRepository
name: podinfo-chart
version: '*'
---
apiVersion: notification.toolkit.fluxcd.io/v1beta2
kind: Alert
metadata:
name: webapp
namespace: flux-system
spec:
eventSeverity: info
eventSources:
- kind: GitRepository
name: '*'
providerRef:
name: slack
---
apiVersion: notification.toolkit.fluxcd.io/v1beta2
kind: Provider
metadata:
name: slack
namespace: flux-system
spec:
address: https://hooks.slack.com/services/mock
type: slack
---
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
name: podinfo
namespace: default
spec:
imageRepositoryRef:
name: acr-podinfo
namespace: flux-system
policy:
semver:
range: 5.0.x
---
apiVersion: v1
kind: Namespace
metadata:
name: flux-system`
func Test_getObjectRef(t *testing.T) {
g := NewWithT(t)
objs, err := ssa.ReadObjects(strings.NewReader(objects))
g.Expect(err).To(Not(HaveOccurred()))
builder := fake.NewClientBuilder().WithScheme(getScheme())
for _, obj := range objs {
builder = builder.WithObjects(obj)
}
c := builder.Build()
tests := []struct {
name string
selector string
namespace string
want []string
wantErr bool
}{
{
name: "Source Ref for Kustomization",
selector: "Kustomization/flux-system",
namespace: "flux-system",
want: []string{"GitRepository/flux-system.flux-system"},
},
{
name: "Crossnamespace Source Ref for Kustomization",
selector: "Kustomization/podinfo",
namespace: "default",
want: []string{"GitRepository/flux-system.flux-system"},
},
{
name: "Source Ref for HelmRelease",
selector: "HelmRelease/podinfo",
namespace: "default",
want: []string{"HelmRepository/podinfo.flux-system", "HelmChart/default-podinfo.flux-system"},
},
{
name: "Source Ref for Alert",
selector: "Alert/webapp",
namespace: "flux-system",
want: []string{"Provider/slack.flux-system"},
},
{
name: "Source Ref for ImagePolicy",
selector: "ImagePolicy/podinfo",
namespace: "default",
want: []string{"ImageRepository/acr-podinfo.flux-system"},
},
{
name: "Empty Ref for Provider",
selector: "Provider/slack",
namespace: "flux-system",
want: nil,
},
{
name: "Non flux resource",
selector: "Namespace/flux-system",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
got, err := getObjectRef(context.Background(), c, tt.selector, tt.namespace)
if tt.wantErr {
g.Expect(err).To(HaveOccurred())
return
}
g.Expect(err).To(Not(HaveOccurred()))
g.Expect(got).To(Equal(tt.want))
})
}
}
func Test_getRows(t *testing.T) {
g := NewWithT(t)
objs, err := ssa.ReadObjects(strings.NewReader(objects))
g.Expect(err).To(Not(HaveOccurred()))
builder := fake.NewClientBuilder().WithScheme(getScheme())
for _, obj := range objs {
builder = builder.WithObjects(obj)
}
eventList := &corev1.EventList{}
for _, obj := range objs {
infoEvent := createEvent(obj, eventv1.EventSeverityInfo, "Info Message", "Info Reason")
warningEvent := createEvent(obj, eventv1.EventSeverityError, "Error Message", "Error Reason")
eventList.Items = append(eventList.Items, infoEvent, warningEvent)
}
builder = builder.WithLists(eventList)
builder.WithIndex(&corev1.Event{}, "involvedObject.kind/name", kindNameIndexer)
c := builder.Build()
tests := []struct {
name string
selector string
refSelector string
namespace string
refNs string
expected [][]string
}{
{
name: "events from all namespaces",
selector: "",
namespace: "",
expected: [][]string{
{"default", "<unknown>", "error", "Error Reason", "HelmRelease/podinfo", "Error Message"},
{"default", "<unknown>", "info", "Info Reason", "HelmRelease/podinfo", "Info Message"},
{"default", "<unknown>", "error", "Error Reason", "ImagePolicy/podinfo", "Error Message"},
{"default", "<unknown>", "info", "Info Reason", "ImagePolicy/podinfo", "Info Message"},
{"default", "<unknown>", "error", "Error Reason", "Kustomization/podinfo", "Error Message"},
{"default", "<unknown>", "info", "Info Reason", "Kustomization/podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "Alert/webapp", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "Alert/webapp", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "GitRepository/flux-system", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "GitRepository/flux-system", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "HelmChart/default-podinfo", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "HelmChart/default-podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "HelmRepository/podinfo", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "HelmRepository/podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "Kustomization/flux-system", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "Kustomization/flux-system", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "Provider/slack", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "Provider/slack", "Info Message"},
},
},
{
name: "events from default namespaces",
selector: "",
namespace: "default",
expected: [][]string{
{"<unknown>", "error", "Error Reason", "HelmRelease/podinfo", "Error Message"},
{"<unknown>", "info", "Info Reason", "HelmRelease/podinfo", "Info Message"},
{"<unknown>", "error", "Error Reason", "ImagePolicy/podinfo", "Error Message"},
{"<unknown>", "info", "Info Reason", "ImagePolicy/podinfo", "Info Message"},
{"<unknown>", "error", "Error Reason", "Kustomization/podinfo", "Error Message"},
{"<unknown>", "info", "Info Reason", "Kustomization/podinfo", "Info Message"},
},
},
{
name: "Kustomization with crossnamespaced GitRepository",
selector: "Kustomization/podinfo",
namespace: "default",
expected: [][]string{
{"default", "<unknown>", "error", "Error Reason", "Kustomization/podinfo", "Error Message"},
{"default", "<unknown>", "info", "Info Reason", "Kustomization/podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "GitRepository/flux-system", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "GitRepository/flux-system", "Info Message"},
},
},
{
name: "HelmRelease with crossnamespaced HelmRepository",
selector: "HelmRelease/podinfo",
namespace: "default",
expected: [][]string{
{"default", "<unknown>", "error", "Error Reason", "HelmRelease/podinfo", "Error Message"},
{"default", "<unknown>", "info", "Info Reason", "HelmRelease/podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "HelmRepository/podinfo", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "HelmRepository/podinfo", "Info Message"},
{"flux-system", "<unknown>", "error", "Error Reason", "HelmChart/default-podinfo", "Error Message"},
{"flux-system", "<unknown>", "info", "Info Reason", "HelmChart/default-podinfo", "Info Message"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
var refs []string
var refNs, refKind, refName string
if tt.selector != "" {
refs, err = getObjectRef(context.Background(), c, tt.selector, tt.namespace)
g.Expect(err).To(Not(HaveOccurred()))
}
g.Expect(err).To(Not(HaveOccurred()))
clientOpts := getTestListOpt(tt.namespace, tt.selector)
var refOpts [][]client.ListOption
for _, ref := range refs {
refKind, refName, refNs = utils.ParseObjectKindNameNamespace(ref)
refSelector := fmt.Sprintf("%s/%s", refKind, refName)
refOpts = append(refOpts, getTestListOpt(refNs, refSelector))
}
showNs := tt.namespace == "" || (refNs != "" && refNs != tt.namespace)
rows, err := getRows(context.Background(), c, clientOpts, refOpts, showNs)
g.Expect(err).To(Not(HaveOccurred()))
g.Expect(rows).To(Equal(tt.expected))
})
}
}
func getTestListOpt(namespace, selector string) []client.ListOption {
clientListOpts := []client.ListOption{client.Limit(cmdutil.DefaultChunkSize), client.InNamespace(namespace)}
if selector != "" {
sel := fields.OneTermEqualSelector("involvedObject.kind/name", selector)
clientListOpts = append(clientListOpts, client.MatchingFieldsSelector{Selector: sel})
}
return clientListOpts
}
func getScheme() *runtime.Scheme {
newscheme := runtime.NewScheme()
corev1.AddToScheme(newscheme)
kustomizev1.AddToScheme(newscheme)
helmv2beta1.AddToScheme(newscheme)
notificationv1.AddToScheme(newscheme)
imagev1.AddToScheme(newscheme)
autov1.AddToScheme(newscheme)
sourcev1.AddToScheme(newscheme)
return newscheme
}
func createEvent(obj client.Object, eventType, msg, reason string) corev1.Event {
return corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Namespace: obj.GetNamespace(),
// name of event needs to be unique so fak
Name: obj.GetNamespace() + obj.GetNamespace() + obj.GetObjectKind().GroupVersionKind().Kind + eventType,
},
Reason: reason,
Message: msg,
Type: eventType,
InvolvedObject: corev1.ObjectReference{
Kind: obj.GetObjectKind().GroupVersionKind().Kind,
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
},
}
}
func kindNameIndexer(obj client.Object) []string {
e, ok := obj.(*corev1.Event)
if !ok {
panic(fmt.Sprintf("Expected a Event, got %T", e))
}
return []string{fmt.Sprintf("%s/%s", e.InvolvedObject.Kind, e.InvolvedObject.Name)}
}
......@@ -37,7 +37,7 @@ func TestHelmReleaseFromGit(t *testing.T) {
tmpl map[string]string
}{
{
"create source git thrfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.0.0",
"create source git thrfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.3.5",
"testdata/helmrelease/create_source_git.golden",
nil,
},
......
......@@ -37,7 +37,7 @@ func TestKustomizationFromGit(t *testing.T) {
tmpl map[string]string
}{
{
"create source git tkfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.0.0",
"create source git tkfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.3.5",
"testdata/kustomization/create_source_git.golden",
nil,
},
......
......@@ -21,6 +21,7 @@ import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/fluxcd/flux2/internal/flags"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta2"
......@@ -53,10 +54,13 @@ The command can read the credentials from '~/.docker/config.json' but they can a
jq -r '. | .repository + "@" + .digest')
cosign sign $digest_url
# Push manifests passed into stdin to GHCR
kustomize build . | flux push artifact oci://ghcr.io/org/config/app:$(git rev-parse --short HEAD) -p - \
# Push manifests passed into stdin to GHCR and set custom OCI annotations
kustomize build . | flux push artifact oci://ghcr.io/org/config/app:$(git rev-parse --short HEAD) -f - \
--source="$(git config --get remote.origin.url)" \
--revision="$(git branch --show-current)@sha1:$(git rev-parse HEAD)"
--revision="$(git branch --show-current)@sha1:$(git rev-parse HEAD)" \
--annotations='org.opencontainers.image.licenses=Apache-2.0' \
--annotations='org.opencontainers.image.documentation=https://app.org/docs' \
--annotations='org.opencontainers.image.description=Production config.'
# Push single manifest file to GHCR using the short Git SHA as the OCI artifact tag
echo $GITHUB_PAT | docker login ghcr.io --username flux --password-stdin
......@@ -81,7 +85,7 @@ The command can read the credentials from '~/.docker/config.json' but they can a
--revision="$(git tag --points-at HEAD)@sha1:$(git rev-parse HEAD)" \
--provider aws
# Or pass credentials directly
# Login by passing credentials directly
flux push artifact oci://docker.io/org/app-config:$(git tag --points-at HEAD) \
--path="./path/to/local/manifests" \
--source="$(git config --get remote.origin.url)" \
......@@ -98,6 +102,7 @@ type pushArtifactFlags struct {
creds string
provider flags.SourceOCIProvider
ignorePaths []string
annotations []string
output string
}
......@@ -110,12 +115,13 @@ func newPushArtifactFlags() pushArtifactFlags {
}
func init() {
pushArtifactCmd.Flags().StringVar(&pushArtifactArgs.path, "path", "", "path to the directory where the Kubernetes manifests are located")
pushArtifactCmd.Flags().StringVarP(&pushArtifactArgs.path, "path", "f", "", "path to the directory where the Kubernetes manifests are located")
pushArtifactCmd.Flags().StringVar(&pushArtifactArgs.source, "source", "", "the source address, e.g. the Git URL")
pushArtifactCmd.Flags().StringVar(&pushArtifactArgs.revision, "revision", "", "the source revision in the format '<branch|tag>@sha1:<commit-sha>'")
pushArtifactCmd.Flags().StringVar(&pushArtifactArgs.creds, "creds", "", "credentials for OCI registry in the format <username>[:<password>] if --provider is generic")
pushArtifactCmd.Flags().Var(&pushArtifactArgs.provider, "provider", pushArtifactArgs.provider.Description())
pushArtifactCmd.Flags().StringSliceVar(&pushArtifactArgs.ignorePaths, "ignore-paths", excludeOCI, "set paths to ignore in .gitignore format")
pushArtifactCmd.Flags().StringArrayVarP(&pushArtifactArgs.annotations, "annotations", "a", nil, "Set custom OCI annotations in the format '<key>=<value>'")
pushArtifactCmd.Flags().StringVarP(&pushArtifactArgs.output, "output", "o", "",
"the format in which the artifact digest should be printed, can be 'json' or 'yaml'")
......@@ -159,9 +165,19 @@ func pushArtifactCmdRun(cmd *cobra.Command, args []string) error {
return fmt.Errorf("invalid path '%s', must point to an existing directory or file: %w", path, err)
}
annotations := map[string]string{}
for _, annotation := range pushArtifactArgs.annotations {
kv := strings.Split(annotation, "=")
if len(kv) != 2 {
return fmt.Errorf("invalid annotation %s, must be in the format key=value", annotation)
}
annotations[kv[0]] = kv[1]
}
meta := oci.Metadata{
Source: pushArtifactArgs.source,
Revision: pushArtifactArgs.revision,
Source: pushArtifactArgs.source,
Revision: pushArtifactArgs.revision,
Annotations: annotations,
}
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
......
......@@ -39,7 +39,7 @@ func TestSourceOCI(t *testing.T) {
tmpl map[string]string
}{
{
"create source oci thrfg --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.1.6 --interval 10m",
"create source oci thrfg --url=oci://ghcr.io/stefanprodan/manifests/podinfo --tag=6.3.5 --interval 10m",
"testdata/oci/create_source_oci.golden",
nil,
},
......
......@@ -3,4 +3,4 @@
✔ HelmRelease created
◎ waiting for HelmRelease reconciliation
✔ HelmRelease thrfg is ready
✔ applied revision 6.0.0
✔ applied revision 6.3.5