1
0
mirror of synced 2026-03-01 19:26:55 +00:00

Compare commits

...

85 Commits

Author SHA1 Message Date
Stefan Prodan
69c3b90fea Merge pull request #1755 from fluxcd/update-components
Update toolkit components
2021-08-26 15:35:01 +03:00
fluxcdbot
75309b4c93 Update toolkit components
- kustomize-controller to v0.14.0
  https://github.com/fluxcd/kustomize-controller/blob/v0.14.0/CHANGELOG.md
- notification-controller to v0.16.0
  https://github.com/fluxcd/notification-controller/blob/v0.16.0/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-08-26 12:11:29 +00:00
Stefan Prodan
433f13a7ed Merge pull request #1754 from ttulka/logs-since-2
Add `logs` flags `--since` and `--since-time`
2021-08-26 15:10:58 +03:00
Tomas Tulka
8896a1e73e tidy
Signed-off-by: Tomas Tulka <tomas.tulka@gmail.com>
2021-08-26 10:56:25 +02:00
Tomas Tulka
54758b1692 add --since and --since-time
Signed-off-by: Tomas Tulka <tomas.tulka@gmail.com>
2021-08-25 22:10:47 +02:00
Stefan Prodan
375e00c79c Merge pull request #1748 from allenporter/ioutil
Remove use of deprecated io/ioutil
2021-08-25 08:41:50 +03:00
Allen Porter
e2454d91f1 Remove use of deprecated io/ioutil
Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-24 13:06:17 -07:00
Stefan Prodan
6894f6f3bf Merge pull request #1743 from allenporter/flux-envtest
Use shared envTest for unit tests
2021-08-24 11:56:23 +03:00
Allen Porter
d45501a129 Use shared envTest for unit tests
Speed up unit tests by using a shared envTest. This requires each
test to use its own namespace to avoid clobbering objects for
other tests. Tests previously took around 8 seconds each, and now
the initial test takes 2 seconds with follow up tests taking less
than a second each.

Also update existing tests that use a fixed namespace to use a
generated namespace.

Share gold file template function with yaml files.

Remove the testClusterMode, and instead rely on MainTest to do
the appropriate test setup and rootArgs flag setup. Move the
rootArg flag setup out of NewTestEnvKubeManager to avoid
side effects.

A follow up change can be to push the individual setups
from NewTestEnvKubeManager() into their respective TestMain since
the harness share little code.

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-24 01:01:14 -07:00
Stefan Prodan
def92e14ee Merge pull request #1740 from allenporter/flux-test-cleanup
Rename trace test golden files
2021-08-23 19:50:28 +03:00
Allen Porter
11708d4189 Rename trace test golden files
Rename trace test golden files to match the convention used by other tests

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-23 09:29:27 -07:00
Stefan Prodan
2bc64bf419 Merge pull request #1739 from allenporter/flux-cmd-test-func
Make test harness more flexible with functions
2021-08-23 19:25:31 +03:00
Allen Porter
3a3bdc62c8 Make test harness more flexible with functions
Replace the 4 arguments to cmdTestCase with a function that
can let tests run arbitrary logic if it is more complex than
what is provided by the test harness. Move the existing logic
into functions that the test can use for common assertions on
golden files and golden values.

These changes were pulled out of PR #1696 to make a smaller review.

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-23 08:57:43 -07:00
Stefan Prodan
72294b2a56 Merge pull request #1733 from fluxcd/arm64-e2e
Move arm64 e2e to Go tests
2021-08-19 15:47:52 +03:00
Stefan Prodan
94940a20ef Move arm64 e2e to Go tests
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-08-19 15:16:45 +03:00
Stefan Prodan
219ff2ef7d Merge pull request #1729 from timja/patch-1
Avoid substitution issue in kustomize for azure credentials sync
2021-08-19 13:10:54 +03:00
Tim Jacomb
bc2de741b8 Avoid substitution issue in kustomize for azure credentials sync
Signed-off-by: Tim Jacomb <tim.jacomb@hmcts.net>
2021-08-19 07:53:58 +01:00
Stefan Prodan
5eabd4e898 Merge pull request #1726 from allenporter/flux-envtest
Remove fakeclient and use testenv for flux cmd tests
2021-08-19 08:33:16 +03:00
Allen Porter
e8d6d5fe5c Remove fakeclient and use testenv for flux cmd tests
Remove use of the fake client, and replace with a real client connected to the
testEnv.

This required fixes to the yaml files as the testEnv has stricter verifcation
of objects. This also meant it was not possible to test a GitRepository with
a missing artifact since that is not a valid state.

The tests are slower than before, taking around 7-10 seconds each because the
 testEnv is setup and destroyed for every test. These will be sped up in a
 follow up PR.

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-18 18:53:53 -07:00
Stefan Prodan
55bd93ff79 Merge pull request #1727 from fluxcd/make-envtest
Wire kubebuilder assets to envtest bin
2021-08-18 17:55:02 +03:00
Stefan Prodan
b34b2d779b Wire kubebuilder assets to envtest bin
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-08-18 17:35:46 +03:00
Stefan Prodan
103ed2be65 Merge pull request #1719 from chanwit/e2e_check_pre
Add e2e test case fo check --pre
2021-08-18 16:42:53 +03:00
Chanwit Kaewkasi
cc32c1be07 add e2e test for check --pre with templating support
Signed-off-by: Chanwit Kaewkasi <chanwit@gmail.com>
2021-08-18 18:28:37 +07:00
Stefan Prodan
a3ba9817a3 Merge pull request #1720 from dholbach/update-calendar
Update links to calendar and resources
2021-08-17 17:10:40 +03:00
Daniel Holbach
6d5f1b17ad update links to calendar and resources
Signed-off-by: Daniel Holbach <daniel@weave.works>
2021-08-17 14:43:04 +02:00
Stefan Prodan
0d5d5fce46 Merge pull request #1721 from fluxcd/test-ref
Refactor e2e tests
2021-08-17 15:31:29 +03:00
Stefan Prodan
375edffd15 Add image scanning e2e tests
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-08-17 15:15:42 +03:00
Stefan Prodan
d1982e64b2 Refactor e2e tests
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-08-17 13:55:14 +03:00
Stefan Prodan
cec8b5336c Merge pull request #1697 from chanwit/e2e_install
Implement testEnv for e2e tests
2021-08-16 20:39:31 +03:00
Chanwit Kaewkasi
8f78263455 implement testEnv for e2e tests
Signed-off-by: Chanwit Kaewkasi <chanwit@gmail.com>
2021-08-17 00:07:09 +07:00
Stefan Prodan
cb96bca6aa Merge pull request #1672 from souleb/main
Adds a watch flag to the get command
2021-08-06 16:16:34 +03:00
Soule BA
c18d0b9217 Adds a watch flag to the get command
The new flag fetch and display the request ressource and then continue
watching the ressource until timeout or cancellation.

A single ressource/ressource type is supported.

Signed-off-by: Soule BA <soule@weave.works>
2021-08-06 13:44:06 +02:00
Hidde Beydals
d1970185b9 Merge pull request #1690 from fluxcd/update-components
Update toolkit components
2021-08-05 19:03:02 +02:00
fluxcdbot
794d3ee2f5 Update toolkit components
- helm-controller to v0.11.2
  https://github.com/fluxcd/helm-controller/blob/v0.11.2/CHANGELOG.md
- kustomize-controller to v0.13.3
  https://github.com/fluxcd/kustomize-controller/blob/v0.13.3/CHANGELOG.md
- source-controller to v0.15.4
  https://github.com/fluxcd/source-controller/blob/v0.15.4/CHANGELOG.md
- notification-controller to v0.15.1
  https://github.com/fluxcd/notification-controller/blob/v0.15.1/CHANGELOG.md
- image-reflector-controller to v0.11.1
  https://github.com/fluxcd/image-reflector-controller/blob/v0.11.1/CHANGELOG.md
- image-automation-controller to v0.14.1
  https://github.com/fluxcd/image-automation-controller/blob/v0.14.1/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-08-05 16:48:34 +00:00
Hidde Beydals
daeef98dfb Merge pull request #1688 from allenporter/flux-test-main
Replace init() with TestMain()
2021-08-05 18:46:56 +02:00
Allen Porter
4146df1f02 Replace init() with TestMain()
Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-04 08:14:22 -07:00
Hidde Beydals
78f4dfa48d Merge pull request #1687 from allenporter/flux-cmd-ioutil
Remove deprecated io/ioutil usage
2021-08-04 16:58:51 +02:00
Allen Porter
8b68d7d7e2 Remove deprecated io/ioutil usage
Issue #1658

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-04 07:46:25 -07:00
Stefan Prodan
ba1bba17ad Merge pull request #1683 from charles-woshicai/print-success-message
feat: display success message while create secrets via `flux` cli.
2021-08-04 17:40:17 +03:00
Charles Cai
70f2b5028f feat: display success message while create secrets via flux cli.
Signed-off-by: Charles Cai <charles.cai@sap.com>
2021-08-04 21:31:57 +08:00
Hidde Beydals
4f4f0d70a4 Merge pull request #1609 from fluxcd/patch-reconcile-req
Request reconcile using patch instead of update
2021-08-04 13:29:01 +02:00
Hidde Beydals
9607b07e65 Request reconcile using patch instead of update
This should prevent the generation of the object getting bumped, as
observed on a GKE K8s 1.18 cluster using the  logic before this commit.

We only want to generation to increase when there are actual changes to
the `spec` of a resource, as some controllers use the `generation`
value to make assumptions about what they should do during a
reconciliation.

Signed-off-by: Hidde Beydals <hello@hidde.co>
2021-08-04 13:08:36 +02:00
Stefan Prodan
3570fab0f9 Merge pull request #1682 from fluxcd/refactor-tests
Refactor test helpers
2021-08-04 11:15:33 +03:00
Stefan Prodan
dd0f17d7a5 Refactor test helpers
- move test helpers to main
- add support for inline golden values
- add test for `flux --version`

Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-08-04 10:47:33 +03:00
Stefan Prodan
2290880389 Merge pull request #1671 from allenporter/flux-trace
Add tests for flux trace command
2021-08-04 10:18:54 +03:00
Allen Porter
351d287d88 Add tests for flux trace command
Add tests for flux trace command that fake out the kubernetes client,
load objects from a yaml file and create them in the client, and
assert on the output of the trace command to an expected golden file.

This is a follow up from the suggestions in PR https://github.com/fluxcd/flux2/pull/1626 which suggested that additional
testing would be helpful. This test approach is modeled after the helm command tests.

This required some changes to the kubernetes client setup to make it
possible to use a fake. If we agree this pattern makes sense, it can be
applied to other commands.

Signed-off-by: Allen Porter <allen@thebends.org>
2021-08-03 06:35:13 -07:00
Hidde Beydals
eba6706f15 Merge pull request #1668 from dmitrika/chore/remove-deprecated-ioutil
chore: remove deprecated io/ioutil
2021-07-30 21:11:56 +02:00
Dmitry Rybin
7f425efa6b chore: remove deprecated io/ioutil
Signed-off-by: Dmitry Rybin <ayrowa@yandex.ru>
2021-07-30 20:51:46 +02:00
Stefan Prodan
d40685ab62 Merge pull request #1653 from fluxcd/gh-bug-template
Provide suggestion for some fields in bug report
2021-07-28 18:21:45 +03:00
Hidde Beydals
f795e3eeb8 Provide suggestion for some fields in bug report
This commit adds suggestion for some of the required fields because
there can be a few exceptions in which these values can not be
provided. For example when the `flux` binary can not be installed, or
the set of controllers has been installed with just an `install.yaml`
file.

We use this approach instead of making the fields optional because it
guides people to provide the information whenever they can, which
should result in higher quality bug reports.

As a tiny addition, the reference to "Flux v2" has been renamed to just
"Flux" as we are slowly transitioning "Flux v1" into "Flux Legacy".

Signed-off-by: Hidde Beydals <hello@hidde.co>
2021-07-27 13:25:17 +02:00
Hidde Beydals
d3944c0204 Merge pull request #1651 from fluxcd/gh-bug-template
Transform GitHub issue template to new format
2021-07-26 16:04:40 +02:00
Hidde Beydals
4086ab15fa Transform GitHub issue template to new format
This will help users to provide bug reports of high quality, as the
requested information is now rendered into dedicated fields, while
allowing us to mark fields as "required".

Signed-off-by: Hidde Beydals <hello@hidde.co>
2021-07-26 15:38:38 +02:00
Hidde Beydals
446a367094 Merge pull request #1626 from allenporter/flux-trace 2021-07-23 16:03:44 +02:00
Allen Porter
bd250c9871 Fix template optional field check in trace
Signed-off-by: Allen Porter <allen@thebends.org>
2021-07-22 20:20:21 -07:00
Allen Porter
91b3788362 Fix trace for optional GitRepository.Spec.Reference
Check for existence of GitRepository.Spec.Reference when displaying a trace to
avoid error:

✗ template: tmpl:28:21: executing "tmpl" at <.GitRepository.Spec.Reference.Tag>: nil pointer evaluating *v1beta1.GitRepositoryRef.Tag

Fixes issue #1621
Manually tested using the use cases highlighted in the issue.

Signed-off-by: Allen Porter <allen@thebends.org>
2021-07-22 20:20:21 -07:00
Hidde Beydals
658dbb9ea8 Merge pull request #1628 from darkowlzz/utils-tests
internal/utils: Add unit tests
2021-07-22 12:15:55 +02:00
Sunny
1257b9cbc8 internal/utils: Add unit tests
Add unit tests for various utils functions.

Signed-off-by: Sunny <darkowlzz@protonmail.com>
2021-07-19 02:05:49 +05:30
Stefan Prodan
0ae39d5a0a Merge pull request #1594 from chanwit/status-selector
Add status-selector flag for get commands to filter results based on status conditions
2021-07-08 10:49:58 +03:00
Chanwit Kaewkasi
d8911e0c77 add an example to the status-selector flag's description
Co-authored-by: Stefan Prodan <stefan.prodan@gmail.com>
Signed-off-by: Chanwit Kaewkasi <chanwit@gmail.com>
2021-07-07 14:21:26 +07:00
Chanwit Kaewkasi
1be006a45f implement status selector
Signed-off-by: Chanwit Kaewkasi <chanwit@gmail.com>
2021-07-06 22:59:03 +07:00
Stefan Prodan
b95e75ddb4 Merge pull request #1591 from fluxcd/update-components
Update kustomize-controller to v0.13.2
2021-07-06 11:15:14 +03:00
fluxcdbot
15a5f75fe7 Update toolkit components
- kustomize-controller to v0.13.2
  https://github.com/fluxcd/kustomize-controller/blob/v0.13.2/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-07-06 07:53:43 +00:00
Stefan Prodan
b01e27f50f Merge pull request #1590 from alex-petrov-vt/iss1585
Add no-header flag for get commands to omit printing the header
2021-07-06 10:53:16 +03:00
Alex Petrov
b1a9583262 Add no-header flag for get commands to omit printing the header
Signed-off-by: Alex Petrov <alex.petrov.vt@gmail.com>
2021-07-05 20:04:37 -04:00
Stefan Prodan
dd5e6377f8 Merge pull request #1579 from paulfantom/patch-1
Update podmonitor example
2021-07-02 14:36:12 +03:00
Paweł Krupa
fcb73554c9 Update podmonitor.yaml
`targetPort` is deprecated since prometheus-operator 0.38.0 as per https://github.com/prometheus-operator/prometheus-operator/blob/master/CHANGELOG.md#0380--2020-03-20

Signed-off-by: paulfantom <pawel@krupa.net.pl>
2021-07-01 17:27:54 +02:00
Stefan Prodan
5c4b3d1080 Merge pull request #1575 from dminca/feature/simplify-panel-label
fix Control Plane dashboard legend
2021-06-30 18:27:00 +03:00
Daniel-Andrei Minca
c98cd10621 fix Control Plane dashboard legend
The legend was not showing the Pod name, instead the whole resource in
the dashboard

As a result, use the correct Prometheus label

Resolves:
Related:
Signed-off-by: Daniel-Andrei Minca <mandrei17@gmail.com>
2021-06-30 16:10:53 +02:00
Stefan Prodan
e4af8ddcc8 Merge pull request #1574 from fluxcd/update-components
Update kustomize-controller to v0.13.1
2021-06-30 15:29:30 +03:00
fluxcdbot
b5ce02b8cf Update toolkit components
- kustomize-controller to v0.13.1
  https://github.com/fluxcd/kustomize-controller/blob/v0.13.1/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-06-30 12:08:03 +00:00
Stefan Prodan
cd42b3fb44 Merge pull request #1569 from fluxcd/update-components
Update source-controller to v0.15.3
2021-06-29 18:17:53 +03:00
fluxcdbot
6dedb767c3 Update toolkit components
- source-controller to v0.15.3
  https://github.com/fluxcd/source-controller/blob/v0.15.3/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-06-29 14:29:00 +00:00
Stefan Prodan
4de3268f3b Merge pull request #1570 from fluxcd/ci-debug
e2e: Update Kubernetes to v1.21.1
2021-06-29 17:28:10 +03:00
Stefan Prodan
a72ff06d79 e2e: Update Kubernetes to v1.21.1
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-29 17:15:59 +03:00
Stefan Prodan
cf239deb3d Print pods status on e2e failures
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-29 15:57:09 +03:00
Stefan Prodan
8735229745 Merge pull request #1555 from fluxcd/trace-cmd
Implement flux trace command
2021-06-29 11:22:45 +03:00
Stefan Prodan
3f081ba2d9 Add flux trace to e2e tests
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-29 11:01:20 +03:00
Stefan Prodan
3f613341cb Extend tracing to owner references
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-29 11:01:01 +03:00
Stefan Prodan
4305b8a77d Implement flux trace command
The trace command allows Flux users to point the CLI to a Kubernetes object in-cluster and get a detailed report about the GitOps pipeline that manages that particular object.

Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-29 11:01:00 +03:00
Stefan Prodan
fab91d44c3 Merge pull request #1568 from fluxcd/image-v1beta1
Use image API v1beta1
2021-06-29 11:00:26 +03:00
Michael Bridgen
34484734d8 Use image API v1beta1
Signed-off-by: Michael Bridgen <michael@weave.works>
2021-06-28 16:20:05 +01:00
Stefan Prodan
10c58bb007 Merge pull request #1567 from fluxcd/update-components
Update toolkit components
2021-06-28 17:58:05 +03:00
fluxcdbot
1c1fd62a91 Update toolkit components
- image-reflector-controller to v0.11.0
  https://github.com/fluxcd/image-reflector-controller/blob/v0.11.0/CHANGELOG.md
- image-automation-controller to v0.14.0
  https://github.com/fluxcd/image-automation-controller/blob/v0.14.0/CHANGELOG.md

Signed-off-by: GitHub <noreply@github.com>
2021-06-28 14:45:58 +00:00
Stefan Prodan
637ac1e3fe Merge pull request #1559 from fluxcd/gh-action-arm
Add ARM and ARM64 support to flux GitHub Action
2021-06-25 15:19:12 +03:00
Stefan Prodan
f52387e849 Add ARM and ARM64 support to flux GitHub Action
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2021-06-25 13:32:39 +03:00
137 changed files with 2908 additions and 396 deletions

View File

@@ -1,46 +0,0 @@
---
name: Bug report
about: Create a report to help us improve Flux v2
title: ''
assignees: ''
---
<!--
Find out more about your support options and getting help at
https://fluxcd.io/support/
-->
### Describe the bug
A clear and concise description of what the bug is.
### To Reproduce
Steps to reproduce the behaviour:
1. Provide Flux install instructions
2. Provide a GitHub repository with Kubernetes manifests
### Expected behavior
A clear and concise description of what you expected to happen.
### Additional context
- Kubernetes version:
- Git provider:
- Container registry provider:
Below please provide the output of the following commands:
```cli
flux --version
flux check
kubectl -n <namespace> get all
kubectl -n <namespace> logs deploy/source-controller
kubectl -n <namespace> logs deploy/kustomize-controller
```

85
.github/ISSUE_TEMPLATE/bug_report.yaml vendored Normal file
View File

@@ -0,0 +1,85 @@
---
name: Bug report
description: Create a report to help us improve Flux
body:
- type: markdown
attributes:
value: |
## Support
Find out more about your support options and getting help at: https://fluxcd.io/support/
- type: textarea
validations:
required: true
attributes:
label: Describe the bug
description: A clear description of what the bug is.
- type: textarea
validations:
required: true
attributes:
label: Steps to reproduce
description: |
Steps to reproduce the problem.
placeholder: |
For example:
1. Install Flux with the additional image automation controllers
2. Run command '...'
3. See error
- type: textarea
validations:
required: true
attributes:
label: Expected behavior
description: A brief description of what you expected to happen.
- type: textarea
attributes:
label: Screenshots and recordings
description: |
If applicable, add screenshots to help explain your problem. You can also record an asciinema session: https://asciinema.org/
- type: input
validations:
required: true
attributes:
label: OS / Distro
description: The OS / distro you are executing `flux` on. If not applicable, write `N/A`.
placeholder: e.g. Windows 10, Ubuntu 20.04, Arch Linux, macOS 10.15...
- type: input
validations:
required: true
attributes:
label: Flux version
description: Run `flux --version` to check. If not applicable, write `N/A`.
placeholder: e.g. 0.16.1
- type: textarea
validations:
required: true
attributes:
label: Flux check
description: Run `flux check` to check. If not applicable, write `N/A`.
placeholder: |
For example:
► checking prerequisites
✔ kubectl 1.21.0 >=1.18.0-0
✔ Kubernetes 1.21.1 >=1.16.0-0
► checking controllers
✔ all checks passed
- type: input
attributes:
label: Git provider
description: If applicable, add the Git provider you are having problems with, e.g. GitHub (Enterprise), GitLab, etc.
- type: input
attributes:
label: Container Registry provider
description: If applicable, add the Container Registry provider you are having problems with, e.g. DockerHub, GitHub Packages, Quay.io, etc.
- type: textarea
attributes:
label: Additional context
description: Add any other context about the problem here. This can be logs (e.g. output from `flux logs`), environment specific caveats, etc.
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/fluxcd/.github/blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

View File

@@ -26,6 +26,9 @@ jobs:
go-version: 1.16.x
- name: Setup Kubernetes
uses: engineerd/setup-kind@v0.5.0
with:
version: v0.11.1
image: kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
- name: Build

View File

@@ -3,7 +3,7 @@ name: e2e-arm64
on:
workflow_dispatch:
push:
branches: [ main, update-components ]
branches: [ main, update-components, arm64-e2e ]
jobs:
ampere:
@@ -23,85 +23,16 @@ jobs:
run: |
echo ::set-output name=CLUSTER::arm64-${GITHUB_SHA:0:7}-$(date +%s)
echo ::set-output name=CONTEXT::kind-arm64-${GITHUB_SHA:0:7}-$(date +%s)
- name: Run unit tests
run: make test
- name: Check if working tree is dirty
run: |
if [[ $(git diff --stat) != '' ]]; then
git diff
echo 'run make test and commit changes'
exit 1
fi
- name: Build
run: |
go build -o /tmp/flux ./cmd/flux
make build
- name: Setup Kubernetes Kind
run: |
kind create cluster --name ${{ steps.prep.outputs.CLUSTER }}
- name: flux check --pre
run: |
/tmp/flux check --pre \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux install
run: |
/tmp/flux install \
--components-extra=image-reflector-controller,image-automation-controller \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux create source git
run: |
/tmp/flux create source git podinfo-gogit \
--git-implementation=go-git \
--url https://github.com/stefanprodan/podinfo \
--tag-semver=">1.0.0" \
--context ${{ steps.prep.outputs.CONTEXT }}
/tmp/flux create source git podinfo-libgit2 \
--git-implementation=libgit2 \
--url https://github.com/stefanprodan/podinfo \
--branch="master" \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux create kustomization
run: |
/tmp/flux create kustomization podinfo \
--source=podinfo-gogit \
--path="./deploy/overlays/dev" \
--prune=true \
--interval=5m \
--validation=client \
--health-check="Deployment/frontend.dev" \
--health-check="Deployment/backend.dev" \
--health-check-timeout=3m \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux create tenant
run: |
/tmp/flux create tenant dev-team \
--with-namespace=apps \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux create helmrelease
run: |
/tmp/flux -n apps create source helm podinfo \
--url https://stefanprodan.github.io/podinfo \
--context ${{ steps.prep.outputs.CONTEXT }}
/tmp/flux -n apps create hr podinfo-helm \
--source=HelmRepository/podinfo \
--chart=podinfo \
--chart-version="6.0.x" \
--service-account=dev-team \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux get all
run: |
/tmp/flux get all --all-namespaces \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: flux uninstall
run: |
/tmp/flux uninstall -s \
--context ${{ steps.prep.outputs.CONTEXT }}
- name: Debug failure
if: failure()
run: |
kubectl --context ${{ steps.prep.outputs.CONTEXT }} -n flux-system get all
/tmp/flux logs --all-namespaces
kind create cluster --name ${{ steps.prep.outputs.CLUSTER }} --kubeconfig=/tmp/${{ steps.prep.outputs.CLUSTER }}
- name: Run e2e tests
run: TEST_KUBECONFIG=/tmp/${{ steps.prep.outputs.CLUSTER }} make e2e
- name: Cleanup
if: always()
run: |
kind delete cluster --name ${{ steps.prep.outputs.CLUSTER }}
rm /tmp/${{ steps.prep.outputs.CLUSTER }}

View File

@@ -26,17 +26,23 @@ jobs:
- name: Setup Kubernetes
uses: engineerd/setup-kind@v0.5.0
with:
version: "v0.10.0"
image: kindest/node:v1.20.2@sha256:8f7ea6e7642c0da54f04a7ee10431549c0257315b3a634f6ef2fecaaedb19bab
version: v0.11.1
image: kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
config: .github/kind/config.yaml # disable KIND-net
- name: Setup envtest
uses: fluxcd/pkg/actions/envtest@main
with:
version: "1.21.x"
- name: Setup Calico for network policy
run: |
kubectl apply -f https://docs.projectcalico.org/v3.16/manifests/calico.yaml
kubectl -n kube-system set env daemonset/calico-node FELIX_IGNORELOOSERPF=true
- name: Setup Kustomize
uses: fluxcd/pkg//actions/kustomize@main
- name: Run test
- name: Run tests
run: make test
- name: Run e2e tests
run: TEST_KUBECONFIG=$HOME/.kube/config make e2e
- name: Check if working tree is dirty
run: |
if [[ $(git diff --stat) != '' ]]; then
@@ -91,6 +97,12 @@ jobs:
--health-check="Deployment/frontend.dev" \
--health-check="Deployment/backend.dev" \
--health-check-timeout=3m
- name: flux trace
run: |
/tmp/flux trace frontend \
--kind=deployment \
--api-version=apps/v1 \
--namespace=dev
- name: flux reconcile kustomization --with-source
run: |
/tmp/flux reconcile kustomization podinfo --with-source
@@ -164,26 +176,6 @@ jobs:
--chart=podinfo \
--chart-version="5.0.x" \
--service-account=dev-team
- name: flux create image repository
run: |
/tmp/flux create image repository podinfo \
--image=ghcr.io/stefanprodan/podinfo \
--interval=1m
- name: flux create image policy
run: |
/tmp/flux create image policy podinfo \
--image-ref=podinfo \
--interval=1m \
--select-semver=5.0.x
- name: flux create image policy podinfo-select-alpha
run: |
/tmp/flux create image policy podinfo-alpha \
--image-ref=podinfo \
--interval=1m \
--select-alpha=desc
- name: flux get image policy
run: |
/tmp/flux get image policy podinfo | grep '5.0.3'
- name: flux2-kustomize-helm-example
run: |
/tmp/flux create source git flux-system \
@@ -205,6 +197,7 @@ jobs:
run: |
kubectl version --client --short
kubectl -n flux-system get all
kubectl -n flux-system describe pods
kubectl -n flux-system get kustomizations -oyaml
kubectl -n flux-system logs deploy/source-controller
kubectl -n flux-system logs deploy/kustomize-controller

View File

@@ -77,6 +77,16 @@ You can run the unit tests by simply doing
make test
```
The e2e test suite uses [kind](https://kind.sigs.k8s.io/) for running kubernetes cluster inside docker containers. You can run the e2e tests by simply doing
```bash
make setup-kind
make e2e
# When done
make cleanup-kind
```
## Acceptance policy
These things will make a PR more likely to be accepted:

View File

@@ -1,5 +1,15 @@
VERSION?=$(shell grep 'VERSION' cmd/flux/main.go | awk '{ print $$4 }' | tr -d '"')
EMBEDDED_MANIFESTS_TARGET=cmd/flux/manifests
TEST_KUBECONFIG?=/tmp/flux-e2e-test-kubeconfig
ENVTEST_BIN_VERSION?=latest
KUBEBUILDER_ASSETS?="$(shell $(SETUP_ENVTEST) use -i $(ENVTEST_BIN_VERSION) -p path)"
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif
rwildcard=$(foreach d,$(wildcard $(addsuffix *,$(1))),$(call rwildcard,$(d)/,$(2)) $(filter $(subst *,%,$(2)),$(d)))
@@ -14,8 +24,25 @@ fmt:
vet:
go vet ./...
test: $(EMBEDDED_MANIFESTS_TARGET) tidy fmt vet
go test ./... -coverprofile cover.out
setup-kind:
kind create cluster --name=flux-e2e-test --kubeconfig=$(TEST_KUBECONFIG) --config=.github/kind/config.yaml
kubectl --kubeconfig=$(TEST_KUBECONFIG) apply -f https://docs.projectcalico.org/v3.16/manifests/calico.yaml
kubectl --kubeconfig=$(TEST_KUBECONFIG) -n kube-system set env daemonset/calico-node FELIX_IGNORELOOSERPF=true
cleanup-kind:
kind delete cluster --name=flux-e2e-test
rm $(TEST_KUBECONFIG)
test: $(EMBEDDED_MANIFESTS_TARGET) tidy fmt vet setup-envtest
KUBEBUILDER_ASSETS=$(KUBEBUILDER_ASSETS) go test ./... -coverprofile cover.out --tags=unit
e2e: $(EMBEDDED_MANIFESTS_TARGET) tidy fmt vet
TEST_KUBECONFIG=$(TEST_KUBECONFIG) go test ./cmd/flux/... -coverprofile e2e.cover.out --tags=e2e -v -failfast
test-with-kind: setup-envtest
make setup-kind
make e2e
make cleanup-kind
$(EMBEDDED_MANIFESTS_TARGET): $(call rwildcard,manifests/,*.yaml *.json)
./manifests/scripts/bundle.sh
@@ -28,3 +55,19 @@ install:
install-dev:
CGO_ENABLED=0 go build -o /usr/local/bin ./cmd/flux
# Find or download setup-envtest
setup-envtest:
ifeq (, $(shell which setup-envtest))
@{ \
set -e ;\
SETUP_ENVTEST_TMP_DIR=$$(mktemp -d) ;\
cd $$SETUP_ENVTEST_TMP_DIR ;\
go mod init tmp ;\
go get sigs.k8s.io/controller-runtime/tools/setup-envtest@latest ;\
rm -rf $$SETUP_ENVTEST_TMP_DIR ;\
}
SETUP_ENVTEST=$(GOBIN)/setup-envtest
else
SETUP_ENVTEST=$(shell which setup-envtest)
endif

View File

@@ -133,7 +133,9 @@ new contributors and there are a multitude of ways to get involved.
### Events
Check out our **[events calendar](https://fluxcd.io/community/#talks)**,
both with upcoming talks you can attend or past events videos you can watch.
Check out our **[events calendar](https://fluxcd.io/#calendar)**,
both with upcoming talks, events and meetings you can attend.
Or view the **[resources section](https://fluxcd.io/resources)**
with past events videos you can watch.
We look forward to seeing you with us!

View File

@@ -10,11 +10,21 @@ Usage:
run: flux -v
```
Note that this action can only be used on GitHub **Linux AMD64** runners.
The latest stable version of the `flux` binary is downloaded from
GitHub [releases](https://github.com/fluxcd/flux2/releases)
and placed at `/usr/local/bin/flux`.
Note that this action can only be used on GitHub **Linux** runners.
You can change the arch (defaults to `amd64`) with:
```yaml
steps:
- name: Setup Flux CLI
uses: fluxcd/flux2/action@main
with:
arch: arm64 # can be amd64, arm64 or arm
```
You can download a specific version with:
```yaml

View File

@@ -8,19 +8,24 @@ inputs:
version:
description: "Flux version e.g. 0.8.0 (defaults to latest stable release)"
required: false
arch:
description: "arch can be amd64, arm64 or arm"
required: true
default: "amd64"
runs:
using: composite
steps:
- name: "Download flux binary to tmp"
shell: bash
run: |
ARCH=${{ inputs.arch }}
VERSION=${{ inputs.version }}
if [ -z $VERSION ]; then
VERSION=$(curl https://api.github.com/repos/fluxcd/flux2/releases/latest -sL | grep tag_name | sed -E 's/.*"([^"]+)".*/\1/' | cut -c 2-)
fi
BIN_URL="https://github.com/fluxcd/flux2/releases/download/v${VERSION}/flux_${VERSION}_linux_amd64.tar.gz"
BIN_URL="https://github.com/fluxcd/flux2/releases/download/v${VERSION}/flux_${VERSION}_linux_${ARCH}.tar.gz"
curl -sL ${BIN_URL} -o /tmp/flux.tar.gz
mkdir -p /tmp/flux
tar -C /tmp/flux/ -zxvf /tmp/flux.tar.gz

View File

@@ -37,6 +37,10 @@ func (a alertAdapter) asClientObject() client.Object {
return a.Alert
}
func (a alertAdapter) deepCopyClientObject() client.Object {
return a.Alert.DeepCopy()
}
// notificationv1.Alert
type alertListAdapter struct {

View File

@@ -37,6 +37,10 @@ func (a alertProviderAdapter) asClientObject() client.Object {
return a.Provider
}
func (a alertProviderAdapter) deepCopyClientObject() client.Object {
return a.Provider.DeepCopy()
}
// notificationv1.Provider
type alertProviderListAdapter struct {

View File

@@ -19,7 +19,7 @@ package main
import (
"crypto/elliptic"
"fmt"
"io/ioutil"
"os"
"github.com/spf13/cobra"
@@ -145,7 +145,7 @@ func buildEmbeddedManifestBase() (string, error) {
if !isEmbeddedVersion(bootstrapArgs.version) {
return "", nil
}
tmpBaseDir, err := ioutil.TempDir("", "flux-manifests-")
tmpBaseDir, err := os.MkdirTemp("", "flux-manifests-")
if err != nil {
return "", err
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
@@ -118,7 +117,7 @@ func bootstrapGitCmdRun(cmd *cobra.Command, args []string) error {
defer os.RemoveAll(manifestsBase)
// Lazy go-git repository
tmpDir, err := ioutil.TempDir("", "flux-bootstrap-")
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
if err != nil {
return fmt.Errorf("failed to create temporary working dir: %w", err)
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"time"
@@ -146,7 +145,7 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
}
// Lazy go-git repository
tmpDir, err := ioutil.TempDir("", "flux-bootstrap-")
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
if err != nil {
return fmt.Errorf("failed to create temporary working dir: %w", err)
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
@@ -159,7 +158,7 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
}
// Lazy go-git repository
tmpDir, err := ioutil.TempDir("", "flux-bootstrap-")
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
if err != nil {
return fmt.Errorf("failed to create temporary working dir: %w", err)
}

37
cmd/flux/check_test.go Normal file
View File

@@ -0,0 +1,37 @@
// +build e2e
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/fluxcd/flux2/internal/utils"
"k8s.io/apimachinery/pkg/version"
)
func TestCheckPre(t *testing.T) {
jsonOutput, err := utils.ExecKubectlCommand(context.TODO(), utils.ModeCapture, rootArgs.kubeconfig, rootArgs.kubecontext, "version", "--output", "json")
if err != nil {
t.Fatalf("Error running utils.ExecKubectlCommand: %v", err.Error())
}
var versions map[string]version.Info
if err := json.Unmarshal([]byte(jsonOutput), &versions); err != nil {
t.Fatalf("Error unmarshalling: %v", err.Error())
}
clientVersion := strings.TrimPrefix(versions["clientVersion"].GitVersion, "v")
serverVersion := strings.TrimPrefix(versions["serverVersion"].GitVersion, "v")
cmd := cmdTestCase{
args: "check --pre",
assert: assertGoldenTemplateFile("testdata/check/check_pre.golden", map[string]string{
"clientVersion": clientVersion,
"serverVersion": serverVersion,
}),
}
cmd.runTestCmd(t)
}

View File

@@ -20,7 +20,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/fluxcd/flux2/internal/flags"
"github.com/fluxcd/flux2/internal/utils"
@@ -201,7 +201,7 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
if len(helmReleaseArgs.valuesFiles) > 0 {
valuesMap := make(map[string]interface{})
for _, v := range helmReleaseArgs.valuesFiles {
data, err := ioutil.ReadFile(v)
data, err := os.ReadFile(v)
if err != nil {
return fmt.Errorf("reading values from %s failed: %w", v, err)
}

View File

@@ -28,7 +28,7 @@ import (
"github.com/fluxcd/pkg/apis/meta"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var createImagePolicyCmd = &cobra.Command{

View File

@@ -26,7 +26,7 @@ import (
"github.com/fluxcd/pkg/apis/meta"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var createImageRepositoryCmd = &cobra.Command{

View File

@@ -22,7 +22,7 @@ import (
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)

View File

@@ -183,7 +183,7 @@ func createSecretGitCmdRun(cmd *cobra.Command, args []string) error {
if err := upsertSecret(ctx, kubeClient, s); err != nil {
return err
}
logger.Actionf("secret '%s' created in '%s' namespace", name, rootArgs.namespace)
logger.Actionf("git secret '%s' created in '%s' namespace", name, rootArgs.namespace)
return nil
}

View File

@@ -112,5 +112,6 @@ func createSecretHelmCmdRun(cmd *cobra.Command, args []string) error {
return err
}
logger.Actionf("helm secret '%s' created in '%s' namespace", name, rootArgs.namespace)
return nil
}

View File

@@ -109,5 +109,6 @@ func createSecretTLSCmdRun(cmd *cobra.Command, args []string) error {
return err
}
logger.Actionf("tls secret '%s' created in '%s' namespace", name, rootArgs.namespace)
return nil
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"github.com/spf13/cobra"
@@ -112,7 +111,7 @@ func createSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
return err
}
tmpDir, err := ioutil.TempDir("", name)
tmpDir, err := os.MkdirTemp("", name)
if err != nil {
return err
}

View File

@@ -20,7 +20,6 @@ import (
"context"
"crypto/elliptic"
"fmt"
"io/ioutil"
"net/url"
"os"
@@ -178,7 +177,7 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
return fmt.Errorf("recurse submodules requires --git-implementation=%s", sourcev1.GoGitImplementation)
}
tmpDir, err := ioutil.TempDir("", name)
tmpDir, err := os.MkdirTemp("", name)
if err != nil {
return err
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"os"
@@ -106,7 +105,7 @@ func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
return err
}
tmpDir, err := ioutil.TempDir("", name)
tmpDir, err := os.MkdirTemp("", name)
if err != nil {
return err
}

View File

@@ -148,7 +148,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
}
if createArgs.export {
for i, _ := range tenantArgs.namespaces {
for i := range tenantArgs.namespaces {
if err := exportTenant(namespaces[i], accounts[i], roleBindings[i]); err != nil {
return err
}
@@ -164,7 +164,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
return err
}
for i, _ := range tenantArgs.namespaces {
for i := range tenantArgs.namespaces {
logger.Actionf("applying namespace %s", namespaces[i].Name)
if err := upsertNamespace(ctx, kubeClient, namespaces[i]); err != nil {
return err

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var deleteImagePolicyCmd = &cobra.Command{

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var deleteImageRepositoryCmd = &cobra.Command{

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
)
var deleteImageUpdateCmd = &cobra.Command{

View File

@@ -20,7 +20,7 @@ import (
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var exportImagePolicyCmd = &cobra.Command{

View File

@@ -20,7 +20,7 @@ import (
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var exportImageRepositoryCmd = &cobra.Command{

View File

@@ -20,7 +20,7 @@ import (
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
)
var exportImageUpdateCmd = &cobra.Command{

View File

@@ -25,6 +25,9 @@ import (
"github.com/spf13/cobra"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
watchtools "k8s.io/client-go/tools/watch"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/fluxcd/pkg/apis/meta"
@@ -32,6 +35,26 @@ import (
"github.com/fluxcd/flux2/internal/utils"
)
type deriveType func(runtime.Object) (summarisable, error)
type typeMap map[string]deriveType
func (m typeMap) registerCommand(t string, f deriveType) error {
if _, ok := m[t]; ok {
return fmt.Errorf("duplicate type function %s", t)
}
m[t] = f
return nil
}
func (m typeMap) execute(t string, obj runtime.Object) (summarisable, error) {
f, ok := m[t]
if !ok {
return nil, fmt.Errorf("unsupported type %s", t)
}
return f(obj)
}
var getCmd = &cobra.Command{
Use: "get",
Short: "Get the resources and their status",
@@ -39,7 +62,10 @@ var getCmd = &cobra.Command{
}
type GetFlags struct {
allNamespaces bool
allNamespaces bool
noHeader bool
statusSelector string
watch bool
}
var getArgs GetFlags
@@ -47,6 +73,10 @@ var getArgs GetFlags
func init() {
getCmd.PersistentFlags().BoolVarP(&getArgs.allNamespaces, "all-namespaces", "A", false,
"list the requested object(s) across all namespaces")
getCmd.PersistentFlags().BoolVarP(&getArgs.noHeader, "no-header", "", false, "skip the header when printing the results")
getCmd.PersistentFlags().BoolVarP(&getArgs.watch, "watch", "w", false, "After listing/getting the requested object, watch for changes.")
getCmd.PersistentFlags().StringVar(&getArgs.statusSelector, "status-selector", "",
"specify the status condition name and the desired state to filter the get result, e.g. ready=false")
rootCmd.AddCommand(getCmd)
}
@@ -54,6 +84,7 @@ type summarisable interface {
listAdapter
summariseItem(i int, includeNamespace bool, includeKind bool) []string
headers(includeNamespace bool) []string
statusSelectorMatches(i int, conditionType, conditionStatus string) bool
}
// --- these help with implementations of summarisable
@@ -65,6 +96,20 @@ func statusAndMessage(conditions []metav1.Condition) (string, string) {
return string(metav1.ConditionFalse), "waiting to be reconciled"
}
func statusMatches(conditionType, conditionStatus string, conditions []metav1.Condition) bool {
// we don't use apimeta.FindStatusCondition because we'd like to use EqualFold to compare two strings
var c *metav1.Condition
for i := range conditions {
if strings.EqualFold(conditions[i].Type, conditionType) {
c = &conditions[i]
}
}
if c != nil {
return strings.EqualFold(string(c.Status), conditionStatus)
}
return false
}
func nameColumns(item named, includeNamespace bool, includeKind bool) []string {
name := item.GetName()
if includeKind {
@@ -82,7 +127,8 @@ var namespaceHeader = []string{"Namespace"}
type getCommand struct {
apiType
list summarisable
list summarisable
funcMap typeMap
}
func (get getCommand) run(cmd *cobra.Command, args []string) error {
@@ -103,13 +149,17 @@ func (get getCommand) run(cmd *cobra.Command, args []string) error {
listOpts = append(listOpts, client.MatchingFields{"metadata.name": args[0]})
}
getAll := cmd.Use == "all"
if getArgs.watch {
return get.watch(ctx, kubeClient, cmd, args, listOpts)
}
err = kubeClient.List(ctx, get.list.asClientList(), listOpts...)
if err != nil {
return err
}
getAll := cmd.Use == "all"
if get.list.len() == 0 {
if !getAll {
logger.Failuref("no %s objects found in %s namespace", get.kind, rootArgs.namespace)
@@ -117,16 +167,97 @@ func (get getCommand) run(cmd *cobra.Command, args []string) error {
return nil
}
header := get.list.headers(getArgs.allNamespaces)
var rows [][]string
for i := 0; i < get.list.len(); i++ {
row := get.list.summariseItem(i, getArgs.allNamespaces, getAll)
rows = append(rows, row)
var header []string
if !getArgs.noHeader {
header = get.list.headers(getArgs.allNamespaces)
}
utils.PrintTable(os.Stdout, header, rows)
rows, err := getRowsToPrint(getAll, get.list)
if err != nil {
return err
}
utils.PrintTable(cmd.OutOrStderr(), header, rows)
if getAll {
fmt.Println()
}
return nil
}
func getRowsToPrint(getAll bool, list summarisable) ([][]string, error) {
noFilter := true
var conditionType, conditionStatus string
if getArgs.statusSelector != "" {
parts := strings.SplitN(getArgs.statusSelector, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("expected status selector in type=status format, but found: %s", getArgs.statusSelector)
}
conditionType = parts[0]
conditionStatus = parts[1]
noFilter = false
}
var rows [][]string
for i := 0; i < list.len(); i++ {
if noFilter || list.statusSelectorMatches(i, conditionType, conditionStatus) {
row := list.summariseItem(i, getArgs.allNamespaces, getAll)
rows = append(rows, row)
}
}
return rows, nil
}
//
// watch starts a client-side watch of one or more resources.
func (get *getCommand) watch(ctx context.Context, kubeClient client.WithWatch, cmd *cobra.Command, args []string, listOpts []client.ListOption) error {
w, err := kubeClient.Watch(ctx, get.list.asClientList(), listOpts...)
if err != nil {
return err
}
_, err = watchUntil(ctx, w, get)
if err != nil {
return err
}
return nil
}
func watchUntil(ctx context.Context, w watch.Interface, get *getCommand) (bool, error) {
firstIteration := true
_, error := watchtools.UntilWithoutRetry(ctx, w, func(e watch.Event) (bool, error) {
objToPrint := e.Object
sink, err := get.funcMap.execute(get.apiType.kind, objToPrint)
if err != nil {
return false, err
}
var header []string
if !getArgs.noHeader {
header = sink.headers(getArgs.allNamespaces)
}
rows, err := getRowsToPrint(false, sink)
if err != nil {
return false, err
}
if firstIteration {
utils.PrintTable(os.Stdout, header, rows)
firstIteration = false
} else {
utils.PrintTable(os.Stdout, []string{}, rows)
}
return false, nil
})
return false, error
}
func validateWatchOption(cmd *cobra.Command, toMatch string) error {
w, _ := cmd.Flags().GetBool("watch")
if cmd.Use == toMatch && w {
return fmt.Errorf("expected a single resource type, but found %s", cmd.Use)
}
return nil
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
)
@@ -32,10 +34,39 @@ var getAlertCmd = &cobra.Command{
Long: "The get alert command prints the statuses of the resources.",
Example: ` # List all Alerts and their status
flux get alerts`,
RunE: getCommand{
apiType: alertType,
list: &alertListAdapter{&notificationv1.AlertList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: alertType,
list: &alertListAdapter{&notificationv1.AlertList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*notificationv1.Alert)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v alert", obj)
}
sink := alertListAdapter{
&notificationv1.AlertList{
Items: []notificationv1.Alert{
*o,
},
},
}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -55,3 +86,8 @@ func (s alertListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (s alertListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,7 +17,10 @@ limitations under the License.
package main
import (
"fmt"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
)
@@ -29,10 +32,39 @@ var getAlertProviderCmd = &cobra.Command{
Long: "The get alert-provider command prints the statuses of the resources.",
Example: ` # List all Providers and their status
flux get alert-providers`,
RunE: getCommand{
apiType: alertProviderType,
list: alertProviderListAdapter{&notificationv1.ProviderList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: alertProviderType,
list: alertProviderListAdapter{&notificationv1.ProviderList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*notificationv1.Provider)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v alert-provider", obj)
}
sink := alertProviderListAdapter{
&notificationv1.ProviderList{
Items: []notificationv1.Provider{
*o,
},
},
}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -52,3 +84,8 @@ func (s alertProviderListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (s alertProviderListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -36,7 +36,12 @@ var getAllCmd = &cobra.Command{
# List all resources in all namespaces
flux get all --all-namespaces`,
RunE: func(cmd *cobra.Command, args []string) error {
err := getSourceAllCmd.RunE(cmd, args)
err := validateWatchOption(cmd, "all")
if err != nil {
return err
}
err = getSourceAllCmd.RunE(cmd, args)
if err != nil {
logError(err)
}

View File

@@ -17,11 +17,13 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
)
var getHelmReleaseCmd = &cobra.Command{
@@ -31,10 +33,36 @@ var getHelmReleaseCmd = &cobra.Command{
Long: "The get helmreleases command prints the statuses of the resources.",
Example: ` # List all Helm releases and their status
flux get helmreleases`,
RunE: getCommand{
apiType: helmReleaseType,
list: &helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: helmReleaseType,
list: &helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*helmv2.HelmRelease)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v helmrelease", obj)
}
sink := helmReleaseListAdapter{&helmv2.HelmReleaseList{
Items: []helmv2.HelmRelease{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -56,3 +84,8 @@ func (a helmReleaseListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a helmReleaseListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -25,6 +25,9 @@ var getImageCmd = &cobra.Command{
Aliases: []string{"image"},
Short: "Get image automation object status",
Long: "The get image sub-commands print the status of image automation objects.",
RunE: func(cmd *cobra.Command, args []string) error {
return validateWatchOption(cmd, "images")
},
}
func init() {

View File

@@ -21,8 +21,8 @@ import (
"github.com/spf13/cobra"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var getImageAllCmd = &cobra.Command{
@@ -35,6 +35,11 @@ var getImageAllCmd = &cobra.Command{
# List all image objects in all namespaces
flux get images all --all-namespaces`,
RunE: func(cmd *cobra.Command, args []string) error {
err := validateWatchOption(cmd, "all")
if err != nil {
return err
}
var allImageCmd = []getCommand{
{
apiType: imageRepositoryType,

View File

@@ -17,9 +17,12 @@ limitations under the License.
package main
import (
"github.com/spf13/cobra"
"fmt"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var getImagePolicyCmd = &cobra.Command{
@@ -31,10 +34,36 @@ var getImagePolicyCmd = &cobra.Command{
# List image policies from all namespaces
flux get image policy --all-namespaces`,
RunE: getCommand{
apiType: imagePolicyType,
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: imagePolicyType,
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*imagev1.ImagePolicy)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v policy", obj)
}
sink := imagePolicyListAdapter{&imagev1.ImagePolicyList{
Items: []imagev1.ImagePolicy{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -54,3 +83,8 @@ func (s imagePolicyListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (s imagePolicyListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,13 +17,15 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var getImageRepositoryCmd = &cobra.Command{
@@ -35,10 +37,36 @@ var getImageRepositoryCmd = &cobra.Command{
# List image repositories from all namespaces
flux get image repository --all-namespaces`,
RunE: getCommand{
apiType: imageRepositoryType,
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: imageRepositoryType,
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*imagev1.ImageRepository)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v repository", obj)
}
sink := imageRepositoryListAdapter{&imagev1.ImageRepositoryList{
Items: []imagev1.ImageRepository{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -63,3 +91,8 @@ func (s imageRepositoryListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (s imageRepositoryListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,13 +17,15 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
)
var getImageUpdateCmd = &cobra.Command{
@@ -35,10 +37,36 @@ var getImageUpdateCmd = &cobra.Command{
# List image update automations from all namespaces
flux get image update --all-namespaces`,
RunE: getCommand{
apiType: imageUpdateAutomationType,
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: imageUpdateAutomationType,
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*autov1.ImageUpdateAutomation)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v update", obj)
}
sink := imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{
Items: []autov1.ImageUpdateAutomation{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -62,3 +90,8 @@ func (s imageUpdateAutomationListAdapter) headers(includeNamespace bool) []strin
}
return headers
}
func (s imageUpdateAutomationListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
)
@@ -32,10 +34,39 @@ var getKsCmd = &cobra.Command{
Long: "The get kustomizations command prints the statuses of the resources.",
Example: ` # List all kustomizations and their status
flux get kustomizations`,
RunE: getCommand{
apiType: kustomizationType,
list: &kustomizationListAdapter{&kustomizev1.KustomizationList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: kustomizationType,
list: &kustomizationListAdapter{&kustomizev1.KustomizationList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*kustomizev1.Kustomization)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v kustomization", obj)
}
sink := kustomizationListAdapter{
&kustomizev1.KustomizationList{
Items: []kustomizev1.Kustomization{
*o,
},
},
}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -57,3 +88,8 @@ func (a kustomizationListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a kustomizationListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
)
@@ -32,10 +34,36 @@ var getReceiverCmd = &cobra.Command{
Long: "The get receiver command prints the statuses of the resources.",
Example: ` # List all Receiver and their status
flux get receivers`,
RunE: getCommand{
apiType: receiverType,
list: receiverListAdapter{&notificationv1.ReceiverList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: receiverType,
list: receiverListAdapter{&notificationv1.ReceiverList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*notificationv1.Receiver)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v receiver", obj)
}
sink := receiverListAdapter{&notificationv1.ReceiverList{
Items: []notificationv1.Receiver{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -55,3 +83,8 @@ func (s receiverListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (s receiverListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := s.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -25,6 +25,10 @@ var getSourceCmd = &cobra.Command{
Aliases: []string{"source"},
Short: "Get source statuses",
Long: "The get source sub-commands print the statuses of the sources.",
RunE: func(cmd *cobra.Command, args []string) error {
return validateWatchOption(cmd, "sources")
},
}
func init() {

View File

@@ -34,6 +34,11 @@ var getSourceAllCmd = &cobra.Command{
# List all sources in all namespaces
flux get sources all --all-namespaces`,
RunE: func(cmd *cobra.Command, args []string) error {
err := validateWatchOption(cmd, "all")
if err != nil {
return err
}
var allSourceCmd = []getCommand{
{
apiType: bucketType,

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)
@@ -34,10 +36,36 @@ var getSourceBucketCmd = &cobra.Command{
# List buckets from all namespaces
flux get sources helm --all-namespaces`,
RunE: getCommand{
apiType: bucketType,
list: &bucketListAdapter{&sourcev1.BucketList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: bucketType,
list: &bucketListAdapter{&sourcev1.BucketList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*sourcev1.Bucket)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v bucket", obj)
}
sink := &bucketListAdapter{&sourcev1.BucketList{
Items: []sourcev1.Bucket{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -62,3 +90,8 @@ func (a bucketListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a bucketListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)
@@ -34,10 +36,36 @@ var getSourceHelmChartCmd = &cobra.Command{
# List Helm charts from all namespaces
flux get sources chart --all-namespaces`,
RunE: getCommand{
apiType: helmChartType,
list: &helmChartListAdapter{&sourcev1.HelmChartList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: helmChartType,
list: &helmChartListAdapter{&sourcev1.HelmChartList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*sourcev1.HelmChart)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v chart", obj)
}
sink := &helmChartListAdapter{&sourcev1.HelmChartList{
Items: []sourcev1.HelmChart{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -62,3 +90,8 @@ func (a helmChartListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a helmChartListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)
@@ -34,10 +36,36 @@ var getSourceGitCmd = &cobra.Command{
# List Git repositories from all namespaces
flux get sources git --all-namespaces`,
RunE: getCommand{
apiType: gitRepositoryType,
list: &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: gitRepositoryType,
list: &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*sourcev1.GitRepository)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v git", obj)
}
sink := &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{
Items: []sourcev1.GitRepository{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -62,3 +90,8 @@ func (a gitRepositoryListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a gitRepositoryListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -17,10 +17,12 @@ limitations under the License.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)
@@ -34,10 +36,36 @@ var getSourceHelmCmd = &cobra.Command{
# List Helm repositories from all namespaces
flux get sources helm --all-namespaces`,
RunE: getCommand{
apiType: helmRepositoryType,
list: &helmRepositoryListAdapter{&sourcev1.HelmRepositoryList{}},
}.run,
RunE: func(cmd *cobra.Command, args []string) error {
get := getCommand{
apiType: helmRepositoryType,
list: &helmRepositoryListAdapter{&sourcev1.HelmRepositoryList{}},
funcMap: make(typeMap),
}
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
o, ok := obj.(*sourcev1.HelmRepository)
if !ok {
return nil, fmt.Errorf("Impossible to cast type %#v helm", obj)
}
sink := &helmRepositoryListAdapter{&sourcev1.HelmRepositoryList{
Items: []sourcev1.HelmRepository{
*o,
}}}
return sink, nil
})
if err != nil {
return err
}
if err := get.run(cmd, args); err != nil {
return err
}
return nil
},
}
func init() {
@@ -62,3 +90,8 @@ func (a helmRepositoryListAdapter) headers(includeNamespace bool) []string {
}
return headers
}
func (a helmRepositoryListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
item := a.Items[i]
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
}

View File

@@ -37,6 +37,10 @@ func (h helmReleaseAdapter) asClientObject() client.Object {
return h.HelmRelease
}
func (h helmReleaseAdapter) deepCopyClientObject() client.Object {
return h.HelmRelease.DeepCopy()
}
// helmv2.HelmReleaseList
type helmReleaseListAdapter struct {

View File

@@ -0,0 +1,56 @@
// +build e2e
package main
import "testing"
func TestHelmReleaseFromGit(t *testing.T) {
cases := []struct {
args string
goldenFile string
}{
{
"create source git thrfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.0.0",
"testdata/helmrelease/create_source_git.golden",
},
{
"create helmrelease thrfg --source=GitRepository/thrfg --chart=./charts/podinfo",
"testdata/helmrelease/create_helmrelease_from_git.golden",
},
{
"get helmrelease thrfg",
"testdata/helmrelease/get_helmrelease_from_git.golden",
},
{
"reconcile helmrelease thrfg --with-source",
"testdata/helmrelease/reconcile_helmrelease_from_git.golden",
},
{
"suspend helmrelease thrfg",
"testdata/helmrelease/suspend_helmrelease_from_git.golden",
},
{
"resume helmrelease thrfg",
"testdata/helmrelease/resume_helmrelease_from_git.golden",
},
{
"delete helmrelease thrfg --silent",
"testdata/helmrelease/delete_helmrelease_from_git.golden",
},
}
namespace := allocateNamespace("thrfg")
del, err := setupTestNamespace(namespace)
if err != nil {
t.Fatal(err)
}
defer del()
for _, tc := range cases {
cmd := cmdTestCase{
args: tc.args + " -n=" + namespace,
assert: assertGoldenTemplateFile(tc.goldenFile, map[string]string{"ns": namespace}),
}
cmd.runTestCmd(t)
}
}

View File

@@ -19,8 +19,8 @@ package main
import (
"sigs.k8s.io/controller-runtime/pkg/client"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
// These are general-purpose adapters for attaching methods to, for
@@ -42,6 +42,10 @@ func (a imageRepositoryAdapter) asClientObject() client.Object {
return a.ImageRepository
}
func (a imageRepositoryAdapter) deepCopyClientObject() client.Object {
return a.ImageRepository.DeepCopy()
}
// imagev1.ImageRepositoryList
type imageRepositoryListAdapter struct {
@@ -100,6 +104,10 @@ func (a imageUpdateAutomationAdapter) asClientObject() client.Object {
return a.ImageUpdateAutomation
}
func (a imageUpdateAutomationAdapter) deepCopyClientObject() client.Object {
return a.ImageUpdateAutomation.DeepCopy()
}
// autov1.ImageUpdateAutomationList
type imageUpdateAutomationListAdapter struct {

48
cmd/flux/image_test.go Normal file
View File

@@ -0,0 +1,48 @@
// +build e2e
package main
import "testing"
func TestImageScanning(t *testing.T) {
cases := []struct {
args string
goldenFile string
}{
{
"create image repository podinfo --image=ghcr.io/stefanprodan/podinfo --interval=10m",
"testdata/image/create_image_repository.golden",
},
{
"create image policy podinfo-semver --image-ref=podinfo --interval=10m --select-semver=5.0.x",
"testdata/image/create_image_policy.golden",
},
{
"get image policy podinfo-semver",
"testdata/image/get_image_policy_semver.golden",
},
{
`create image policy podinfo-regex --image-ref=podinfo --interval=10m --select-semver=">4.0.0" --filter-regex="5\.0\.0"`,
"testdata/image/create_image_policy.golden",
},
{
"get image policy podinfo-regex",
"testdata/image/get_image_policy_regex.golden",
},
}
namespace := allocateNamespace("tis")
del, err := setupTestNamespace(namespace)
if err != nil {
t.Fatal(err)
}
defer del()
for _, tc := range cases {
cmd := cmdTestCase{
args: tc.args + " -n=" + namespace,
assert: assertGoldenFile(tc.goldenFile),
}
cmd.runTestCmd(t)
}
}

View File

@@ -19,7 +19,6 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
@@ -132,7 +131,7 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
logger.Generatef("generating manifests")
}
tmpDir, err := ioutil.TempDir("", rootArgs.namespace)
tmpDir, err := os.MkdirTemp("", rootArgs.namespace)
if err != nil {
return err
}

View File

@@ -37,6 +37,10 @@ func (a kustomizationAdapter) asClientObject() client.Object {
return a.Kustomization
}
func (a kustomizationAdapter) deepCopyClientObject() client.Object {
return a.Kustomization.DeepCopy()
}
// kustomizev1.KustomizationList
type kustomizationListAdapter struct {

View File

@@ -0,0 +1,56 @@
// +build e2e
package main
import "testing"
func TestKustomizationFromGit(t *testing.T) {
cases := []struct {
args string
goldenFile string
}{
{
"create source git tkfg --url=https://github.com/stefanprodan/podinfo --branch=main --tag=6.0.0",
"testdata/kustomization/create_source_git.golden",
},
{
"create kustomization tkfg --source=tkfg --path=./deploy/overlays/dev --prune=true --interval=5m --validation=client --health-check=Deployment/frontend.dev --health-check=Deployment/backend.dev --health-check-timeout=3m",
"testdata/kustomization/create_kustomization_from_git.golden",
},
{
"get kustomization tkfg",
"testdata/kustomization/get_kustomization_from_git.golden",
},
{
"reconcile kustomization tkfg --with-source",
"testdata/kustomization/reconcile_kustomization_from_git.golden",
},
{
"suspend kustomization tkfg",
"testdata/kustomization/suspend_kustomization_from_git.golden",
},
{
"resume kustomization tkfg",
"testdata/kustomization/resume_kustomization_from_git.golden",
},
{
"delete kustomization tkfg --silent",
"testdata/kustomization/delete_kustomization_from_git.golden",
},
}
namespace := allocateNamespace("tkfg")
del, err := setupTestNamespace(namespace)
if err != nil {
t.Fatal(err)
}
defer del()
for _, tc := range cases {
cmd := cmdTestCase{
args: tc.args + " -n=" + namespace,
assert: assertGoldenTemplateFile(tc.goldenFile, map[string]string{"ns": namespace}),
}
cmd.runTestCmd(t)
}
}

View File

@@ -26,12 +26,14 @@ import (
"os"
"strings"
"sync"
"time"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/kubectl/pkg/util"
"github.com/fluxcd/flux2/internal/flags"
"github.com/fluxcd/flux2/internal/utils"
@@ -42,16 +44,19 @@ var logsCmd = &cobra.Command{
Short: "Display formatted logs for Flux components",
Long: "The logs command displays formatted logs from various Flux components.",
Example: ` # Print the reconciliation logs of all Flux custom resources in your cluster
flux logs --all-namespaces
flux logs --all-namespaces
# Print all logs of all Flux custom resources newer than 2 minutes
flux logs --all-namespaces --since=2m
# Stream logs for a particular log level
flux logs --follow --level=error --all-namespaces
# Stream logs for a particular log level
flux logs --follow --level=error --all-namespaces
# Filter logs by kind, name and namespace
flux logs --kind=Kustomization --name=podinfo --namespace=default
# Filter logs by kind, name and namespace
flux logs --kind=Kustomization --name=podinfo --namespace=default
# Print logs when Flux is installed in a different namespace than flux-system
flux logs --flux-namespace=my-namespace
# Print logs when Flux is installed in a different namespace than flux-system
flux logs --flux-namespace=my-namespace
`,
RunE: logsCmdRun,
}
@@ -64,6 +69,8 @@ type logsFlags struct {
name string
fluxNamespace string
allNamespaces bool
sinceTime string
sinceSeconds time.Duration
}
var logsArgs = &logsFlags{
@@ -78,6 +85,8 @@ func init() {
logsCmd.Flags().Int64VarP(&logsArgs.tail, "tail", "", logsArgs.tail, "lines of recent log file to display")
logsCmd.Flags().StringVarP(&logsArgs.fluxNamespace, "flux-namespace", "", rootArgs.defaults.Namespace, "the namespace where the Flux components are running")
logsCmd.Flags().BoolVarP(&logsArgs.allNamespaces, "all-namespaces", "A", false, "displays logs for objects across all namespaces")
logsCmd.Flags().DurationVar(&logsArgs.sinceSeconds, "since", logsArgs.sinceSeconds, "Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used.")
logsCmd.Flags().StringVar(&logsArgs.sinceTime, "since-time", logsArgs.sinceTime, "Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used.")
rootCmd.AddCommand(logsCmd)
}
@@ -87,7 +96,6 @@ func logsCmdRun(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()
var pods []corev1.Pod
cfg, err := utils.KubeConfig(rootArgs.kubeconfig, rootArgs.kubecontext)
if err != nil {
return err
@@ -102,7 +110,7 @@ func logsCmdRun(cmd *cobra.Command, args []string) error {
return fmt.Errorf("no argument required")
}
pods, err = getPods(ctx, clientset, fluxSelector)
pods, err := getPods(ctx, clientset, fluxSelector)
if err != nil {
return err
}
@@ -115,6 +123,24 @@ func logsCmdRun(cmd *cobra.Command, args []string) error {
logOpts.TailLines = &logsArgs.tail
}
if len(logsArgs.sinceTime) > 0 && logsArgs.sinceSeconds != 0 {
return fmt.Errorf("at most one of `sinceTime` or `sinceSeconds` may be specified")
}
if len(logsArgs.sinceTime) > 0 {
t, err := util.ParseRFC3339(logsArgs.sinceTime, metav1.Now)
if err != nil {
return fmt.Errorf("%s is not a valid (RFC3339) time", logsArgs.sinceTime)
}
logOpts.SinceTime = &t
}
if logsArgs.sinceSeconds != 0 {
// round up to the nearest second
sec := int64(logsArgs.sinceSeconds.Round(time.Second).Seconds())
logOpts.SinceSeconds = &sec
}
var requests []rest.ResponseWrapper
for _, pod := range pods {
req := clientset.CoreV1().Pods(logsArgs.fluxNamespace).GetLogs(pod.Name, logOpts)

63
cmd/flux/logs_test.go Normal file
View File

@@ -0,0 +1,63 @@
// +build unit
package main
import (
"testing"
)
func TestLogsNoArgs(t *testing.T) {
cmd := cmdTestCase{
args: "logs",
assert: assertSuccess(),
}
cmd.runTestCmd(t)
}
func TestLogsAllNamespaces(t *testing.T) {
cmd := cmdTestCase{
args: "logs --all-namespaces",
assert: assertSuccess(),
}
cmd.runTestCmd(t)
}
func TestLogsSince(t *testing.T) {
cmd := cmdTestCase{
args: "logs --since=2m",
assert: assertSuccess(),
}
cmd.runTestCmd(t)
}
func TestLogsSinceInvalid(t *testing.T) {
cmd := cmdTestCase{
args: "logs --since=XXX",
assert: assertError(`invalid argument "XXX" for "--since" flag: time: invalid duration "XXX"`),
}
cmd.runTestCmd(t)
}
func TestLogsSinceTime(t *testing.T) {
cmd := cmdTestCase{
args: "logs --since-time=2021-08-06T14:26:25.546Z",
assert: assertSuccess(),
}
cmd.runTestCmd(t)
}
func TestLogsSinceTimeInvalid(t *testing.T) {
cmd := cmdTestCase{
args: "logs --since-time=XXX",
assert: assertError("XXX is not a valid (RFC3339) time"),
}
cmd.runTestCmd(t)
}
func TestLogsSinceOnlyOneAllowed(t *testing.T) {
cmd := cmdTestCase{
args: "logs --since=2m --since-time=2021-08-06T14:26:25.546Z",
assert: assertError("at most one of `sinceTime` or `sinceSeconds` may be specified"),
}
cmd.runTestCmd(t)
}

62
cmd/flux/main_e2e_test.go Normal file
View File

@@ -0,0 +1,62 @@
// +build e2e
package main
import (
"context"
"fmt"
"os"
"testing"
"github.com/fluxcd/flux2/internal/utils"
)
func TestMain(m *testing.M) {
// Ensure tests print consistent timestamps regardless of timezone
os.Setenv("TZ", "UTC")
testEnv, err := NewTestEnvKubeManager(ExistingClusterMode)
if err != nil {
panic(fmt.Errorf("error creating kube manager: '%w'", err))
}
rootArgs.kubeconfig = testEnv.kubeConfigPath
// Install Flux.
output, err := executeCommand("install --components-extra=image-reflector-controller,image-automation-controller")
if err != nil {
panic(fmt.Errorf("install falied: %s error:'%w'", output, err))
}
// Run tests
code := m.Run()
// Uninstall Flux
output, err = executeCommand("uninstall -s --keep-namespace")
if err != nil {
panic(fmt.Errorf("uninstall falied: %s error:'%w'", output, err))
}
// Delete namespace and wait for finalisation
kubectlArgs := []string{"delete", "namespace", "flux-system"}
_, err = utils.ExecKubectlCommand(context.TODO(), utils.ModeStderrOS, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...)
if err != nil {
panic(fmt.Errorf("delete namespace error:'%w'", err))
}
testEnv.Stop()
os.Exit(code)
}
func setupTestNamespace(namespace string) (func(), error) {
kubectlArgs := []string{"create", "namespace", namespace}
_, err := utils.ExecKubectlCommand(context.TODO(), utils.ModeStderrOS, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...)
if err != nil {
return nil, err
}
return func() {
kubectlArgs := []string{"delete", "namespace", namespace}
utils.ExecKubectlCommand(context.TODO(), utils.ModeCapture, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...)
}, nil
}

310
cmd/flux/main_test.go Normal file
View File

@@ -0,0 +1,310 @@
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"text/template"
"time"
"github.com/google/go-cmp/cmp"
"github.com/mattn/go-shellwords"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
k8syaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
)
var nextNamespaceId int64
// Return a unique namespace with the specified prefix, for tests to create
// objects that won't collide with each other.
func allocateNamespace(prefix string) string {
id := atomic.AddInt64(&nextNamespaceId, 1)
return fmt.Sprintf("%s-%d", prefix, id)
}
func readYamlObjects(rdr io.Reader) ([]unstructured.Unstructured, error) {
objects := []unstructured.Unstructured{}
reader := k8syaml.NewYAMLReader(bufio.NewReader(rdr))
for {
doc, err := reader.Read()
if err != nil {
if err == io.EOF {
break
}
}
unstructuredObj := &unstructured.Unstructured{}
decoder := k8syaml.NewYAMLOrJSONDecoder(bytes.NewBuffer(doc), len(doc))
err = decoder.Decode(unstructuredObj)
if err != nil {
return nil, err
}
objects = append(objects, *unstructuredObj)
}
return objects, nil
}
// A KubeManager that can create objects that are subject to a test.
type testEnvKubeManager struct {
client client.WithWatch
testEnv *envtest.Environment
kubeConfigPath string
}
func (m *testEnvKubeManager) CreateObjectFile(objectFile string, templateValues map[string]string, t *testing.T) {
buf, err := os.ReadFile(objectFile)
if err != nil {
t.Fatalf("Error reading file '%s': %v", objectFile, err)
}
content, err := executeTemplate(string(buf), templateValues)
if err != nil {
t.Fatalf("Error evaluating template file '%s': '%v'", objectFile, err)
}
clientObjects, err := readYamlObjects(strings.NewReader(content))
if err != nil {
t.Fatalf("Error decoding yaml file '%s': %v", objectFile, err)
}
err = m.CreateObjects(clientObjects, t)
if err != nil {
t.Logf("Error creating test objects: '%v'", err)
}
}
func (m *testEnvKubeManager) CreateObjects(clientObjects []unstructured.Unstructured, t *testing.T) error {
for _, obj := range clientObjects {
// First create the object then set its status if present in the
// yaml file. Make a copy first since creating an object may overwrite
// the status.
createObj := obj.DeepCopy()
err := m.client.Create(context.Background(), createObj)
if err != nil {
return err
}
obj.SetResourceVersion(createObj.GetResourceVersion())
err = m.client.Status().Update(context.Background(), &obj)
if err != nil {
return err
}
}
return nil
}
func (m *testEnvKubeManager) Stop() error {
if m.testEnv == nil {
return fmt.Errorf("do nothing because testEnv is nil")
}
return m.testEnv.Stop()
}
func NewTestEnvKubeManager(testClusterMode TestClusterMode) (*testEnvKubeManager, error) {
switch testClusterMode {
case TestEnvClusterMode:
useExistingCluster := false
testEnv := &envtest.Environment{
UseExistingCluster: &useExistingCluster,
CRDDirectoryPaths: []string{"manifests"},
}
cfg, err := testEnv.Start()
if err != nil {
return nil, err
}
user, err := testEnv.ControlPlane.AddUser(envtest.User{
Name: "envtest-admin",
Groups: []string{"system:masters"},
}, nil)
if err != nil {
return nil, err
}
kubeConfig, err := user.KubeConfig()
if err != nil {
return nil, err
}
tmpFilename := filepath.Join("/tmp", "kubeconfig-"+time.Nanosecond.String())
os.WriteFile(tmpFilename, kubeConfig, 0644)
k8sClient, err := client.NewWithWatch(cfg, client.Options{})
if err != nil {
return nil, err
}
return &testEnvKubeManager{
testEnv: testEnv,
client: k8sClient,
kubeConfigPath: tmpFilename,
}, nil
case ExistingClusterMode:
// TEST_KUBECONFIG is mandatory to prevent destroying a current cluster accidentally.
testKubeConfig := os.Getenv("TEST_KUBECONFIG")
if testKubeConfig == "" {
return nil, fmt.Errorf("environment variable TEST_KUBECONFIG is required to run tests against an existing cluster")
}
useExistingCluster := true
config, err := clientcmd.BuildConfigFromFlags("", testKubeConfig)
testEnv := &envtest.Environment{
UseExistingCluster: &useExistingCluster,
Config: config,
}
cfg, err := testEnv.Start()
if err != nil {
return nil, err
}
k8sClient, err := client.NewWithWatch(cfg, client.Options{})
if err != nil {
return nil, err
}
return &testEnvKubeManager{
testEnv: testEnv,
client: k8sClient,
kubeConfigPath: testKubeConfig,
}, nil
}
return nil, nil
}
// Function that sets an expectation on the output of a command. Tests can
// either implement this directly or use a helper below.
type assertFunc func(output string, err error) error
// Assemble multiple assertFuncs into a single assertFunc
func assert(fns ...assertFunc) assertFunc {
return func(output string, err error) error {
for _, fn := range fns {
if assertErr := fn(output, err); assertErr != nil {
return assertErr
}
}
return nil
}
}
// Expect the command to run without error
func assertSuccess() assertFunc {
return func(output string, err error) error {
if err != nil {
return fmt.Errorf("Expected success but was error: %v", err)
}
return nil
}
}
// Expect the command to fail with the specified error
func assertError(expected string) assertFunc {
return func(output string, err error) error {
if err == nil {
return fmt.Errorf("Expected error but was success")
}
if expected != err.Error() {
return fmt.Errorf("Expected error '%v' but got '%v'", expected, err.Error())
}
return nil
}
}
// Expect the command to succeed with the expected test output.
func assertGoldenValue(expected string) assertFunc {
return assert(
assertSuccess(),
func(output string, err error) error {
diff := cmp.Diff(expected, output)
if diff != "" {
return fmt.Errorf("Mismatch from expected value (-want +got):\n%s", diff)
}
return nil
})
}
// Filename that contains the expected test output.
func assertGoldenFile(goldenFile string) assertFunc {
return assertGoldenTemplateFile(goldenFile, map[string]string{})
}
// Filename that contains the expected test output. The golden file is a template that
// is pre-processed with the specified templateValues.
func assertGoldenTemplateFile(goldenFile string, templateValues map[string]string) assertFunc {
goldenFileContents, fileErr := os.ReadFile(goldenFile)
return func(output string, err error) error {
if fileErr != nil {
return fmt.Errorf("Error reading golden file '%s': %s", goldenFile, fileErr)
}
var expectedOutput string
if len(templateValues) > 0 {
expectedOutput, err = executeTemplate(string(goldenFileContents), templateValues)
if err != nil {
return fmt.Errorf("Error executing golden template file '%s': %s", goldenFile, err)
}
} else {
expectedOutput = string(goldenFileContents)
}
if assertErr := assertGoldenValue(expectedOutput)(output, err); assertErr != nil {
return fmt.Errorf("Mismatch from golden file '%s': %v", goldenFile, assertErr)
}
return nil
}
}
type TestClusterMode int
const (
TestEnvClusterMode = TestClusterMode(iota + 1)
ExistingClusterMode
)
// Structure used for each test to load objects into kubernetes, run
// commands and assert on the expected output.
type cmdTestCase struct {
// The command line arguments to test.
args string
// Tests use assertFunc to assert on an output, success or failure. This
// can be a function defined by the test or existing function above.
assert assertFunc
// Filename that contains yaml objects to load into Kubernetes
objectFile string
}
func (cmd *cmdTestCase) runTestCmd(t *testing.T) {
actual, testErr := executeCommand(cmd.args)
if assertErr := cmd.assert(actual, testErr); assertErr != nil {
t.Error(assertErr)
}
}
func executeTemplate(content string, templateValues map[string]string) (string, error) {
tmpl := template.Must(template.New("golden").Parse(content))
var out bytes.Buffer
if err := tmpl.Execute(&out, templateValues); err != nil {
return "", err
}
return out.String(), nil
}
// Run the command and return the captured output.
func executeCommand(cmd string) (string, error) {
args, err := shellwords.Parse(cmd)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetErr(buf)
rootCmd.SetArgs(args)
logger.stderr = rootCmd.ErrOrStderr()
_, err = rootCmd.ExecuteC()
result := buf.String()
return result, err
}

View File

@@ -0,0 +1,34 @@
// +build unit
package main
import (
"fmt"
"os"
"testing"
)
// The test environment is long running process shared between tests, initialized
// by a `TestMain` function depending on how the test is involved and which tests
// are a part of the build.
var testEnv *testEnvKubeManager
func TestMain(m *testing.M) {
// Ensure tests print consistent timestamps regardless of timezone
os.Setenv("TZ", "UTC")
// Creating the test env manager sets rootArgs client flags
km, err := NewTestEnvKubeManager(TestEnvClusterMode)
if err != nil {
panic(fmt.Errorf("error creating kube manager: '%w'", err))
}
testEnv = km
rootArgs.kubeconfig = testEnv.kubeConfigPath
// Run tests
code := m.Run()
km.Stop()
os.Exit(code)
}

View File

@@ -39,6 +39,13 @@ type adapter interface {
asClientObject() client.Object
}
// copyable is an interface for a wrapper or alias from which we can
// get a deep copied client.Object, required when you e.g. want to
// calculate a patch.
type copyable interface {
deepCopyClientObject() client.Object
}
// listAdapater is the analogue to adapter, but for lists; the
// controller runtime distinguishes between methods dealing with
// objects and lists.

View File

@@ -37,6 +37,10 @@ func (a receiverAdapter) asClientObject() client.Object {
return a.Receiver
}
func (a receiverAdapter) deepCopyClientObject() client.Object {
return a.Receiver.DeepCopy()
}
// notificationv1.Receiver
type receiverListAdapter struct {

View File

@@ -52,6 +52,7 @@ type reconcileCommand struct {
type reconcilable interface {
adapter // to be able to load from the cluster
copyable // to be able to calculate patches
suspendable // to tell if it's suspended
// these are implemented by anything embedding metav1.ObjectMeta
@@ -142,6 +143,7 @@ func requestReconciliation(ctx context.Context, kubeClient client.Client,
if err := kubeClient.Get(ctx, namespacedName, obj.asClientObject()); err != nil {
return err
}
patch := client.MergeFrom(obj.deepCopyClientObject())
if ann := obj.GetAnnotations(); ann == nil {
obj.SetAnnotations(map[string]string{
meta.ReconcileRequestAnnotation: time.Now().Format(time.RFC3339Nano),
@@ -150,7 +152,7 @@ func requestReconciliation(ctx context.Context, kubeClient client.Client,
ann[meta.ReconcileRequestAnnotation] = time.Now().Format(time.RFC3339Nano)
obj.SetAnnotations(ann)
}
return kubeClient.Update(ctx, obj.asClientObject())
return kubeClient.Patch(ctx, obj.asClientObject(), patch)
})
}

View File

@@ -21,7 +21,7 @@ import (
"github.com/spf13/cobra"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var reconcileImageRepositoryCmd = &cobra.Command{

View File

@@ -22,7 +22,7 @@ import (
"github.com/spf13/cobra"
apimeta "k8s.io/apimachinery/pkg/api/meta"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
meta "github.com/fluxcd/pkg/apis/meta"
)

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var resumeImageRepositoryCmd = &cobra.Command{

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
)
var resumeImageUpdateCmd = &cobra.Command{

View File

@@ -41,6 +41,10 @@ func (a bucketAdapter) asClientObject() client.Object {
return a.Bucket
}
func (a bucketAdapter) deepCopyClientObject() client.Object {
return a.Bucket.DeepCopy()
}
// sourcev1.BucketList
type bucketListAdapter struct {
@@ -70,6 +74,10 @@ func (a helmChartAdapter) asClientObject() client.Object {
return a.HelmChart
}
func (a helmChartAdapter) deepCopyClientObject() client.Object {
return a.HelmChart.DeepCopy()
}
// sourcev1.HelmChartList
type helmChartListAdapter struct {
@@ -99,6 +107,10 @@ func (a gitRepositoryAdapter) asClientObject() client.Object {
return a.GitRepository
}
func (a gitRepositoryAdapter) deepCopyClientObject() client.Object {
return a.GitRepository.DeepCopy()
}
// sourcev1.GitRepositoryList
type gitRepositoryListAdapter struct {
@@ -128,6 +140,10 @@ func (a helmRepositoryAdapter) asClientObject() client.Object {
return a.HelmRepository
}
func (a helmRepositoryAdapter) deepCopyClientObject() client.Object {
return a.HelmRepository.DeepCopy()
}
// sourcev1.HelmRepositoryList
type helmRepositoryListAdapter struct {

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha2"
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
)
var suspendImageRepositoryCmd = &cobra.Command{

View File

@@ -19,7 +19,7 @@ package main
import (
"github.com/spf13/cobra"
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha2"
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
)
var suspendImageUpdateCmd = &cobra.Command{

View File

@@ -0,0 +1,4 @@
► checking prerequisites
✔ kubectl {{ .clientVersion }} >=1.18.0-0
✔ Kubernetes {{ .serverVersion }} >=1.16.0-0
✔ prerequisites checks passed

View File

@@ -0,0 +1,6 @@
✚ generating HelmRelease
► applying HelmRelease
✔ HelmRelease created
◎ waiting for HelmRelease reconciliation
✔ HelmRelease thrfg is ready
✔ applied revision 6.0.0

View File

@@ -0,0 +1,6 @@
✚ generating GitRepository source
► applying GitRepository source
✔ GitRepository source created
◎ waiting for GitRepository source reconciliation
✔ GitRepository source reconciliation completed
✔ fetched revision: 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951

View File

@@ -0,0 +1,2 @@
► deleting helmreleases thrfg in {{ .ns }} namespace
✔ helmreleases deleted

View File

@@ -0,0 +1,2 @@
NAME READY MESSAGE REVISION SUSPENDED
thrfg True Release reconciliation succeeded 6.0.0 False

View File

@@ -0,0 +1,10 @@
► annotating GitRepository thrfg in {{ .ns }} namespace
✔ GitRepository annotated
◎ waiting for GitRepository reconciliation
✔ GitRepository reconciliation completed
✔ fetched revision 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951
► annotating HelmRelease thrfg in {{ .ns }} namespace
✔ HelmRelease annotated
◎ waiting for HelmRelease reconciliation
✔ HelmRelease reconciliation completed
✔ applied revision 6.0.0

View File

@@ -0,0 +1,5 @@
► resuming helmreleases thrfg in {{ .ns }} namespace
✔ helmreleases resumed
◎ waiting for HelmRelease reconciliation
✔ HelmRelease reconciliation completed
✔ applied revision 6.0.0

View File

@@ -0,0 +1,2 @@
► suspending helmreleases thrfg in {{ .ns }} namespace
✔ helmreleases suspended

View File

@@ -0,0 +1,5 @@
✚ generating ImagePolicy
► applying ImagePolicy
✔ ImageRepository created
◎ waiting for ImagePolicy reconciliation
✔ ImagePolicy reconciliation completed

View File

@@ -0,0 +1,5 @@
✚ generating ImageRepository
► applying ImageRepository
✔ ImageRepository created
◎ waiting for ImageRepository reconciliation
✔ ImageRepository reconciliation completed

View File

@@ -0,0 +1,2 @@
NAME READY MESSAGE LATEST IMAGE
podinfo-regex True Latest image tag for 'ghcr.io/stefanprodan/podinfo' resolved to: 5.0.0 ghcr.io/stefanprodan/podinfo:5.0.0

View File

@@ -0,0 +1,2 @@
NAME READY MESSAGE LATEST IMAGE
podinfo-semver True Latest image tag for 'ghcr.io/stefanprodan/podinfo' resolved to: 5.0.3 ghcr.io/stefanprodan/podinfo:5.0.3

View File

@@ -0,0 +1,6 @@
✚ generating Kustomization
► applying Kustomization
✔ Kustomization created
◎ waiting for Kustomization reconciliation
✔ Kustomization tkfg is ready
✔ applied revision 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951

View File

@@ -0,0 +1,6 @@
✚ generating GitRepository source
► applying GitRepository source
✔ GitRepository source created
◎ waiting for GitRepository source reconciliation
✔ GitRepository source reconciliation completed
✔ fetched revision: 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951

View File

@@ -0,0 +1,2 @@
► deleting kustomizations tkfg in {{ .ns }} namespace
✔ kustomizations deleted

View File

@@ -0,0 +1,2 @@
NAME READY MESSAGE REVISION SUSPENDED
tkfg True Applied revision: 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951 False

View File

@@ -0,0 +1,10 @@
► annotating GitRepository tkfg in {{ .ns }} namespace
✔ GitRepository annotated
◎ waiting for GitRepository reconciliation
✔ GitRepository reconciliation completed
✔ fetched revision 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951
► annotating Kustomization tkfg in {{ .ns }} namespace
✔ Kustomization annotated
◎ waiting for Kustomization reconciliation
✔ Kustomization reconciliation completed
✔ applied revision 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951

View File

@@ -0,0 +1,5 @@
► resuming kustomizations tkfg in {{ .ns }} namespace
✔ kustomizations resumed
◎ waiting for Kustomization reconciliation
✔ Kustomization reconciliation completed
✔ applied revision 6.0.0/627d5c4bb67b77185f37e31d734b085019ff2951

View File

@@ -0,0 +1,2 @@
► suspending kustomizations tkfg in {{ .ns }} namespace
✔ kustomizations suspended

View File

@@ -0,0 +1,25 @@
Object: deployment/podinfo
Namespace: {{ .ns }}
Status: Managed by Flux
---
HelmRelease: podinfo
Namespace: {{ .ns }}
Revision: 6.0.0
Status: Last reconciled at 2021-07-16 15:42:20 +0000 UTC
Message: Release reconciliation succeeded
---
HelmChart: podinfo-podinfo
Namespace: {{ .fluxns }}
Chart: podinfo
Version: 6.0.0
Revision: 6.0.0
Status: Last reconciled at 2021-07-16 15:32:09 +0000 UTC
Message: Fetched revision: 6.0.0
---
HelmRepository: podinfo
Namespace: {{ .fluxns }}
URL: https://stefanprodan.github.io/podinfo
Revision: 8411f23d07d3701f0e96e7d9e503b7936d7e1d56
Status: Last reconciled at 2021-07-11 00:25:46 +0000 UTC
Message: Fetched revision: 8411f23d07d3701f0e96e7d9e503b7936d7e1d56

155
cmd/flux/testdata/trace/deployment.yaml vendored Normal file
View File

@@ -0,0 +1,155 @@
---
apiVersion: v1
kind: Namespace
metadata:
name: {{ .fluxns }}
---
apiVersion: v1
kind: Namespace
metadata:
name: {{ .ns }}
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: podinfo
app.kubernetes.io/managed-by: Helm
helm.toolkit.fluxcd.io/name: podinfo
helm.toolkit.fluxcd.io/namespace: {{ .ns }}
name: podinfo
namespace: {{ .ns }}
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: podinfo
template:
metadata:
labels:
app.kubernetes.io/name: podinfo
spec:
containers:
- name: hello
command: [ "echo hello world" ]
image: busybox
---
apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
labels:
kustomize.toolkit.fluxcd.io/name: infrastructure
kustomize.toolkit.fluxcd.io/namespace: {{ .fluxns }}
name: podinfo
namespace: {{ .ns }}
spec:
chart:
spec:
chart: podinfo
sourceRef:
kind: HelmRepository
name: podinfo
namespace: {{ .fluxns }}
interval: 5m
status:
conditions:
- lastTransitionTime: "2021-07-16T15:42:20Z"
message: Release reconciliation succeeded
reason: ReconciliationSucceeded
status: "True"
type: Ready
helmChart: {{ .fluxns }}/podinfo-podinfo
lastAppliedRevision: 6.0.0
lastAttemptedRevision: 6.0.0
lastAttemptedValuesChecksum: c31db75d05b7515eba2eef47bd71038c74b2e531
---
apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: HelmChart
metadata:
name: podinfo-podinfo
namespace: {{ .fluxns }}
spec:
chart: podinfo
sourceRef:
kind: HelmRepository
name: podinfo
version: 6.0.0
interval: 5m
status:
artifact:
checksum: cf13ba96773d9a879cd052c86e73199b3f96c854
lastUpdateTime: "2021-08-01T04:42:55Z"
revision: 6.0.0
path: "example"
url: "example"
conditions:
- lastTransitionTime: "2021-07-16T15:32:09Z"
message: 'Fetched revision: 6.0.0'
reason: ChartPullSucceeded
status: "True"
type: Ready
---
apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: HelmRepository
metadata:
labels:
kustomize.toolkit.fluxcd.io/name: infrastructure
kustomize.toolkit.fluxcd.io/namespace: flux-system
name: podinfo
namespace: {{ .fluxns }}
spec:
interval: 5m
timeout: 1m0s
url: https://stefanprodan.github.io/podinfo
status:
artifact:
checksum: 8411f23d07d3701f0e96e7d9e503b7936d7e1d56
lastUpdateTime: "2021-07-11T00:25:46Z"
revision: 8411f23d07d3701f0e96e7d9e503b7936d7e1d56
path: "example"
url: "example"
conditions:
- lastTransitionTime: "2021-07-11T00:25:46Z"
message: 'Fetched revision: 8411f23d07d3701f0e96e7d9e503b7936d7e1d56'
reason: IndexationSucceed
status: "True"
type: Ready
---
apiVersion: kustomize.toolkit.fluxcd.io/v1beta1
kind: Kustomization
metadata:
name: infrastructure
namespace: {{ .fluxns }}
spec:
path: ./infrastructure/
sourceRef:
kind: GitRepository
name: flux-system
validation: client
interval: 5m
prune: true
status:
conditions:
- lastTransitionTime: "2021-08-01T04:52:56Z"
message: 'Applied revision: main/696f056df216eea4f9401adbee0ff744d4df390f'
reason: ReconciliationSucceeded
status: "True"
type: Ready
---
apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: GitRepository
metadata:
labels:
kustomize.toolkit.fluxcd.io/name: flux-system
kustomize.toolkit.fluxcd.io/namespace: {{ .fluxns }}
name: flux-system
namespace: {{ .fluxns }}
spec:
gitImplementation: go-git
ref:
branch: main
secretRef:
name: flux-system
interval: 5m
url: ssh://git@github.com/example/repo

View File

@@ -0,0 +1,19 @@
Object: HelmRelease/podinfo
Namespace: {{ .ns }}
Status: Managed by Flux
---
Kustomization: infrastructure
Namespace: {{ .fluxns }}
Path: ./infrastructure
Revision: main/696f056df216eea4f9401adbee0ff744d4df390f
Status: Last reconciled at 2021-08-01 04:52:56 +0000 UTC
Message: Applied revision: main/696f056df216eea4f9401adbee0ff744d4df390f
---
GitRepository: flux-system
Namespace: {{ .fluxns }}
URL: ssh://git@github.com/example/repo
Branch: main
Revision: main/696f056df216eea4f9401adbee0ff744d4df390f
Status: Last reconciled at 2021-07-20 00:48:16 +0000 UTC
Message: Fetched revision: main/696f056df216eea4f9401adbee0ff744d4df390f

View File

@@ -0,0 +1,90 @@
---
apiVersion: v1
kind: Namespace
metadata:
name: {{ .fluxns }}
---
apiVersion: v1
kind: Namespace
metadata:
name: {{ .ns }}
---
apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
labels:
kustomize.toolkit.fluxcd.io/name: infrastructure
kustomize.toolkit.fluxcd.io/namespace: {{ .fluxns }}
name: podinfo
namespace: {{ .ns }}
spec:
chart:
spec:
chart: podinfo
sourceRef:
kind: HelmRepository
name: podinfo
namespace: {{ .fluxns }}
interval: 5m
status:
conditions:
- lastTransitionTime: "2021-07-16T15:42:20Z"
message: Release reconciliation succeeded
reason: ReconciliationSucceeded
status: "True"
type: Ready
helmChart: {{ .fluxns }}/podinfo-podinfo
lastAppliedRevision: 6.0.0
lastAttemptedRevision: 6.0.0
lastAttemptedValuesChecksum: c31db75d05b7515eba2eef47bd71038c74b2e531
---
apiVersion: kustomize.toolkit.fluxcd.io/v1beta1
kind: Kustomization
metadata:
name: infrastructure
namespace: {{ .fluxns }}
spec:
path: ./infrastructure
sourceRef:
kind: GitRepository
name: flux-system
validation: client
interval: 5m
prune: false
status:
conditions:
- lastTransitionTime: "2021-08-01T04:52:56Z"
message: 'Applied revision: main/696f056df216eea4f9401adbee0ff744d4df390f'
reason: ReconciliationSucceeded
status: "True"
type: Ready
lastAppliedRevision: main/696f056df216eea4f9401adbee0ff744d4df390f
---
apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: GitRepository
metadata:
labels:
kustomize.toolkit.fluxcd.io/name: flux-system
kustomize.toolkit.fluxcd.io/namespace: {{ .fluxns }}
name: flux-system
namespace: {{ .fluxns }}
spec:
gitImplementation: go-git
ref:
branch: main
secretRef:
name: flux-system
url: ssh://git@github.com/example/repo
interval: 5m
status:
artifact:
lastUpdateTime: "2021-08-01T04:28:42Z"
revision: main/696f056df216eea4f9401adbee0ff744d4df390f
path: "example"
url: "example"
conditions:
- lastTransitionTime: "2021-07-20T00:48:16Z"
message: 'Fetched revision: main/696f056df216eea4f9401adbee0ff744d4df390f'
reason: GitOperationSucceed
status: "True"
type: Ready

492
cmd/flux/trace.go Normal file
View File

@@ -0,0 +1,492 @@
/*
Copyright 2021 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 (
"bufio"
"bytes"
"context"
"fmt"
"text/template"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/fluxcd/flux2/internal/utils"
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
fluxmeta "github.com/fluxcd/pkg/apis/meta"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
)
var traceCmd = &cobra.Command{
Use: "trace [name]",
Short: "trace an in-cluster object throughout the GitOps delivery pipeline",
Long: `The trace command shows how an object is managed by Flux,
from which source and revision it comes, and what's the latest reconciliation status.'`,
Example: ` # Trace a Kubernetes Deployment
flux trace my-app --kind=deployment --api-version=apps/v1 --namespace=apps
# Trace a Kubernetes Pod
flux trace redis-master-0 --kind=pod --api-version=v1 -n redis
# Trace a Kubernetes global object
flux trace redis --kind=namespace --api-version=v1
# Trace a Kubernetes custom resource
flux trace redis --kind=helmrelease --api-version=helm.toolkit.fluxcd.io/v2beta1 -n redis`,
RunE: traceCmdRun,
}
type traceFlags struct {
apiVersion string
kind string
}
var traceArgs = traceFlags{}
func init() {
traceCmd.Flags().StringVar(&traceArgs.kind, "kind", "",
"the Kubernetes object kind, e.g. Deployment'")
traceCmd.Flags().StringVar(&traceArgs.apiVersion, "api-version", "",
"the Kubernetes object API version, e.g. 'apps/v1'")
rootCmd.AddCommand(traceCmd)
}
func traceCmdRun(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("object name is required")
}
name := args[0]
if traceArgs.kind == "" {
return fmt.Errorf("object kind is required (--kind)")
}
if traceArgs.apiVersion == "" {
return fmt.Errorf("object apiVersion is required (--api-version)")
}
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
if err != nil {
return err
}
gv, err := schema.ParseGroupVersion(traceArgs.apiVersion)
if err != nil {
return fmt.Errorf("invaild apiVersion: %w", err)
}
obj := &unstructured.Unstructured{}
obj.SetGroupVersionKind(schema.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: traceArgs.kind,
})
objName := types.NamespacedName{
Namespace: rootArgs.namespace,
Name: name,
}
err = kubeClient.Get(ctx, objName, obj)
if err != nil {
return fmt.Errorf("failed to find object: %w", err)
}
if ks, ok := isOwnerManagedByFlux(ctx, kubeClient, obj, kustomizev1.GroupVersion.Group); ok {
report, err := traceKustomization(ctx, kubeClient, ks, obj)
if err != nil {
return err
}
rootCmd.Print(report)
return nil
}
if hr, ok := isOwnerManagedByFlux(ctx, kubeClient, obj, helmv2.GroupVersion.Group); ok {
report, err := traceHelm(ctx, kubeClient, hr, obj)
if err != nil {
return err
}
rootCmd.Print(report)
return nil
}
return fmt.Errorf("object not managed by Flux")
}
func traceKustomization(ctx context.Context, kubeClient client.Client, ksName types.NamespacedName, obj *unstructured.Unstructured) (string, error) {
ks := &kustomizev1.Kustomization{}
ksReady := &metav1.Condition{}
err := kubeClient.Get(ctx, ksName, ks)
if err != nil {
return "", fmt.Errorf("failed to find kustomization: %w", err)
}
ksReady = meta.FindStatusCondition(ks.Status.Conditions, fluxmeta.ReadyCondition)
var ksRepository *sourcev1.GitRepository
var ksRepositoryReady *metav1.Condition
if ks.Spec.SourceRef.Kind == sourcev1.GitRepositoryKind {
ksRepository = &sourcev1.GitRepository{}
sourceNamespace := ks.Namespace
if ks.Spec.SourceRef.Namespace != "" {
sourceNamespace = ks.Spec.SourceRef.Namespace
}
err = kubeClient.Get(ctx, types.NamespacedName{
Namespace: sourceNamespace,
Name: ks.Spec.SourceRef.Name,
}, ksRepository)
if err != nil {
return "", fmt.Errorf("failed to find GitRepository: %w", err)
}
ksRepositoryReady = meta.FindStatusCondition(ksRepository.Status.Conditions, fluxmeta.ReadyCondition)
}
var traceTmpl = `
Object: {{.ObjectName}}
{{- if .ObjectNamespace }}
Namespace: {{.ObjectNamespace}}
{{- end }}
Status: Managed by Flux
{{- if .Kustomization }}
---
Kustomization: {{.Kustomization.Name}}
Namespace: {{.Kustomization.Namespace}}
{{- if .Kustomization.Spec.TargetNamespace }}
Target: {{.Kustomization.Spec.TargetNamespace}}
{{- end }}
Path: {{.Kustomization.Spec.Path}}
Revision: {{.Kustomization.Status.LastAppliedRevision}}
{{- if .KustomizationReady }}
Status: Last reconciled at {{.KustomizationReady.LastTransitionTime}}
Message: {{.KustomizationReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
{{- if .GitRepository }}
---
GitRepository: {{.GitRepository.Name}}
Namespace: {{.GitRepository.Namespace}}
URL: {{.GitRepository.Spec.URL}}
{{- if .GitRepository.Spec.Reference }}
{{- if .GitRepository.Spec.Reference.Tag }}
Tag: {{.GitRepository.Spec.Reference.Tag}}
{{- else if .GitRepository.Spec.Reference.SemVer }}
Tag: {{.GitRepository.Spec.Reference.SemVer}}
{{- else if .GitRepository.Spec.Reference.Branch }}
Branch: {{.GitRepository.Spec.Reference.Branch}}
{{- end }}
{{- end }}
{{- if .GitRepository.Status.Artifact }}
Revision: {{.GitRepository.Status.Artifact.Revision}}
{{- end }}
{{- if .GitRepositoryReady }}
{{- if eq .GitRepositoryReady.Status "False" }}
Status: Last reconciliation failed at {{.GitRepositoryReady.LastTransitionTime}}
{{- else }}
Status: Last reconciled at {{.GitRepositoryReady.LastTransitionTime}}
{{- end }}
Message: {{.GitRepositoryReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
`
traceResult := struct {
ObjectName string
ObjectNamespace string
Kustomization *kustomizev1.Kustomization
KustomizationReady *metav1.Condition
GitRepository *sourcev1.GitRepository
GitRepositoryReady *metav1.Condition
}{
ObjectName: obj.GetKind() + "/" + obj.GetName(),
ObjectNamespace: obj.GetNamespace(),
Kustomization: ks,
KustomizationReady: ksReady,
GitRepository: ksRepository,
GitRepositoryReady: ksRepositoryReady,
}
t, err := template.New("tmpl").Parse(traceTmpl)
if err != nil {
return "", err
}
var data bytes.Buffer
writer := bufio.NewWriter(&data)
if err := t.Execute(writer, traceResult); err != nil {
return "", err
}
if err := writer.Flush(); err != nil {
return "", err
}
return data.String(), nil
}
func traceHelm(ctx context.Context, kubeClient client.Client, hrName types.NamespacedName, obj *unstructured.Unstructured) (string, error) {
hr := &helmv2.HelmRelease{}
hrReady := &metav1.Condition{}
err := kubeClient.Get(ctx, hrName, hr)
if err != nil {
return "", fmt.Errorf("failed to find HelmRelease: %w", err)
}
hrReady = meta.FindStatusCondition(hr.Status.Conditions, fluxmeta.ReadyCondition)
var hrChart *sourcev1.HelmChart
var hrChartReady *metav1.Condition
if chart := hr.Status.HelmChart; chart != "" {
hrChart = &sourcev1.HelmChart{}
err = kubeClient.Get(ctx, utils.ParseNamespacedName(chart), hrChart)
if err != nil {
return "", fmt.Errorf("failed to find HelmChart: %w", err)
}
hrChartReady = meta.FindStatusCondition(hrChart.Status.Conditions, fluxmeta.ReadyCondition)
}
var hrGitRepository *sourcev1.GitRepository
var hrGitRepositoryReady *metav1.Condition
if hr.Spec.Chart.Spec.SourceRef.Kind == sourcev1.GitRepositoryKind {
hrGitRepository = &sourcev1.GitRepository{}
sourceNamespace := hr.Namespace
if hr.Spec.Chart.Spec.SourceRef.Namespace != "" {
sourceNamespace = hr.Spec.Chart.Spec.SourceRef.Namespace
}
err = kubeClient.Get(ctx, types.NamespacedName{
Namespace: sourceNamespace,
Name: hr.Spec.Chart.Spec.SourceRef.Name,
}, hrGitRepository)
if err != nil {
return "", fmt.Errorf("failed to find GitRepository: %w", err)
}
hrGitRepositoryReady = meta.FindStatusCondition(hrGitRepository.Status.Conditions, fluxmeta.ReadyCondition)
}
var hrHelmRepository *sourcev1.HelmRepository
var hrHelmRepositoryReady *metav1.Condition
if hr.Spec.Chart.Spec.SourceRef.Kind == sourcev1.HelmRepositoryKind {
hrHelmRepository = &sourcev1.HelmRepository{}
sourceNamespace := hr.Namespace
if hr.Spec.Chart.Spec.SourceRef.Namespace != "" {
sourceNamespace = hr.Spec.Chart.Spec.SourceRef.Namespace
}
err = kubeClient.Get(ctx, types.NamespacedName{
Namespace: sourceNamespace,
Name: hr.Spec.Chart.Spec.SourceRef.Name,
}, hrHelmRepository)
if err != nil {
return "", fmt.Errorf("failed to find HelmRepository: %w", err)
}
hrHelmRepositoryReady = meta.FindStatusCondition(hrHelmRepository.Status.Conditions, fluxmeta.ReadyCondition)
}
var traceTmpl = `
Object: {{.ObjectName}}
{{- if .ObjectNamespace }}
Namespace: {{.ObjectNamespace}}
{{- end }}
Status: Managed by Flux
{{- if .HelmRelease }}
---
HelmRelease: {{.HelmRelease.Name}}
Namespace: {{.HelmRelease.Namespace}}
{{- if .HelmRelease.Spec.TargetNamespace }}
Target: {{.HelmRelease.Spec.TargetNamespace}}
{{- end }}
Revision: {{.HelmRelease.Status.LastAppliedRevision}}
{{- if .HelmReleaseReady }}
Status: Last reconciled at {{.HelmReleaseReady.LastTransitionTime}}
Message: {{.HelmReleaseReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
{{- if .HelmChart }}
---
HelmChart: {{.HelmChart.Name}}
Namespace: {{.HelmChart.Namespace}}
Chart: {{.HelmChart.Spec.Chart}}
Version: {{.HelmChart.Spec.Version}}
{{- if .HelmChart.Status.Artifact }}
Revision: {{.HelmChart.Status.Artifact.Revision}}
{{- end }}
{{- if .HelmChartReady }}
Status: Last reconciled at {{.HelmChartReady.LastTransitionTime}}
Message: {{.HelmChartReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
{{- if .HelmRepository }}
---
HelmRepository: {{.HelmRepository.Name}}
Namespace: {{.HelmRepository.Namespace}}
URL: {{.HelmRepository.Spec.URL}}
{{- if .HelmRepository.Status.Artifact }}
Revision: {{.HelmRepository.Status.Artifact.Revision}}
{{- end }}
{{- if .HelmRepositoryReady }}
Status: Last reconciled at {{.HelmRepositoryReady.LastTransitionTime}}
Message: {{.HelmRepositoryReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
{{- if .GitRepository }}
---
GitRepository: {{.GitRepository.Name}}
Namespace: {{.GitRepository.Namespace}}
URL: {{.GitRepository.Spec.URL}}
{{- if .GitRepository.Spec.Reference }}
{{- if .GitRepository.Spec.Reference.Tag }}
Tag: {{.GitRepository.Spec.Reference.Tag}}
{{- else if .GitRepository.Spec.Reference.SemVer }}
Tag: {{.GitRepository.Spec.Reference.SemVer}}
{{- else if .GitRepository.Spec.Reference.Branch }}
Branch: {{.GitRepository.Spec.Reference.Branch}}
{{- end }}
{{- end }}
{{- if .GitRepository.Status.Artifact }}
Revision: {{.GitRepository.Status.Artifact.Revision}}
{{- end }}
{{- if .GitRepositoryReady }}
{{- if eq .GitRepositoryReady.Status "False" }}
Status: Last reconciliation failed at {{.GitRepositoryReady.LastTransitionTime}}
{{- else }}
Status: Last reconciled at {{.GitRepositoryReady.LastTransitionTime}}
{{- end }}
Message: {{.GitRepositoryReady.Message}}
{{- else }}
Status: Unknown
{{- end }}
{{- end }}
`
traceResult := struct {
ObjectName string
ObjectNamespace string
HelmRelease *helmv2.HelmRelease
HelmReleaseReady *metav1.Condition
HelmChart *sourcev1.HelmChart
HelmChartReady *metav1.Condition
GitRepository *sourcev1.GitRepository
GitRepositoryReady *metav1.Condition
HelmRepository *sourcev1.HelmRepository
HelmRepositoryReady *metav1.Condition
}{
ObjectName: obj.GetKind() + "/" + obj.GetName(),
ObjectNamespace: obj.GetNamespace(),
HelmRelease: hr,
HelmReleaseReady: hrReady,
HelmChart: hrChart,
HelmChartReady: hrChartReady,
GitRepository: hrGitRepository,
GitRepositoryReady: hrGitRepositoryReady,
HelmRepository: hrHelmRepository,
HelmRepositoryReady: hrHelmRepositoryReady,
}
t, err := template.New("tmpl").Parse(traceTmpl)
if err != nil {
return "", err
}
var data bytes.Buffer
writer := bufio.NewWriter(&data)
if err := t.Execute(writer, traceResult); err != nil {
return "", err
}
if err := writer.Flush(); err != nil {
return "", err
}
return data.String(), nil
}
func isManagedByFlux(obj *unstructured.Unstructured, group string) (types.NamespacedName, bool) {
nameKey := fmt.Sprintf("%s/name", group)
namespaceKey := fmt.Sprintf("%s/namespace", group)
namespacedName := types.NamespacedName{}
for k, v := range obj.GetLabels() {
if k == nameKey {
namespacedName.Name = v
}
if k == namespaceKey {
namespacedName.Namespace = v
}
}
if namespacedName.Name == "" {
return namespacedName, false
}
return namespacedName, true
}
func isOwnerManagedByFlux(ctx context.Context, kubeClient client.Client, obj *unstructured.Unstructured, group string) (types.NamespacedName, bool) {
if n, ok := isManagedByFlux(obj, group); ok {
return n, true
}
namespacedName := types.NamespacedName{}
for _, reference := range obj.GetOwnerReferences() {
owner := &unstructured.Unstructured{}
gv, err := schema.ParseGroupVersion(reference.APIVersion)
if err != nil {
return namespacedName, false
}
owner.SetGroupVersionKind(schema.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: reference.Kind,
})
ownerName := types.NamespacedName{
Namespace: obj.GetNamespace(),
Name: reference.Name,
}
err = kubeClient.Get(ctx, ownerName, owner)
if err != nil {
return namespacedName, false
}
if n, ok := isManagedByFlux(owner, group); ok {
return n, true
}
if len(owner.GetOwnerReferences()) > 0 {
return isOwnerManagedByFlux(ctx, kubeClient, owner, group)
}
}
return namespacedName, false
}

51
cmd/flux/trace_test.go Normal file
View File

@@ -0,0 +1,51 @@
// +build unit
package main
import (
"testing"
)
func TestTraceNoArgs(t *testing.T) {
cmd := cmdTestCase{
args: "trace",
assert: assertError("object name is required"),
}
cmd.runTestCmd(t)
}
func TestTrace(t *testing.T) {
cases := []struct {
name string
args string
objectFile string
goldenFile string
}{
{
"Deployment",
"trace podinfo --kind deployment --api-version=apps/v1",
"testdata/trace/deployment.yaml",
"testdata/trace/deployment.golden",
},
{
"HelmRelease",
"trace podinfo --kind HelmRelease --api-version=helm.toolkit.fluxcd.io/v2beta1",
"testdata/trace/helmrelease.yaml",
"testdata/trace/helmrelease.golden",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tmpl := map[string]string{
"ns": allocateNamespace("podinfo"),
"fluxns": allocateNamespace("flux-system"),
}
testEnv.CreateObjectFile(tc.objectFile, tmpl, t)
cmd := cmdTestCase{
args: tc.args + " -n=" + tmpl["ns"],
assert: assertGoldenTemplateFile(tc.goldenFile, tmpl),
}
cmd.runTestCmd(t)
})
}
}

15
cmd/flux/version_test.go Normal file
View File

@@ -0,0 +1,15 @@
// +build unit
package main
import (
"testing"
)
func TestVersion(t *testing.T) {
cmd := cmdTestCase{
args: "--version",
assert: assertGoldenValue("flux version 0.0.0-dev.0\n"),
}
cmd.runTestCmd(t)
}

Some files were not shown because too many files have changed in this diff Show More