Compare commits
233 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c61cfcbd18 | ||
|
|
eba2dd36e0 | ||
|
|
2a75754561 | ||
|
|
d03944893d | ||
|
|
884c6ebd37 | ||
|
|
331ac3f031 | ||
|
|
ccc84a8367 | ||
|
|
daeb41c31b | ||
|
|
17bda9c110 | ||
|
|
febedaad8f | ||
|
|
d1357dff1f | ||
|
|
102552427f | ||
|
|
f33898265d | ||
|
|
57bdaf939a | ||
|
|
981fed111b | ||
|
|
3a4a2002d4 | ||
|
|
b8d4af5538 | ||
|
|
0646538cef | ||
|
|
70a87247e2 | ||
|
|
61129c6b6a | ||
|
|
c158f95130 | ||
|
|
ad90d37f14 | ||
|
|
73ba754481 | ||
|
|
7dcfbdbb29 | ||
|
|
f453507fcc | ||
|
|
c5465de000 | ||
|
|
352b864636 | ||
|
|
c034befbb5 | ||
|
|
572cdf40fc | ||
|
|
0c0d353e9c | ||
|
|
bcc90afba2 | ||
|
|
a919703011 | ||
|
|
3300a45c39 | ||
|
|
f1cfae8f26 | ||
|
|
62763961be | ||
|
|
f1dab2279d | ||
|
|
ea337cf839 | ||
|
|
27277136f8 | ||
|
|
dd0b807fe4 | ||
|
|
ed09dd57b6 | ||
|
|
58b4c980c1 | ||
|
|
dd5165dcbf | ||
|
|
6da22613fe | ||
|
|
d0926776a5 | ||
|
|
14dc39e8d2 | ||
|
|
f0f2a79384 | ||
|
|
7b6f875920 | ||
|
|
52cec044b8 | ||
|
|
07dd59892f | ||
|
|
ffeaa683c5 | ||
|
|
1301bf7c15 | ||
|
|
69387fd2a4 | ||
|
|
12a0ebe3ba | ||
|
|
3de81827eb | ||
|
|
a7362b60e7 | ||
|
|
5d4bb3a43f | ||
|
|
d02d507812 | ||
|
|
554de7ba6f | ||
|
|
5d9ccc973d | ||
|
|
53ffb8aa00 | ||
|
|
c4da4a81aa | ||
|
|
b824ea8858 | ||
|
|
22e26efec1 | ||
|
|
679490e8f4 | ||
|
|
15f17ed36d | ||
|
|
c8265fb80c | ||
|
|
3883e92631 | ||
|
|
aa9bc4ce8b | ||
|
|
37c14e8088 | ||
|
|
439fbafc01 | ||
|
|
1b8e980519 | ||
|
|
567acb6291 | ||
|
|
996bfe87ff | ||
|
|
3c1793b6c5 | ||
|
|
1a7f253767 | ||
|
|
f188e59b21 | ||
|
|
5ea4e814f5 | ||
|
|
008b3b8408 | ||
|
|
7ae3dee900 | ||
|
|
2395ab6e14 | ||
|
|
8efe053ffa | ||
|
|
612600b88c | ||
|
|
4d7df52dbe | ||
|
|
b6c63a1aa4 | ||
|
|
a4788ce6bb | ||
|
|
0ba6fc1b36 | ||
|
|
0e35c209d9 | ||
|
|
3b9b2cbe9f | ||
|
|
45240bdb71 | ||
|
|
22a5ac7f0f | ||
|
|
d55d185044 | ||
|
|
2bb09697ce | ||
|
|
f316aff2d3 | ||
|
|
433628791b | ||
|
|
4f52b77563 | ||
|
|
52145c045d | ||
|
|
512761080e | ||
|
|
037a5b71fd | ||
|
|
b66bdec61a | ||
|
|
16f52610ab | ||
|
|
b2f018e29b | ||
|
|
1f497cac44 | ||
|
|
4abe69f90a | ||
|
|
75023011d3 | ||
|
|
09f145d880 | ||
|
|
811cd4248f | ||
|
|
a4871724ac | ||
|
|
a7d6446d8f | ||
|
|
635a17ef1e | ||
|
|
6280fbce17 | ||
|
|
daa72e72b0 | ||
|
|
35bb770697 | ||
|
|
9cc5a7d8de | ||
|
|
9b62f01b53 | ||
|
|
a643a82006 | ||
|
|
82b74d8689 | ||
|
|
a5825bb9f5 | ||
|
|
88a890d717 | ||
|
|
be6fab795d | ||
|
|
7a5b9e2991 | ||
|
|
ee1f70841c | ||
|
|
adc3d17eab | ||
|
|
f909d6fde2 | ||
|
|
016a388147 | ||
|
|
aea442e7e1 | ||
|
|
bb013ceb28 | ||
|
|
dd65e9b89d | ||
|
|
12146eda8c | ||
|
|
cd87fbba0d | ||
|
|
c73541f81f | ||
|
|
4618998792 | ||
|
|
0a3b581aa9 | ||
|
|
aaa319b9bf | ||
|
|
25e782177b | ||
|
|
e940fd3d1f | ||
|
|
31d5cb4ad8 | ||
|
|
21576fe459 | ||
|
|
65863a2cb8 | ||
|
|
cdd055bfa6 | ||
|
|
fedf960a5f | ||
|
|
4546fa3270 | ||
|
|
979f3f557c | ||
|
|
48a38a8a5d | ||
|
|
9880b32b0a | ||
|
|
e664ef7a8d | ||
|
|
7cfef379d0 | ||
|
|
093a91c7fc | ||
|
|
94687a047f | ||
|
|
38fdc603ad | ||
|
|
55cecb7f96 | ||
|
|
32e949598e | ||
|
|
6d0c8aff4b | ||
|
|
5eecf03af6 | ||
|
|
76e9884032 | ||
|
|
9867c4baf0 | ||
|
|
2bc05c8cbd | ||
|
|
d15b0107e4 | ||
|
|
c64cb1304d | ||
|
|
c1f209c7a5 | ||
|
|
116ccd6b3b | ||
|
|
b6f30ae3e1 | ||
|
|
5c522ed2e1 | ||
|
|
bc29b80912 | ||
|
|
cfbc17fbf8 | ||
|
|
af0c939302 | ||
|
|
e02538d38d | ||
|
|
001d37567c | ||
|
|
af82ce31a6 | ||
|
|
12ad4908fa | ||
|
|
40ef94ab45 | ||
|
|
8834ab0210 | ||
|
|
128d23720f | ||
|
|
90f4891ca9 | ||
|
|
61ac81c4d9 | ||
|
|
bd05a8173c | ||
|
|
e3d6461a80 | ||
|
|
2bb582f7ed | ||
|
|
2f9a52852f | ||
|
|
137f083b4d | ||
|
|
11f4c54a40 | ||
|
|
c813eaf6d1 | ||
|
|
ffdaa9dfe9 | ||
|
|
182928002b | ||
|
|
7222af2b7e | ||
|
|
034ead5272 | ||
|
|
eca1f19e95 | ||
|
|
ec70c14649 | ||
|
|
65d906a735 | ||
|
|
b981bae1db | ||
|
|
d2df9ccf33 | ||
|
|
5e51f51449 | ||
|
|
2c044a27e4 | ||
|
|
d274a1115e | ||
|
|
bfae2899f3 | ||
|
|
5352a7e13a | ||
|
|
c49f9ef26a | ||
|
|
4a7376c5f5 | ||
|
|
567ce7f987 | ||
|
|
26bc0a8100 | ||
|
|
e7ff319685 | ||
|
|
072138deff | ||
|
|
dd8dc90c1e | ||
|
|
8f1da33375 | ||
|
|
c02fbc2794 | ||
|
|
371db07108 | ||
|
|
99f5dbf16b | ||
|
|
0db06c8962 | ||
|
|
a8e5876b2e | ||
|
|
8273851b73 | ||
|
|
c2967240bb | ||
|
|
282a6270c8 | ||
|
|
1b299fad90 | ||
|
|
aa8dced7ad | ||
|
|
050ba951b0 | ||
|
|
5e47c16099 | ||
|
|
902db4c732 | ||
|
|
86462fbee6 | ||
|
|
48bed79439 | ||
|
|
26b61c2b6b | ||
|
|
3b2253ddc0 | ||
|
|
5ddcb39129 | ||
|
|
59adef5bcc | ||
|
|
875aefc8dd | ||
|
|
0dbc9d213e | ||
|
|
9f4c53e321 | ||
|
|
3c8716f6ac | ||
|
|
1a7f31ae2e | ||
|
|
64ad69acfe | ||
|
|
9f47b55aa9 | ||
|
|
53a1db0703 | ||
|
|
2a789ec705 | ||
|
|
3047b25193 | ||
|
|
f66399cdc0 |
17
.github/aur/flux-bin/.SRCINFO.template
vendored
Normal file
17
.github/aur/flux-bin/.SRCINFO.template
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
pkgbase = flux-bin
|
||||
pkgdesc = Open and extensible continuous delivery solution for Kubernetes
|
||||
pkgver = ${PKGVER}
|
||||
pkgrel = ${PKGREL}
|
||||
url = https://fluxcd.io/
|
||||
arch = x86_64
|
||||
arch = armv6h
|
||||
arch = armv7h
|
||||
arch = aarch64
|
||||
license = APACHE
|
||||
optdepends = kubectl
|
||||
source_x86_64 = flux-bin-${PKGVER}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v1/flux_${PKGVER}_linux_amd64.tar.gz
|
||||
source_armv6h = flux-bin-${PKGVER}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v1/flux_${PKGVER}_linux_arm.tar.gz
|
||||
source_armv7h = flux-bin-${PKGVER}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v1/flux_${PKGVER}_linux_arm.tar.gz
|
||||
source_aarch64 = flux-bin-${PKGVER}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v1/flux_${PKGVER}_linux_arm64.tar.gz
|
||||
|
||||
pkgname = flux-bin
|
||||
1
.github/aur/flux-bin/.gitignore
vendored
Normal file
1
.github/aur/flux-bin/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.pkg
|
||||
39
.github/aur/flux-bin/PKGBUILD.template
vendored
Normal file
39
.github/aur/flux-bin/PKGBUILD.template
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
# Maintainer: Aurel Canciu <aurelcanciu@gmail.com>
|
||||
# Maintainer: Hidde Beydals <hello@hidde.co>
|
||||
|
||||
pkgname=flux-bin
|
||||
pkgver=${PKGVER}
|
||||
pkgrel=${PKGREL}
|
||||
pkgdesc="Open and extensible continuous delivery solution for Kubernetes"
|
||||
url="https://fluxcd.io/"
|
||||
arch=("x86_64" "armv6h" "armv7h" "aarch64")
|
||||
license=("APACHE")
|
||||
optdepends=("kubectl")
|
||||
source_x86_64=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_amd64.tar.gz"
|
||||
)
|
||||
source_armv6h=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
)
|
||||
source_armv7h=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
)
|
||||
source_aarch64=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm64.tar.gz"
|
||||
)
|
||||
sha256sums_x86_64=(
|
||||
${SHA256SUM_AMD64}
|
||||
)
|
||||
sha256sums_armv6h=(
|
||||
${SHA256SUM_ARM}
|
||||
)
|
||||
sha256sums_armv7h=(
|
||||
${SHA256SUM_ARM}
|
||||
)
|
||||
sha256sums_aarch64=(
|
||||
${SHA256SUM_ARM64}
|
||||
)
|
||||
|
||||
package() {
|
||||
install -Dm755 flux "$pkgdir/usr/bin/flux"
|
||||
}
|
||||
55
.github/aur/flux-bin/publish.sh
vendored
Executable file
55
.github/aur/flux-bin/publish.sh
vendored
Executable file
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
|
||||
WD=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)
|
||||
PKGNAME=$(basename $WD)
|
||||
ROOT=${WD%/.github/aur/$PKGNAME}
|
||||
|
||||
LOCKFILE=/tmp/aur-$PKGNAME.lock
|
||||
exec 100>$LOCKFILE || exit 0
|
||||
flock -n 100 || exit 0
|
||||
trap "rm -f $LOCKFILE" EXIT
|
||||
|
||||
export VERSION=$1
|
||||
echo "Publishing to AUR as version ${VERSION}"
|
||||
|
||||
cd $WD
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
|
||||
|
||||
eval $(ssh-agent -s)
|
||||
ssh-add <(echo "$AUR_BOT_SSH_PRIVATE_KEY")
|
||||
|
||||
GITDIR=$(mktemp -d /tmp/aur-$PKGNAME-XXX)
|
||||
trap "rm -rf $GITDIR" EXIT
|
||||
git clone aur@aur.archlinux.org:$PKGNAME $GITDIR 2>&1
|
||||
|
||||
CURRENT_PKGVER=$(cat $GITDIR/.SRCINFO | grep pkgver | awk '{ print $3 }')
|
||||
CURRENT_PKGREL=$(cat $GITDIR/.SRCINFO | grep pkgrel | awk '{ print $3 }')
|
||||
|
||||
export PKGVER=${VERSION/-/}
|
||||
|
||||
if [[ "${CURRENT_PKGVER}" == "${PKGVER}" ]]; then
|
||||
export PKGREL=$((CURRENT_PKGREL+1))
|
||||
else
|
||||
export PKGREL=1
|
||||
fi
|
||||
|
||||
export SHA256SUM_ARM=$(sha256sum ${ROOT}/dist/flux_${PKGVER}_linux_arm.tar.gz | awk '{ print $1 }')
|
||||
export SHA256SUM_ARM64=$(sha256sum ${ROOT}/dist/flux_${PKGVER}_linux_arm64.tar.gz | awk '{ print $1 }')
|
||||
export SHA256SUM_AMD64=$(sha256sum ${ROOT}/dist/flux_${PKGVER}_linux_amd64.tar.gz | awk '{ print $1 }')
|
||||
|
||||
envsubst '$PKGVER $PKGREL $SHA256SUM_AMD64 $SHA256SUM_ARM $SHA256SUM_ARM64' < .SRCINFO.template > $GITDIR/.SRCINFO
|
||||
envsubst '$PKGVER $PKGREL $SHA256SUM_AMD64 $SHA256SUM_ARM $SHA256SUM_ARM64' < PKGBUILD.template > $GITDIR/PKGBUILD
|
||||
|
||||
cd $GITDIR
|
||||
git config user.name "fluxcdbot"
|
||||
git config user.email "fluxcdbot@users.noreply.github.com"
|
||||
git add -A
|
||||
if [ -z "$(git status --porcelain)" ]; then
|
||||
echo "No changes."
|
||||
else
|
||||
git commit -m "Updated to version v${PKGVER} release ${PKGREL}"
|
||||
git push origin master
|
||||
fi
|
||||
19
.github/aur/flux-go/.SRCINFO.template
vendored
Normal file
19
.github/aur/flux-go/.SRCINFO.template
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
pkgbase = flux-go
|
||||
pkgdesc = Open and extensible continuous delivery solution for Kubernetes
|
||||
pkgver = ${PKGVER}
|
||||
pkgrel = ${PKGREL}
|
||||
url = https://fluxcd.io/
|
||||
arch = x86_64
|
||||
arch = armv6h
|
||||
arch = armv7h
|
||||
arch = aarch64
|
||||
license = APACHE
|
||||
makedepends = go
|
||||
depends = glibc
|
||||
optdepends = kubectl
|
||||
provides = flux-bin
|
||||
conflicts = flux-bin
|
||||
replaces = flux-cli
|
||||
source = flux-go-${PKGVER}.tar.gz::https://github.com/fluxcd/flux2/archive/v${PKGVER}.tar.gz
|
||||
|
||||
pkgname = flux-go
|
||||
1
.github/aur/flux-go/.gitignore
vendored
Normal file
1
.github/aur/flux-go/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.pkg
|
||||
43
.github/aur/flux-go/PKGBUILD.template
vendored
Normal file
43
.github/aur/flux-go/PKGBUILD.template
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
# Maintainer: Aurel Canciu <aurelcanciu@gmail.com>
|
||||
# Maintainer: Hidde Beydals <hello@hidde.co>
|
||||
|
||||
pkgname=flux-go
|
||||
pkgver=${PKGVER}
|
||||
pkgrel=${PKGREL}
|
||||
pkgdesc="Open and extensible continuous delivery solution for Kubernetes"
|
||||
url="https://fluxcd.io/"
|
||||
arch=("x86_64" "armv6h" "armv7h" "aarch64")
|
||||
license=("APACHE")
|
||||
provides=("flux-bin")
|
||||
conflicts=("flux-bin")
|
||||
replaces=("flux-cli")
|
||||
depends=("glibc")
|
||||
makedepends=("go")
|
||||
optdepends=("kubectl")
|
||||
source=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/archive/v$pkgver.tar.gz"
|
||||
)
|
||||
sha256sums=(
|
||||
${SHA256SUM}
|
||||
)
|
||||
|
||||
build() {
|
||||
cd "flux2-$pkgver"
|
||||
export CGO_LDFLAGS="$LDFLAGS"
|
||||
export CGO_CFLAGS="$CFLAGS"
|
||||
export CGO_CXXFLAGS="$CXXFLAGS"
|
||||
export CGO_CPPFLAGS="$CPPFLAGS"
|
||||
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
|
||||
go build -ldflags "-X main.VERSION=$pkgver" -o flux-bin ./cmd/flux
|
||||
}
|
||||
|
||||
check() {
|
||||
cd "flux2-$pkgver"
|
||||
make test
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "flux2-$pkgver"
|
||||
install -Dm755 flux-bin "$pkgdir/usr/bin/flux"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
}
|
||||
53
.github/aur/flux-go/publish.sh
vendored
Executable file
53
.github/aur/flux-go/publish.sh
vendored
Executable file
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
|
||||
WD=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)
|
||||
PKGNAME=$(basename $WD)
|
||||
ROOT=${WD%/.github/aur/$PKGNAME}
|
||||
|
||||
LOCKFILE=/tmp/aur-$PKGNAME.lock
|
||||
exec 100>$LOCKFILE || exit 0
|
||||
flock -n 100 || exit 0
|
||||
trap "rm -f $LOCKFILE" EXIT
|
||||
|
||||
export VERSION=$1
|
||||
echo "Publishing to AUR as version ${VERSION}"
|
||||
|
||||
cd $WD
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
|
||||
|
||||
eval $(ssh-agent -s)
|
||||
ssh-add <(echo "$AUR_BOT_SSH_PRIVATE_KEY")
|
||||
|
||||
GITDIR=$(mktemp -d /tmp/aur-$PKGNAME-XXX)
|
||||
trap "rm -rf $GITDIR" EXIT
|
||||
git clone aur@aur.archlinux.org:$PKGNAME $GITDIR 2>&1
|
||||
|
||||
CURRENT_PKGVER=$(cat $GITDIR/.SRCINFO | grep pkgver | awk '{ print $3 }')
|
||||
CURRENT_PKGREL=$(cat $GITDIR/.SRCINFO | grep pkgrel | awk '{ print $3 }')
|
||||
|
||||
export PKGVER=${VERSION/-/}
|
||||
|
||||
if [[ "${CURRENT_PKGVER}" == "${PKGVER}" ]]; then
|
||||
export PKGREL=$((CURRENT_PKGREL+1))
|
||||
else
|
||||
export PKGREL=1
|
||||
fi
|
||||
|
||||
export SHA256SUM=$(curl -sL https://github.com/fluxcd/flux2/archive/v$PKGVER.tar.gz | sha256sum | awk '{ print $1 }')
|
||||
|
||||
envsubst '$PKGVER $PKGREL $SHA256SUM' < .SRCINFO.template > $GITDIR/.SRCINFO
|
||||
envsubst '$PKGVER $PKGREL $SHA256SUM' < PKGBUILD.template > $GITDIR/PKGBUILD
|
||||
|
||||
cd $GITDIR
|
||||
git config user.name "fluxcdbot"
|
||||
git config user.email "fluxcdbot@users.noreply.github.com"
|
||||
git add -A
|
||||
if [ -z "$(git status --porcelain)" ]; then
|
||||
echo "No changes."
|
||||
else
|
||||
git commit -m "Updated to version v${PKGVER} release ${PKGREL}"
|
||||
git push origin master
|
||||
fi
|
||||
19
.github/aur/flux-scm/.SRCINFO.template
vendored
Normal file
19
.github/aur/flux-scm/.SRCINFO.template
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
pkgbase = flux-scm
|
||||
pkgdesc = Open and extensible continuous delivery solution for Kubernetes
|
||||
pkgver = ${PKGVER}
|
||||
pkgrel = ${PKGREL}
|
||||
url = https://fluxcd.io/
|
||||
arch = x86_64
|
||||
arch = armv6h
|
||||
arch = armv7h
|
||||
arch = aarch64
|
||||
license = APACHE
|
||||
makedepends = go
|
||||
depends = glibc
|
||||
optdepends = kubectl
|
||||
provides = flux-bin
|
||||
conflicts = flux-bin
|
||||
source = git+https://github.com/fluxcd/flux2.git
|
||||
md5sums = SKIP
|
||||
|
||||
pkgname = flux-scm
|
||||
1
.github/aur/flux-scm/.gitignore
vendored
Normal file
1
.github/aur/flux-scm/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.pkg
|
||||
45
.github/aur/flux-scm/PKGBUILD.template
vendored
Normal file
45
.github/aur/flux-scm/PKGBUILD.template
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
# Maintainer: Aurel Canciu <aurelcanciu@gmail.com>
|
||||
# Maintainer: Hidde Beydals <hello@hidde.co>
|
||||
|
||||
pkgname=flux-scm
|
||||
pkgver=${PKGVER}
|
||||
pkgrel=${PKGREL}
|
||||
pkgdesc="Open and extensible continuous delivery solution for Kubernetes"
|
||||
url="https://fluxcd.io/"
|
||||
arch=("x86_64" "armv6h" "armv7h" "aarch64")
|
||||
license=("APACHE")
|
||||
provides=("flux-bin")
|
||||
conflicts=("flux-bin")
|
||||
depends=("glibc")
|
||||
makedepends=("go")
|
||||
optdepends=("kubectl")
|
||||
source=(
|
||||
"git+https://github.com/fluxcd/flux2.git"
|
||||
)
|
||||
md5sums=('SKIP')
|
||||
|
||||
pkgver() {
|
||||
cd "flux2"
|
||||
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "flux2"
|
||||
export CGO_LDFLAGS="$LDFLAGS"
|
||||
export CGO_CFLAGS="$CFLAGS"
|
||||
export CGO_CXXFLAGS="$CXXFLAGS"
|
||||
export CGO_CPPFLAGS="$CPPFLAGS"
|
||||
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
|
||||
go build -ldflags "-X main.VERSION=$pkgver" -o flux-bin ./cmd/flux
|
||||
}
|
||||
|
||||
check() {
|
||||
cd "flux2"
|
||||
make test
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "flux2"
|
||||
install -Dm755 flux-bin "$pkgdir/usr/bin/flux"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
}
|
||||
51
.github/aur/flux-scm/publish.sh
vendored
Executable file
51
.github/aur/flux-scm/publish.sh
vendored
Executable file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
|
||||
WD=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)
|
||||
PKGNAME=$(basename $WD)
|
||||
ROOT=${WD%/.github/aur/$PKGNAME}
|
||||
|
||||
LOCKFILE=/tmp/aur-$PKGNAME.lock
|
||||
exec 100>$LOCKFILE || exit 0
|
||||
flock -n 100 || exit 0
|
||||
trap "rm -f $LOCKFILE" EXIT
|
||||
|
||||
export VERSION=$1
|
||||
echo "Publishing to AUR as version ${VERSION}"
|
||||
|
||||
cd $WD
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
|
||||
|
||||
eval $(ssh-agent -s)
|
||||
ssh-add <(echo "$AUR_BOT_SSH_PRIVATE_KEY")
|
||||
|
||||
GITDIR=$(mktemp -d /tmp/aur-$PKGNAME-XXX)
|
||||
trap "rm -rf $GITDIR" EXIT
|
||||
git clone aur@aur.archlinux.org:$PKGNAME $GITDIR 2>&1
|
||||
|
||||
CURRENT_PKGVER=$(cat $GITDIR/.SRCINFO | grep pkgver | awk '{ print $3 }')
|
||||
CURRENT_PKGREL=$(cat $GITDIR/.SRCINFO | grep pkgrel | awk '{ print $3 }')
|
||||
|
||||
export PKGVER=${VERSION/-/}
|
||||
|
||||
if [[ "${CURRENT_PKGVER}" == "${PKGVER}" ]]; then
|
||||
export PKGREL=$((CURRENT_PKGREL+1))
|
||||
else
|
||||
export PKGREL=1
|
||||
fi
|
||||
|
||||
envsubst '$PKGVER $PKGREL' < .SRCINFO.template > $GITDIR/.SRCINFO
|
||||
envsubst '$PKGVER $PKGREL' < PKGBUILD.template > $GITDIR/PKGBUILD
|
||||
|
||||
cd $GITDIR
|
||||
git config user.name "fluxcdbot"
|
||||
git config user.email "fluxcdbot@users.noreply.github.com"
|
||||
git add -A
|
||||
if [ -z "$(git status --porcelain)" ]; then
|
||||
echo "No changes."
|
||||
else
|
||||
git commit -m "Updated to version v${PKGVER} release ${PKGREL}"
|
||||
git push origin master
|
||||
fi
|
||||
3
.github/workflows/bootstrap.yaml
vendored
3
.github/workflows/bootstrap.yaml
vendored
@@ -49,8 +49,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: uninstall
|
||||
run: |
|
||||
./bin/flux suspend kustomization flux-system
|
||||
./bin/flux uninstall --resources --crds -s
|
||||
./bin/flux uninstall --resources --crds -s --timeout=10m
|
||||
- name: bootstrap reinstall
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
|
||||
21
.github/workflows/e2e.yaml
vendored
21
.github/workflows/e2e.yaml
vendored
@@ -136,12 +136,31 @@ jobs:
|
||||
- name: flux delete source git
|
||||
run: |
|
||||
./bin/flux delete source git podinfo --silent
|
||||
- name: flux create tenant
|
||||
run: |
|
||||
./bin/flux create tenant dev-team --with-namespace=apps
|
||||
./bin/flux -n apps create source helm podinfo \
|
||||
--url https://stefanprodan.github.io/podinfo
|
||||
./bin/flux -n apps create hr podinfo-helm \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--chart-version="5.0.x" \
|
||||
--service-account=dev-team
|
||||
- name: flux2-kustomize-helm-example
|
||||
run: |
|
||||
./bin/flux create source git flux-system \
|
||||
--url=https://github.com/fluxcd/flux2-kustomize-helm-example \
|
||||
--branch=main
|
||||
./bin/flux create kustomization flux-system \
|
||||
--source=flux-system \
|
||||
--path=./clusters/staging
|
||||
kubectl -n flux-system wait kustomization/apps --for=condition=ready --timeout=2m
|
||||
- name: flux check
|
||||
run: |
|
||||
./bin/flux check
|
||||
- name: flux uninstall
|
||||
run: |
|
||||
./bin/flux uninstall --crds --silent
|
||||
./bin/flux uninstall --crds --silent --timeout=10m
|
||||
- name: Debug failure
|
||||
if: failure()
|
||||
run: |
|
||||
|
||||
22
.github/workflows/release.yaml
vendored
22
.github/workflows/release.yaml
vendored
@@ -59,24 +59,9 @@ jobs:
|
||||
|
||||
# create tarball
|
||||
cd ./output && tar -cvzf manifests.tar.gz $files
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: actions/create-release@latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
- name: Upload artifacts
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/manifests.tar.gz
|
||||
asset_name: manifests.tar.gz
|
||||
asset_content_type: application/gzip
|
||||
- name: Generate install manifest
|
||||
run: |
|
||||
kustomize build ./manifests/install > ./output/install.yaml
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v1
|
||||
with:
|
||||
@@ -85,3 +70,4 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
HOMEBREW_TAP_GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
|
||||
AUR_BOT_SSH_PRIVATE_KEY: ${{ secrets.AUR_BOT_SSH_PRIVATE_KEY }}
|
||||
|
||||
2
.github/workflows/update.yml
vendored
2
.github/workflows/update.yml
vendored
@@ -40,6 +40,8 @@ jobs:
|
||||
bump_version kustomize-controller
|
||||
bump_version source-controller
|
||||
bump_version notification-controller
|
||||
bump_version image-reflector-controller
|
||||
bump_version image-automation-controller
|
||||
|
||||
# add missing and remove unused modules
|
||||
go mod tidy
|
||||
|
||||
@@ -50,3 +50,23 @@ brews:
|
||||
type: optional
|
||||
test: |
|
||||
system "#{bin}/flux --version"
|
||||
publishers:
|
||||
- name: aur-pkg-bin
|
||||
env:
|
||||
- AUR_BOT_SSH_PRIVATE_KEY={{ .Env.AUR_BOT_SSH_PRIVATE_KEY }}
|
||||
cmd: |
|
||||
.github/aur/flux-bin/publish.sh {{ .Version }}
|
||||
- name: aur-pkg-scm
|
||||
env:
|
||||
- AUR_BOT_SSH_PRIVATE_KEY={{ .Env.AUR_BOT_SSH_PRIVATE_KEY }}
|
||||
cmd: |
|
||||
.github/aur/flux-scm/publish.sh {{ .Version }}
|
||||
- name: aur-pkg-go
|
||||
env:
|
||||
- AUR_BOT_SSH_PRIVATE_KEY={{ .Env.AUR_BOT_SSH_PRIVATE_KEY }}
|
||||
cmd: |
|
||||
.github/aur/flux-go/publish.sh {{ .Version }}
|
||||
release:
|
||||
extra_files:
|
||||
- glob: ./output/manifests.tar.gz
|
||||
- glob: ./output/install.yaml
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# Contributing
|
||||
|
||||
Flux is [Apache 2.0
|
||||
licensed](https://github.com/fluxcd/flux2/blob/main/LICENSE) and
|
||||
Flux is [Apache 2.0 licensed](https://github.com/fluxcd/flux2/blob/main/LICENSE) and
|
||||
accepts contributions via GitHub pull requests. This document outlines
|
||||
some of the conventions on to make it easier to get your contribution
|
||||
accepted.
|
||||
@@ -14,9 +13,18 @@ code.
|
||||
By contributing to this project you agree to the Developer Certificate of
|
||||
Origin (DCO). This document was created by the Linux Kernel community and is a
|
||||
simple statement that you, as a contributor, have the legal right to make the
|
||||
contribution. No action from you is required, but it's a good idea to see the
|
||||
[DCO](DCO) file for details before you start contributing code to FluxCD
|
||||
organization.
|
||||
contribution.
|
||||
|
||||
We require all commits to be signed. By signing off with your signature, you
|
||||
certify that you wrote the patch or otherwise have the right to contribute the
|
||||
material by the rules of the [DCO](DCO):
|
||||
|
||||
`Signed-off-by: Jane Doe <jane.doe@example.com>`
|
||||
|
||||
The signature must contain your real name
|
||||
(sorry, no pseudonyms or anonymous contributions)
|
||||
If your `user.name` and `user.email` are configured in your Git config,
|
||||
you can sign your commit automatically with `git commit -s`.
|
||||
|
||||
## Communications
|
||||
|
||||
|
||||
10
MAINTAINERS
10
MAINTAINERS
@@ -2,7 +2,17 @@ The maintainers are generally available in Slack at
|
||||
https://cloud-native.slack.com in #flux (https://cloud-native.slack.com/messages/CLAJ40HV3)
|
||||
(obtain an invitation at https://slack.cncf.io/).
|
||||
|
||||
These maintainers are shared with other Flux v2-related git
|
||||
repositories under https://github.com/fluxcd, as noted in their
|
||||
respective MAINTAINERS files.
|
||||
|
||||
For convenience, they are reflected in the GitHub team
|
||||
@fluxcd/flux2-maintainers -- if the list here changes, that team also
|
||||
should.
|
||||
|
||||
In alphabetical order:
|
||||
|
||||
Aurel Canciu, Sortlist <aurel@sortlist.com> (github: @relu, slack: relu)
|
||||
Hidde Beydals, Weaveworks <hidde@weave.works> (github: @hiddeco, slack: hidde)
|
||||
Philip Laine, Xenit <philip.laine@xenit.se> (github: @phillebaba, slack: phillebaba)
|
||||
Stefan Prodan, Weaveworks <stefan@weave.works> (github: @stefanprodan, slack: stefanprodan)
|
||||
|
||||
30
README.md
30
README.md
@@ -36,6 +36,15 @@ curl -s https://toolkit.fluxcd.io/install.sh | sudo bash
|
||||
. <(flux completion bash)
|
||||
```
|
||||
|
||||
Arch Linux (AUR) packages:
|
||||
|
||||
- [flux-bin](https://aur.archlinux.org/packages/flux-bin): install the latest
|
||||
stable version using a pre-build binary (recommended)
|
||||
- [flux-go](https://aur.archlinux.org/packages/flux-go): build the latest
|
||||
stable version from source code
|
||||
- [flux-scm](https://aur.archlinux.org/packages/flux-scm): build the latest
|
||||
(unstable) version from source code from our git `main` branch
|
||||
|
||||
Binaries for macOS, Windows and Linux AMD64/ARM are available to download on the
|
||||
[release page](https://github.com/fluxcd/flux2/releases).
|
||||
|
||||
@@ -98,19 +107,18 @@ Depending on what you want to do, some of the following bits might be your first
|
||||
- To be part of the conversation about Flux's development, [join the flux-dev mailing list](https://lists.cncf.io/g/cncf-flux-dev).
|
||||
- Check out [how to contribute](CONTRIBUTING.md) to the project
|
||||
|
||||
### Featured Talks
|
||||
### Upcoming Events
|
||||
- 11 Jan 2021 - [Helm + GitOps = ⚡️⚡️⚡️ with Scott Rigby](https://www.meetup.com/GitOps-Community/events/275348736/)
|
||||
|
||||
### Featured Talks
|
||||
- 14 Dec 2020 - [The Power of GitOps with Flux and Flagger (GitOps Hands-On) with Leigh Capili](https://youtu.be/cB7iXeNLteE)
|
||||
- 30 Nov 2020 - [The Power of GitOps with Flux 2 - Part 3 with Leigh Capili](https://youtu.be/N_K5g7o9JKg)
|
||||
- 24 Nov 2020 - [Flux CD v2 with GitOps Toolkit - Kubernetes Deployment and Sync Mechanism](https://youtu.be/R6OeIgb7lUI)
|
||||
- 02 Nov 2020 - [The Power of GitOps with Flux & GitOps Toolkit - Part 2 with Leigh Capili](https://youtu.be/fC2YCxQRUwU)
|
||||
- 28 Oct 2020 - [The Kubelist Podcast: Flux with Michael Bridgen](https://www.heavybit.com/library/podcasts/the-kubelist-podcast/ep-5-flux-with-michael-bridgen-of-weaveworks/)
|
||||
- 19 Oct 2020 - [The Power of GitOps with Flux & GitOps Toolkit - Part 1 with Leigh Capili](https://youtu.be/0v5bjysXTL8)
|
||||
- 12 Oct 2020 - [Rawkode Live: Introduction to GitOps Toolkit with Stefan Prodan](https://youtu.be/HqTzuOBP0eY)
|
||||
- 4 Sep 2020 - [KubeCon Europe: The road to Flux v2 and Progressive Delivery with Stefan Prodan & Hidde Beydals](https://youtu.be/8v94nUkXsxU)
|
||||
- 25 June 2020 - [Cloud Native Nordics: Introduction to GitOps & GitOps Toolkit with Alexis Richardson & Stefan Prodan](https://youtu.be/qQBtSkgl7tI)
|
||||
- 7 May 2020 - [GitOps Days - Community Special: GitOps Toolkit Experimentation with Stefan Prodan](https://youtu.be/WHzxunv4DKk?t=6521)
|
||||
- 04 Sep 2020 - [KubeCon Europe: The road to Flux v2 and Progressive Delivery with Stefan Prodan & Hidde Beydals](https://youtu.be/8v94nUkXsxU)
|
||||
- 25 Jun 2020 - [Cloud Native Nordics: Introduction to GitOps & GitOps Toolkit with Alexis Richardson & Stefan Prodan](https://youtu.be/qQBtSkgl7tI)
|
||||
|
||||
### Upcoming Events
|
||||
|
||||
- 2 Nov 2020 - [The Power of GitOps with Flux & GitOps Toolkit - Part 2 with Leigh Capili](https://www.meetup.com/GitOps-Community/events/273934676/)
|
||||
- 12-13 Nov 2020 - [GitOps Days EMEA](https://www.gitopsdays.com/) with talks and workshops on migrating to Flux v2 and Helm Controller
|
||||
- 19 Nov 2020 - [KubeCon NA: Progressive Delivery Techniques with Flagger and Flux v2 with Stefan Prodan](https://kccncna20.sched.com/event/1b04f8408b49976b843a5d0019cb8112)
|
||||
|
||||
We are looking forward to seeing you with us!
|
||||
We look forward to seeing you with us!
|
||||
|
||||
6
action/Dockerfile
Normal file
6
action/Dockerfile
Normal file
@@ -0,0 +1,6 @@
|
||||
FROM stefanprodan/alpine-base:latest
|
||||
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
89
action/README.md
Normal file
89
action/README.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Flux GitHub Action
|
||||
|
||||
Usage:
|
||||
|
||||
```yaml
|
||||
steps:
|
||||
- name: Setup Flux CLI
|
||||
uses: fluxcd/flux2/action@main
|
||||
- name: Run Flux commands
|
||||
run: flux -v
|
||||
```
|
||||
|
||||
This action places the `flux` binary inside your repository root under `bin/flux`.
|
||||
You should add `bin/flux` to your `.gitignore` file, as in the following example:
|
||||
|
||||
```gitignore
|
||||
# ignore flux binary
|
||||
bin/flux
|
||||
```
|
||||
|
||||
Note that this action can only be used on GitHub **Linux AMD64** runners.
|
||||
|
||||
### Automate Flux updates
|
||||
|
||||
Example workflow for updating Flux's components generated with `flux bootstrap --arch=amd64 --path=clusters/production`:
|
||||
|
||||
```yaml
|
||||
name: update-flux
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 * * * *"
|
||||
|
||||
jobs:
|
||||
components:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v2
|
||||
- name: Setup Flux CLI
|
||||
uses: fluxcd/flux2/action@main
|
||||
- name: Check for updates
|
||||
id: update
|
||||
run: |
|
||||
flux install --arch=amd64 \
|
||||
--export > ./clusters/production/flux-system/gotk-components.yaml
|
||||
|
||||
VERSION="$(flux -v)"
|
||||
echo "::set-output name=flux_version::$VERSION"
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v3
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: update-flux
|
||||
commit-message: Update to ${{ steps.update.outputs.flux_version }}
|
||||
title: Update to ${{ steps.update.outputs.flux_version }}
|
||||
body: |
|
||||
${{ steps.update.outputs.flux_version }}
|
||||
```
|
||||
|
||||
### End-to-end testing
|
||||
|
||||
Example workflow for running Flux in Kubernetes Kind:
|
||||
|
||||
```yaml
|
||||
name: e2e
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
kubernetes:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Setup Flux CLI
|
||||
uses: fluxcd/flux2/action@main
|
||||
- name: Setup Kubernetes Kind
|
||||
uses: engineerd/setup-kind@v0.5.0
|
||||
- name: Install Flux in Kubernetes Kind
|
||||
run: flux install
|
||||
```
|
||||
|
||||
A complete e2e testing workflow is available here
|
||||
[flux2-kustomize-helm-example](https://github.com/fluxcd/flux2-kustomize-helm-example/blob/main/.github/workflows/e2e.yaml)
|
||||
15
action/action.yml
Normal file
15
action/action.yml
Normal file
@@ -0,0 +1,15 @@
|
||||
name: 'kustomize'
|
||||
description: 'A GitHub Action for running Flux commands'
|
||||
author: 'Flux project'
|
||||
branding:
|
||||
icon: 'command'
|
||||
color: 'blue'
|
||||
inputs:
|
||||
version:
|
||||
description: 'strict semver'
|
||||
required: false
|
||||
runs:
|
||||
using: 'docker'
|
||||
image: 'Dockerfile'
|
||||
args:
|
||||
- ${{ inputs.version }}
|
||||
40
action/entrypoint.sh
Executable file
40
action/entrypoint.sh
Executable file
@@ -0,0 +1,40 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Copyright 2020 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.
|
||||
|
||||
set -e
|
||||
|
||||
VERSION=$1
|
||||
|
||||
if [ -z $VERSION ]; then
|
||||
# Find latest release if no version is specified
|
||||
VERSION=$(curl https://api.github.com/repos/fluxcd/flux2/releases/latest -sL | grep tag_name | sed -E 's/.*"([^"]+)".*/\1/' | cut -c 2-)
|
||||
fi
|
||||
|
||||
# Download linux binary
|
||||
BIN_URL="https://github.com/fluxcd/flux2/releases/download/v${VERSION}/flux_${VERSION}_linux_amd64.tar.gz"
|
||||
curl -sL $BIN_URL | tar xz
|
||||
|
||||
# Copy binary to GitHub runner
|
||||
mkdir -p $GITHUB_WORKSPACE/bin
|
||||
mv ./flux $GITHUB_WORKSPACE/bin
|
||||
chmod +x $GITHUB_WORKSPACE/bin/flux
|
||||
|
||||
# Print version
|
||||
$GITHUB_WORKSPACE/bin/flux -v
|
||||
|
||||
# Add binary to GitHub runner path
|
||||
echo "$GITHUB_WORKSPACE/bin" >> $GITHUB_PATH
|
||||
echo "$RUNNER_WORKSPACE/$(basename $GITHUB_REPOSITORY)/bin" >> $GITHUB_PATH
|
||||
@@ -47,7 +47,8 @@ var bootstrapCmd = &cobra.Command{
|
||||
|
||||
var (
|
||||
bootstrapVersion string
|
||||
bootstrapComponents []string
|
||||
bootstrapDefaultComponents []string
|
||||
bootstrapExtraComponents []string
|
||||
bootstrapRegistry string
|
||||
bootstrapImagePullSecret string
|
||||
bootstrapBranch string
|
||||
@@ -58,6 +59,7 @@ var (
|
||||
bootstrapLogLevel = flags.LogLevel(defaults.LogLevel)
|
||||
bootstrapRequiredComponents = []string{"source-controller", "kustomize-controller"}
|
||||
bootstrapTokenAuth bool
|
||||
bootstrapClusterDomain string
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -67,8 +69,10 @@ const (
|
||||
func init() {
|
||||
bootstrapCmd.PersistentFlags().StringVarP(&bootstrapVersion, "version", "v", defaults.Version,
|
||||
"toolkit version")
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapComponents, "components", defaults.Components,
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapDefaultComponents, "components", defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapExtraComponents, "components-extra", nil,
|
||||
"list of components in addition to those supplied or defaulted, accepts comma-separated values")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapRegistry, "registry", "ghcr.io/fluxcd",
|
||||
"container registry where the toolkit images are published")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapImagePullSecret, "image-pull-secret", "",
|
||||
@@ -84,17 +88,27 @@ func init() {
|
||||
"when enabled, the personal access token will be used instead of SSH deploy key")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapLogLevel, "log-level", bootstrapLogLevel.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapManifestsPath, "manifests", "", "path to the manifest directory")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapClusterDomain, "cluster-domain", defaults.ClusterDomain, "internal cluster domain")
|
||||
bootstrapCmd.PersistentFlags().MarkHidden("manifests")
|
||||
rootCmd.AddCommand(bootstrapCmd)
|
||||
}
|
||||
|
||||
func bootstrapComponents() []string {
|
||||
return append(bootstrapDefaultComponents, bootstrapExtraComponents...)
|
||||
}
|
||||
|
||||
func bootstrapValidate() error {
|
||||
components := bootstrapComponents()
|
||||
for _, component := range bootstrapRequiredComponents {
|
||||
if !utils.ContainsItemString(bootstrapComponents, component) {
|
||||
if !utils.ContainsItemString(components, component) {
|
||||
return fmt.Errorf("component %s is required", component)
|
||||
}
|
||||
}
|
||||
|
||||
if err := utils.ValidateComponents(components); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -103,7 +117,7 @@ func generateInstallManifests(targetPath, namespace, tmpDir string, localManifes
|
||||
BaseURL: localManifests,
|
||||
Version: bootstrapVersion,
|
||||
Namespace: namespace,
|
||||
Components: bootstrapComponents,
|
||||
Components: bootstrapComponents(),
|
||||
Registry: bootstrapRegistry,
|
||||
ImagePullSecret: bootstrapImagePullSecret,
|
||||
Arch: bootstrapArch.String(),
|
||||
@@ -114,6 +128,7 @@ func generateInstallManifests(targetPath, namespace, tmpDir string, localManifes
|
||||
ManifestFile: defaults.ManifestFile,
|
||||
Timeout: timeout,
|
||||
TargetPath: targetPath,
|
||||
ClusterDomain: bootstrapClusterDomain,
|
||||
}
|
||||
|
||||
if localManifests == "" {
|
||||
@@ -125,30 +140,29 @@ func generateInstallManifests(targetPath, namespace, tmpDir string, localManifes
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
|
||||
if filePath, err := output.WriteFile(tmpDir); err != nil {
|
||||
filePath, err := output.WriteFile(tmpDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
} else {
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
func applyInstallManifests(ctx context.Context, manifestPath string, components []string) error {
|
||||
kubectlArgs := []string{"apply", "-f", manifestPath}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubectlArgs...); err != nil {
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
for _, deployment := range components {
|
||||
kubectlArgs = []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubectlArgs...); err != nil {
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSyncManifests(url, branch, name, namespace, targetPath, tmpDir string, interval time.Duration) error {
|
||||
func generateSyncManifests(url, branch, name, namespace, targetPath, tmpDir string, interval time.Duration) (string, error) {
|
||||
opts := sync.Options{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
@@ -161,23 +175,23 @@ func generateSyncManifests(url, branch, name, namespace, targetPath, tmpDir stri
|
||||
|
||||
manifest, err := sync.Generate(opts)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generating install manifests failed: %w", err)
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
|
||||
if _, err := manifest.WriteFile(tmpDir); err != nil {
|
||||
return err
|
||||
output, err := manifest.WriteFile(tmpDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if err := utils.GenerateKustomizationYaml(filepath.Join(tmpDir, targetPath, namespace)); err != nil {
|
||||
return err
|
||||
outputDir := filepath.Dir(output)
|
||||
if err := utils.GenerateKustomizationYaml(outputDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return nil
|
||||
return outputDir, nil
|
||||
}
|
||||
|
||||
func applySyncManifests(ctx context.Context, kubeClient client.Client, name, namespace, targetPath, tmpDir string) error {
|
||||
kubectlArgs := []string{"apply", "-k", filepath.Join(tmpDir, targetPath, namespace)}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeStderrOS, kubectlArgs...); err != nil {
|
||||
func applySyncManifests(ctx context.Context, kubeClient client.Client, name, namespace, manifestsPath string) error {
|
||||
kubectlArgs := []string{"apply", "-k", manifestsPath}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeStderrOS, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -225,7 +239,7 @@ func shouldCreateDeployKey(ctx context.Context, kubeClient client.Client, namesp
|
||||
}
|
||||
|
||||
func generateDeployKey(ctx context.Context, kubeClient client.Client, url *url.URL, namespace string) (string, error) {
|
||||
pair, err := generateKeyPair(ctx)
|
||||
pair, err := generateKeyPair(ctx, sourceGitKeyAlgorithm, sourceGitRSABits, sourceGitECDSACurve)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -252,3 +266,20 @@ func generateDeployKey(ctx context.Context, kubeClient client.Client, url *url.U
|
||||
|
||||
return string(pair.PublicKey), nil
|
||||
}
|
||||
|
||||
func checkIfBootstrapPathDiffers(ctx context.Context, kubeClient client.Client, namespace string, path string) (string, bool) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Name: namespace,
|
||||
Namespace: namespace,
|
||||
}
|
||||
var fluxSystemKustomization kustomizev1.Kustomization
|
||||
err := kubeClient.Get(ctx, namespacedName, &fluxSystemKustomization)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if fluxSystemKustomization.Spec.Path == path {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return fluxSystemKustomization.Spec.Path, true
|
||||
}
|
||||
|
||||
@@ -23,14 +23,17 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/git"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var bootstrapGitHubCmd = &cobra.Command{
|
||||
@@ -75,7 +78,7 @@ var (
|
||||
ghPersonal bool
|
||||
ghPrivate bool
|
||||
ghHostname string
|
||||
ghPath string
|
||||
ghPath flags.SafeRelativePath
|
||||
ghTeams []string
|
||||
ghDelete bool
|
||||
ghSSHHostname string
|
||||
@@ -94,7 +97,7 @@ func init() {
|
||||
bootstrapGitHubCmd.Flags().DurationVar(&ghInterval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&ghHostname, "hostname", git.GitHubDefaultHostname, "GitHub hostname")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&ghSSHHostname, "ssh-hostname", "", "GitHub SSH hostname, to be used when the SSH host differs from the HTTPS one")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&ghPath, "path", "", "repository path, when specified the cluster sync will be scoped to this path")
|
||||
bootstrapGitHubCmd.Flags().Var(&ghPath, "path", "path relative to the repository root, when specified the cluster sync will be scoped to this path")
|
||||
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&ghDelete, "delete", false, "delete repository (used for testing only)")
|
||||
bootstrapGitHubCmd.Flags().MarkHidden("delete")
|
||||
@@ -112,6 +115,20 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
usedPath, bootstrapPathDiffers := checkIfBootstrapPathDiffers(ctx, kubeClient, namespace, filepath.ToSlash(ghPath.String()))
|
||||
|
||||
if bootstrapPathDiffers {
|
||||
return fmt.Errorf("cluster already bootstrapped to %v path", usedPath)
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(ghRepository, ghOwner, ghHostname, ghToken, "flux", ghOwner+"@users.noreply.github.com")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -132,9 +149,6 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
if ghDelete {
|
||||
if err := provider.DeleteRepository(ctx, repository); err != nil {
|
||||
return err
|
||||
@@ -174,13 +188,13 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
manifest, err := generateInstallManifests(ghPath, namespace, tmpDir, bootstrapManifestsPath)
|
||||
installManifest, err := generateInstallManifests(ghPath.String(), namespace, tmpDir, bootstrapManifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// stage install manifests
|
||||
changed, err = repository.Commit(ctx, path.Join(ghPath, namespace), "Add manifests")
|
||||
changed, err = repository.Commit(ctx, path.Join(ghPath.String(), namespace), "Add manifests")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -195,18 +209,13 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
logger.Successf("components are up to date")
|
||||
}
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// determine if repo synchronization is working
|
||||
isInstall := shouldInstallManifests(ctx, kubeClient, namespace)
|
||||
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
if err := applyInstallManifests(ctx, manifest, bootstrapComponents); err != nil {
|
||||
if err := applyInstallManifests(ctx, installManifest, bootstrapComponents()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
@@ -259,12 +268,13 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// configure repo synchronization
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repoURL, bootstrapBranch, namespace, namespace, ghPath, tmpDir, ghInterval); err != nil {
|
||||
syncManifests, err := generateSyncManifests(repoURL, bootstrapBranch, namespace, namespace, filepath.ToSlash(ghPath.String()), tmpDir, ghInterval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(ghPath, namespace), "Add manifests"); err != nil {
|
||||
if changed, err = repository.Commit(ctx, path.Join(ghPath.String(), namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
@@ -275,7 +285,7 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, ghPath, tmpDir); err != nil {
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, syncManifests); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -23,14 +23,18 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/git"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var bootstrapGitLabCmd = &cobra.Command{
|
||||
@@ -65,6 +69,10 @@ the bootstrap command will perform an upgrade if needed.`,
|
||||
RunE: bootstrapGitLabCmdRun,
|
||||
}
|
||||
|
||||
const (
|
||||
gitlabProjectRegex = `\A[[:alnum:]\x{00A9}-\x{1f9ff}_][[:alnum:]\p{Pd}\x{00A9}-\x{1f9ff}_\.]*\z`
|
||||
)
|
||||
|
||||
var (
|
||||
glOwner string
|
||||
glRepository string
|
||||
@@ -73,7 +81,7 @@ var (
|
||||
glPrivate bool
|
||||
glHostname string
|
||||
glSSHHostname string
|
||||
glPath string
|
||||
glPath flags.SafeRelativePath
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -84,7 +92,7 @@ func init() {
|
||||
bootstrapGitLabCmd.Flags().DurationVar(&glInterval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glHostname, "hostname", git.GitLabDefaultHostname, "GitLab hostname")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glSSHHostname, "ssh-hostname", "", "GitLab SSH hostname, to be used when the SSH host differs from the HTTPS one")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glPath, "path", "", "repository path, when specified the cluster sync will be scoped to this path")
|
||||
bootstrapGitLabCmd.Flags().Var(&glPath, "path", "path relative to the repository root, when specified the cluster sync will be scoped to this path")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitLabCmd)
|
||||
}
|
||||
@@ -95,10 +103,32 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("%s environment variable not found", git.GitLabTokenName)
|
||||
}
|
||||
|
||||
projectNameIsValid, err := regexp.MatchString(gitlabProjectRegex, glRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !projectNameIsValid {
|
||||
return fmt.Errorf("%s is an invalid project name for gitlab.\nIt can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'.", glRepository)
|
||||
}
|
||||
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
usedPath, bootstrapPathDiffers := checkIfBootstrapPathDiffers(ctx, kubeClient, namespace, filepath.ToSlash(glPath.String()))
|
||||
|
||||
if bootstrapPathDiffers {
|
||||
return fmt.Errorf("cluster already bootstrapped to %v path", usedPath)
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(glRepository, glOwner, glHostname, glToken, "flux", glOwner+"@users.noreply.gitlab.com")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -113,20 +143,12 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
IsPersonal: glPersonal,
|
||||
}
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
// create GitLab project if doesn't exists
|
||||
logger.Actionf("connecting to %s", glHostname)
|
||||
changed, err := provider.CreateRepository(ctx, repository)
|
||||
@@ -145,13 +167,13 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
manifest, err := generateInstallManifests(glPath, namespace, tmpDir, bootstrapManifestsPath)
|
||||
installManifest, err := generateInstallManifests(glPath.String(), namespace, tmpDir, bootstrapManifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// stage install manifests
|
||||
changed, err = repository.Commit(ctx, path.Join(glPath, namespace), "Add manifests")
|
||||
changed, err = repository.Commit(ctx, path.Join(glPath.String(), namespace), "Add manifests")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -172,7 +194,7 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
if err := applyInstallManifests(ctx, manifest, bootstrapComponents); err != nil {
|
||||
if err := applyInstallManifests(ctx, installManifest, bootstrapComponents()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
@@ -225,12 +247,13 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// configure repo synchronization
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repoURL, bootstrapBranch, namespace, namespace, glPath, tmpDir, glInterval); err != nil {
|
||||
syncManifests, err := generateSyncManifests(repoURL, bootstrapBranch, namespace, namespace, filepath.ToSlash(glPath.String()), tmpDir, glInterval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(glPath, namespace), "Add manifests"); err != nil {
|
||||
if changed, err = repository.Commit(ctx, path.Join(glPath.String(), namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
@@ -241,7 +264,7 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, glPath, tmpDir); err != nil {
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, syncManifests); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
)
|
||||
|
||||
var checkCmd = &cobra.Command{
|
||||
@@ -104,7 +103,7 @@ func kubectlCheck(ctx context.Context, version string) bool {
|
||||
}
|
||||
|
||||
kubectlArgs := []string{"version", "--client", "--output", "json"}
|
||||
output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubectlArgs...)
|
||||
output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubeconfig, kubecontext, kubectlArgs...)
|
||||
if err != nil {
|
||||
logger.Failuref("kubectl version can't be determined")
|
||||
return false
|
||||
@@ -133,7 +132,7 @@ func kubectlCheck(ctx context.Context, version string) bool {
|
||||
}
|
||||
|
||||
func kubernetesCheck(version string) bool {
|
||||
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
|
||||
cfg, err := utils.KubeConfig(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
logger.Failuref("Kubernetes client initialization failed: %s", err.Error())
|
||||
return false
|
||||
@@ -174,14 +173,14 @@ func componentsCheck() bool {
|
||||
ok := true
|
||||
for _, deployment := range checkComponents {
|
||||
kubectlArgs := []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubectlArgs...); err != nil {
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
logger.Failuref("%s: %s", deployment, strings.TrimSuffix(output, "\n"))
|
||||
ok = false
|
||||
} else {
|
||||
logger.Successf("%s is healthy", deployment)
|
||||
}
|
||||
kubectlArgs = []string{"-n", namespace, "get", "deployment", deployment, "-o", "jsonpath=\"{..image}\""}
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubectlArgs...); err == nil {
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubeconfig, kubecontext, kubectlArgs...); err == nil {
|
||||
logger.Actionf(strings.TrimPrefix(strings.TrimSuffix(output, "\""), "\""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ command -v flux >/dev/null && . <(flux completion zsh) && compdef _flux flux
|
||||
or write a cached file in one of the completion directories in your ${fpath}:
|
||||
|
||||
echo "${fpath// /\n}" | grep -i completion
|
||||
flux completions zsh > _flux
|
||||
flux completion zsh > _flux
|
||||
|
||||
mv _flux ~/.oh-my-zsh/completions # oh-my-zsh
|
||||
mv _flux ~/.zprezto/modules/completion/external/src/ # zprezto
|
||||
|
||||
@@ -17,13 +17,19 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var createCmd = &cobra.Command{
|
||||
@@ -46,6 +52,78 @@ func init() {
|
||||
rootCmd.AddCommand(createCmd)
|
||||
}
|
||||
|
||||
// upsertable is an interface for values that can be used in `upsert`.
|
||||
type upsertable interface {
|
||||
adapter
|
||||
named
|
||||
}
|
||||
|
||||
// upsert updates or inserts an object. Instead of providing the
|
||||
// object itself, you provide a named (as in Name and Namespace)
|
||||
// template value, and a mutate function which sets the values you
|
||||
// want to update. The mutate function is nullary -- you mutate a
|
||||
// value in the closure, e.g., by doing this:
|
||||
//
|
||||
// var existing Value
|
||||
// existing.Name = name
|
||||
// existing.Namespace = ns
|
||||
// upsert(ctx, client, valueAdapter{&value}, func() error {
|
||||
// value.Spec = onePreparedEarlier
|
||||
// })
|
||||
func (names apiType) upsert(ctx context.Context, kubeClient client.Client, object upsertable, mutate func() error) (types.NamespacedName, error) {
|
||||
nsname := types.NamespacedName{
|
||||
Namespace: object.GetNamespace(),
|
||||
Name: object.GetName(),
|
||||
}
|
||||
|
||||
op, err := controllerutil.CreateOrUpdate(ctx, kubeClient, object.asRuntimeObject(), mutate)
|
||||
if err != nil {
|
||||
return nsname, err
|
||||
}
|
||||
|
||||
switch op {
|
||||
case controllerutil.OperationResultCreated:
|
||||
logger.Successf("%s created", names.kind)
|
||||
case controllerutil.OperationResultUpdated:
|
||||
logger.Successf("%s updated", names.kind)
|
||||
}
|
||||
return nsname, nil
|
||||
}
|
||||
|
||||
type upsertWaitable interface {
|
||||
upsertable
|
||||
statusable
|
||||
}
|
||||
|
||||
// upsertAndWait encodes the pattern of creating or updating a
|
||||
// resource, then waiting for it to reconcile. See the note on
|
||||
// `upsert` for how to work with the `mutate` argument.
|
||||
func (names apiType) upsertAndWait(object upsertWaitable, mutate func() error) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext) // NB globals
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Generatef("generating %s", names.kind)
|
||||
logger.Actionf("applying %s", names.kind)
|
||||
|
||||
namespacedName, err := imageRepositoryType.upsert(ctx, kubeClient, object, mutate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for %s reconciliation", names.kind)
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isReady(ctx, kubeClient, namespacedName, object)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s reconciliation completed", names.kind)
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseLabels() (map[string]string, error) {
|
||||
result := make(map[string]string)
|
||||
for _, label := range labels {
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -179,11 +180,11 @@ func isAlertReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -177,11 +178,11 @@ func isAlertProviderReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -67,6 +68,14 @@ var createHelmReleaseCmd = &cobra.Command{
|
||||
--chart=podinfo \
|
||||
--values=./my-values.yaml
|
||||
|
||||
# Create a HelmRelease with values from a Kubernetes secret
|
||||
kubectl -n app create secret generic my-secret-values \
|
||||
--from-file=values.yaml=/path/to/my-secret-values.yaml
|
||||
flux -n app create hr podinfo \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--values-from=Secret/my-secret-values
|
||||
|
||||
# Create a HelmRelease with a custom release name
|
||||
flux create hr podinfo \
|
||||
--release-name=podinfo-dev
|
||||
@@ -97,6 +106,8 @@ var (
|
||||
hrChartVersion string
|
||||
hrTargetNamespace string
|
||||
hrValuesFile string
|
||||
hrValuesFrom flags.HelmReleaseValuesFrom
|
||||
hrSAName string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -106,7 +117,9 @@ func init() {
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrChartVersion, "chart-version", "", "Helm chart version, accepts a semver range (ignored for charts from GitRepository sources)")
|
||||
createHelmReleaseCmd.Flags().StringArrayVar(&hrDependsOn, "depends-on", nil, "HelmReleases that must be ready before this release can be installed, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrTargetNamespace, "target-namespace", "", "namespace to install this release, defaults to the HelmRelease namespace")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrSAName, "service-account", "", "the name of the service account to impersonate when reconciling this HelmRelease")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrValuesFile, "values", "", "local path to the values.yaml file")
|
||||
createHelmReleaseCmd.Flags().Var(&hrValuesFrom, "values-from", hrValuesFrom.Description())
|
||||
createCmd.AddCommand(createHelmReleaseCmd)
|
||||
}
|
||||
|
||||
@@ -156,6 +169,10 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
},
|
||||
}
|
||||
|
||||
if hrSAName != "" {
|
||||
helmRelease.Spec.ServiceAccountName = hrSAName
|
||||
}
|
||||
|
||||
if hrValuesFile != "" {
|
||||
data, err := ioutil.ReadFile(hrValuesFile)
|
||||
if err != nil {
|
||||
@@ -170,6 +187,13 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
helmRelease.Spec.Values = &apiextensionsv1.JSON{Raw: json}
|
||||
}
|
||||
|
||||
if hrValuesFrom.String() != "" {
|
||||
helmRelease.Spec.ValuesFrom = []helmv2.ValuesReference{{
|
||||
Kind: hrValuesFrom.Kind,
|
||||
Name: hrValuesFrom.Name,
|
||||
}}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportHelmRelease(helmRelease)
|
||||
}
|
||||
@@ -243,6 +267,6 @@ func isHelmReleaseReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return meta.HasReadyCondition(helmRelease.Status.Conditions), nil
|
||||
return apimeta.IsStatusConditionTrue(helmRelease.Status.Conditions, meta.ReadyCondition), nil
|
||||
}
|
||||
}
|
||||
|
||||
38
cmd/flux/create_image.go
Normal file
38
cmd/flux/create_image.go
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const createImageLong = `
|
||||
The create image sub-commands work with image automation objects; that is,
|
||||
object controlling updates to git based on e.g., new container images
|
||||
being available.`
|
||||
|
||||
var createImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Create or update resources dealing with image automation",
|
||||
Long: strings.TrimSpace(createImageLong),
|
||||
}
|
||||
|
||||
func init() {
|
||||
createCmd.AddCommand(createImageCmd)
|
||||
}
|
||||
110
cmd/flux/create_image_policy.go
Normal file
110
cmd/flux/create_image_policy.go
Normal file
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var createImagePolicyCmd = &cobra.Command{
|
||||
Use: "policy <name>",
|
||||
Short: "Create or update an ImagePolicy object",
|
||||
Long: `The create image policy command generates an ImagePolicy resource.
|
||||
An ImagePolicy object calculates a "latest image" given an image
|
||||
repository and a policy, e.g., semver.
|
||||
|
||||
The image that sorts highest according to the policy is recorded in
|
||||
the status of the object.`,
|
||||
RunE: createImagePolicyRun}
|
||||
|
||||
type imagePolicyFlags struct {
|
||||
imageRef string
|
||||
semver string
|
||||
}
|
||||
|
||||
var imagePolicyArgs = imagePolicyFlags{}
|
||||
|
||||
func init() {
|
||||
flags := createImagePolicyCmd.Flags()
|
||||
flags.StringVar(&imagePolicyArgs.imageRef, "image-ref", "", "the name of an image repository object")
|
||||
flags.StringVar(&imagePolicyArgs.semver, "semver", "", "a semver range to apply to tags; e.g., '1.x'")
|
||||
|
||||
createImageCmd.AddCommand(createImagePolicyCmd)
|
||||
}
|
||||
|
||||
// getObservedGeneration is implemented here, since it's not
|
||||
// (presently) needed elsewhere.
|
||||
func (obj imagePolicyAdapter) getObservedGeneration() int64 {
|
||||
return obj.ImagePolicy.Status.ObservedGeneration
|
||||
}
|
||||
|
||||
func createImagePolicyRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("ImagePolicy name is required")
|
||||
}
|
||||
objectName := args[0]
|
||||
|
||||
if imagePolicyArgs.imageRef == "" {
|
||||
return fmt.Errorf("the name of an ImageRepository in the namespace is required (--image-ref)")
|
||||
}
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var policy = imagev1.ImagePolicy{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: objectName,
|
||||
Namespace: namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: imagev1.ImagePolicySpec{
|
||||
ImageRepositoryRef: corev1.LocalObjectReference{
|
||||
Name: imagePolicyArgs.imageRef,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
switch {
|
||||
case imagePolicyArgs.semver != "":
|
||||
policy.Spec.Policy.SemVer = &imagev1.SemVerPolicy{
|
||||
Range: imagePolicyArgs.semver,
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("a policy must be provided with --semver")
|
||||
}
|
||||
|
||||
if export {
|
||||
return printExport(exportImagePolicy(&policy))
|
||||
}
|
||||
|
||||
var existing imagev1.ImagePolicy
|
||||
copyName(&existing, &policy)
|
||||
err = imagePolicyType.upsertAndWait(imagePolicyAdapter{&existing}, func() error {
|
||||
existing.Spec = policy.Spec
|
||||
existing.SetLabels(policy.Labels)
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
110
cmd/flux/create_image_repository.go
Normal file
110
cmd/flux/create_image_repository.go
Normal file
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-containerregistry/pkg/name"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var createImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository <name>",
|
||||
Short: "Create or update an ImageRepository object",
|
||||
Long: `The create image repository command generates an ImageRepository resource.
|
||||
An ImageRepository object specifies an image repository to scan.`,
|
||||
RunE: createImageRepositoryRun,
|
||||
}
|
||||
|
||||
type imageRepoFlags struct {
|
||||
image string
|
||||
secretRef string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var imageRepoArgs = imageRepoFlags{}
|
||||
|
||||
func init() {
|
||||
flags := createImageRepositoryCmd.Flags()
|
||||
flags.StringVar(&imageRepoArgs.image, "image", "", "the image repository to scan; e.g., library/alpine")
|
||||
flags.StringVar(&imageRepoArgs.secretRef, "secret-ref", "", "the name of a docker-registry secret to use for credentials")
|
||||
// NB there is already a --timeout in the global flags, for
|
||||
// controlling timeout on operations while e.g., creating objects.
|
||||
flags.DurationVar(&imageRepoArgs.timeout, "scan-timeout", 0, "a timeout for scanning; this defaults to the interval if not set")
|
||||
|
||||
createImageCmd.AddCommand(createImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func createImageRepositoryRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("ImageRepository name is required")
|
||||
}
|
||||
objectName := args[0]
|
||||
|
||||
if imageRepoArgs.image == "" {
|
||||
return fmt.Errorf("an image repository (--image) is required")
|
||||
}
|
||||
|
||||
if _, err := name.NewRepository(imageRepoArgs.image); err != nil {
|
||||
return fmt.Errorf("unable to parse image value: %w", err)
|
||||
}
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var repo = imagev1.ImageRepository{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: objectName,
|
||||
Namespace: namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: imagev1.ImageRepositorySpec{
|
||||
Image: imageRepoArgs.image,
|
||||
Interval: metav1.Duration{Duration: interval},
|
||||
},
|
||||
}
|
||||
if imageRepoArgs.timeout != 0 {
|
||||
repo.Spec.Timeout = &metav1.Duration{Duration: imageRepoArgs.timeout}
|
||||
}
|
||||
if imageRepoArgs.secretRef != "" {
|
||||
repo.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: imageRepoArgs.secretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if export {
|
||||
return printExport(exportImageRepository(&repo))
|
||||
}
|
||||
|
||||
// a temp value for use with the rest
|
||||
var existing imagev1.ImageRepository
|
||||
copyName(&existing, &repo)
|
||||
err = imageRepositoryType.upsertAndWait(imageRepositoryAdapter{&existing}, func() error {
|
||||
existing.Spec = repo.Spec
|
||||
existing.Labels = repo.Labels
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
113
cmd/flux/create_image_updateauto.go
Normal file
113
cmd/flux/create_image_updateauto.go
Normal file
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var createImageUpdateCmd = &cobra.Command{
|
||||
Use: "update <name>",
|
||||
Short: "Create or update an ImageUpdateAutomation object",
|
||||
Long: `The create image update command generates an ImageUpdateAutomation resource.
|
||||
An ImageUpdateAutomation object specifies an automated update to images
|
||||
mentioned in YAMLs in a git repository.`,
|
||||
RunE: createImageUpdateRun,
|
||||
}
|
||||
|
||||
type imageUpdateFlags struct {
|
||||
// git checkout spec
|
||||
gitRepoRef string
|
||||
branch string
|
||||
// commit spec
|
||||
commitTemplate string
|
||||
authorName string
|
||||
authorEmail string
|
||||
}
|
||||
|
||||
var imageUpdateArgs = imageUpdateFlags{}
|
||||
|
||||
func init() {
|
||||
flags := createImageUpdateCmd.Flags()
|
||||
flags.StringVar(&imageUpdateArgs.gitRepoRef, "git-repo-ref", "", "the name of a GitRepository resource with details of the upstream git repository")
|
||||
flags.StringVar(&imageUpdateArgs.branch, "branch", "", "the branch to push commits to")
|
||||
flags.StringVar(&imageUpdateArgs.commitTemplate, "commit-template", "", "a template for commit messages")
|
||||
flags.StringVar(&imageUpdateArgs.authorName, "author-name", "", "the name to use for commit author")
|
||||
flags.StringVar(&imageUpdateArgs.authorEmail, "author-email", "", "the email to use for commit author")
|
||||
|
||||
createImageCmd.AddCommand(createImageUpdateCmd)
|
||||
}
|
||||
|
||||
func createImageUpdateRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("ImageUpdateAutomation name is required")
|
||||
}
|
||||
objectName := args[0]
|
||||
|
||||
if imageUpdateArgs.gitRepoRef == "" {
|
||||
return fmt.Errorf("a reference to a GitRepository is required (--git-repo-ref)")
|
||||
}
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var update = autov1.ImageUpdateAutomation{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: objectName,
|
||||
Namespace: namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: autov1.ImageUpdateAutomationSpec{
|
||||
Checkout: autov1.GitCheckoutSpec{
|
||||
GitRepositoryRef: corev1.LocalObjectReference{
|
||||
Name: imageUpdateArgs.gitRepoRef,
|
||||
},
|
||||
Branch: imageUpdateArgs.branch,
|
||||
},
|
||||
Interval: metav1.Duration{Duration: interval},
|
||||
Update: autov1.UpdateStrategy{
|
||||
Setters: &autov1.SettersStrategy{},
|
||||
},
|
||||
Commit: autov1.CommitSpec{
|
||||
AuthorName: imageUpdateArgs.authorName,
|
||||
AuthorEmail: imageUpdateArgs.authorEmail,
|
||||
MessageTemplate: imageUpdateArgs.commitTemplate,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if export {
|
||||
return printExport(exportImageUpdate(&update))
|
||||
}
|
||||
|
||||
var existing autov1.ImageUpdateAutomation
|
||||
copyName(&existing, &update)
|
||||
err = imageUpdateAutomationType.upsertAndWait(imageUpdateAutomationAdapter{&existing}, func() error {
|
||||
existing.Spec = update.Spec
|
||||
existing.Labels = update.Labels
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -73,14 +74,13 @@ var createKsCmd = &cobra.Command{
|
||||
|
||||
var (
|
||||
ksSource flags.KustomizationSource
|
||||
ksPath string
|
||||
ksPath flags.SafeRelativePath = "./"
|
||||
ksPrune bool
|
||||
ksDependsOn []string
|
||||
ksValidation string
|
||||
ksHealthCheck []string
|
||||
ksHealthTimeout time.Duration
|
||||
ksSAName string
|
||||
ksSANamespace string
|
||||
ksDecryptionProvider flags.DecryptionProvider
|
||||
ksDecryptionSecret string
|
||||
ksTargetNamespace string
|
||||
@@ -88,14 +88,13 @@ var (
|
||||
|
||||
func init() {
|
||||
createKsCmd.Flags().Var(&ksSource, "source", ksSource.Description())
|
||||
createKsCmd.Flags().StringVar(&ksPath, "path", "./", "path to the directory containing the Kustomization file")
|
||||
createKsCmd.Flags().Var(&ksPath, "path", "path to the directory containing a kustomization.yaml file")
|
||||
createKsCmd.Flags().BoolVar(&ksPrune, "prune", false, "enable garbage collection")
|
||||
createKsCmd.Flags().StringArrayVar(&ksHealthCheck, "health-check", nil, "workload to be included in the health assessment, in the format '<kind>/<name>.<namespace>'")
|
||||
createKsCmd.Flags().DurationVar(&ksHealthTimeout, "health-check-timeout", 2*time.Minute, "timeout of health checking operations")
|
||||
createKsCmd.Flags().StringVar(&ksValidation, "validation", "", "validate the manifests before applying them on the cluster, can be 'client' or 'server'")
|
||||
createKsCmd.Flags().StringArrayVar(&ksDependsOn, "depends-on", nil, "Kustomization that must be ready before this Kustomization can be applied, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createKsCmd.Flags().StringVar(&ksSAName, "sa-name", "", "service account name")
|
||||
createKsCmd.Flags().StringVar(&ksSANamespace, "sa-namespace", "", "service account namespace")
|
||||
createKsCmd.Flags().StringVar(&ksSAName, "service-account", "", "the name of the service account to impersonate when reconciling this Kustomization")
|
||||
createKsCmd.Flags().Var(&ksDecryptionProvider, "decryption-provider", ksDecryptionProvider.Description())
|
||||
createKsCmd.Flags().StringVar(&ksDecryptionSecret, "decryption-secret", "", "set the Kubernetes secret name that contains the OpenPGP private keys used for sops decryption")
|
||||
createKsCmd.Flags().StringVar(&ksTargetNamespace, "target-namespace", "", "overrides the namespace of all Kustomization objects reconciled by this Kustomization")
|
||||
@@ -111,7 +110,7 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if ksPath == "" {
|
||||
return fmt.Errorf("path is required")
|
||||
}
|
||||
if !strings.HasPrefix(ksPath, "./") {
|
||||
if !strings.HasPrefix(ksPath.String(), "./") {
|
||||
return fmt.Errorf("path must begin with ./")
|
||||
}
|
||||
|
||||
@@ -135,7 +134,7 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
Path: ksPath,
|
||||
Path: ksPath.String(),
|
||||
Prune: ksPrune,
|
||||
SourceRef: kustomizev1.CrossNamespaceSourceReference{
|
||||
Kind: ksSource.Kind,
|
||||
@@ -188,11 +187,8 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
if ksSAName != "" && ksSANamespace != "" {
|
||||
kustomization.Spec.ServiceAccount = &kustomizev1.ServiceAccount{
|
||||
Name: ksSAName,
|
||||
Namespace: ksSANamespace,
|
||||
}
|
||||
if ksSAName != "" {
|
||||
kustomization.Spec.ServiceAccountName = ksSAName
|
||||
}
|
||||
|
||||
if ksDecryptionProvider != "" {
|
||||
@@ -278,11 +274,11 @@ func isKustomizationReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -189,11 +190,11 @@ func isReceiverReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
82
cmd/flux/create_secret.go
Normal file
82
cmd/flux/create_secret.go
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
var createSecretCmd = &cobra.Command{
|
||||
Use: "secret",
|
||||
Short: "Create or update Kubernetes secrets",
|
||||
Long: "The create source sub-commands generate Kubernetes secrets specific to Flux.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
createCmd.AddCommand(createSecretCmd)
|
||||
}
|
||||
|
||||
func upsertSecret(ctx context.Context, kubeClient client.Client, secret corev1.Secret) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: secret.GetNamespace(),
|
||||
Name: secret.GetName(),
|
||||
}
|
||||
|
||||
var existing corev1.Secret
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &secret); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
existing.StringData = secret.StringData
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportSecret(secret corev1.Secret) error {
|
||||
secret.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
206
cmd/flux/create_secret_git.go
Normal file
206
cmd/flux/create_secret_git.go
Normal file
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/elliptic"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/ssh"
|
||||
)
|
||||
|
||||
var createSecretGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Create or update a Kubernetes secret for Git authentication",
|
||||
Long: `
|
||||
The create secret git command generates a Kubernetes secret with Git credentials.
|
||||
For Git over SSH, the host and SSH keys are automatically generated and stored in the secret.
|
||||
For Git over HTTP/S, the provided basic authentication credentials are stored in the secret.`,
|
||||
Example: ` # Create a Git SSH authentication secret using an ECDSA P-521 curve public key
|
||||
|
||||
flux create secret git podinfo-auth \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--ssh-key-algorithm=ecdsa \
|
||||
--ssh-ecdsa-curve=p521
|
||||
|
||||
# Create a secret for a Git repository using basic authentication
|
||||
flux create secret git podinfo-auth \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--username=username \
|
||||
--password=password
|
||||
|
||||
# Create a Git SSH secret on disk and print the deploy key
|
||||
flux create secret git podinfo-auth \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--export > podinfo-auth.yaml
|
||||
|
||||
yq read podinfo-auth.yaml 'data."identity.pub"' | base64 --decode
|
||||
|
||||
# Create a Git SSH secret on disk and encrypt it with Mozilla SOPS
|
||||
flux create secret git podinfo-auth \
|
||||
--namespace=apps \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--export > podinfo-auth.yaml
|
||||
|
||||
sops --encrypt --encrypted-regex '^(data|stringData)$' \
|
||||
--in-place podinfo-auth.yaml
|
||||
`,
|
||||
RunE: createSecretGitCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
secretGitURL string
|
||||
secretGitUsername string
|
||||
secretGitPassword string
|
||||
secretGitKeyAlgorithm flags.PublicKeyAlgorithm = "rsa"
|
||||
secretGitRSABits flags.RSAKeyBits = 2048
|
||||
secretGitECDSACurve = flags.ECDSACurve{Curve: elliptic.P384()}
|
||||
)
|
||||
|
||||
func init() {
|
||||
createSecretGitCmd.Flags().StringVar(&secretGitURL, "url", "", "git address, e.g. ssh://git@host/org/repository")
|
||||
createSecretGitCmd.Flags().StringVarP(&secretGitUsername, "username", "u", "", "basic authentication username")
|
||||
createSecretGitCmd.Flags().StringVarP(&secretGitPassword, "password", "p", "", "basic authentication password")
|
||||
createSecretGitCmd.Flags().Var(&secretGitKeyAlgorithm, "ssh-key-algorithm", secretGitKeyAlgorithm.Description())
|
||||
createSecretGitCmd.Flags().Var(&secretGitRSABits, "ssh-rsa-bits", secretGitRSABits.Description())
|
||||
createSecretGitCmd.Flags().Var(&secretGitECDSACurve, "ssh-ecdsa-curve", secretGitECDSACurve.Description())
|
||||
|
||||
createSecretCmd.AddCommand(createSecretGitCmd)
|
||||
}
|
||||
|
||||
func createSecretGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("secret name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if secretGitURL == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
|
||||
u, err := url.Parse(secretGitURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
|
||||
secretLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: secretLabels,
|
||||
},
|
||||
}
|
||||
|
||||
switch u.Scheme {
|
||||
case "ssh":
|
||||
pair, err := generateKeyPair(ctx, secretGitKeyAlgorithm, secretGitRSABits, secretGitECDSACurve)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hostKey, err := scanHostKey(ctx, u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
secret.Data = map[string][]byte{
|
||||
"identity": pair.PrivateKey,
|
||||
"identity.pub": pair.PublicKey,
|
||||
"known_hosts": hostKey,
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("deploy key: %s", string(pair.PublicKey))
|
||||
}
|
||||
case "http", "https":
|
||||
if secretGitUsername == "" || secretGitPassword == "" {
|
||||
return fmt.Errorf("for Git over HTTP/S the username and password are required")
|
||||
}
|
||||
|
||||
// TODO: add cert data when it's implemented in source-controller
|
||||
secret.Data = map[string][]byte{
|
||||
"username": []byte(secretGitUsername),
|
||||
"password": []byte(secretGitPassword),
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("git URL scheme '%s' not supported, can be: ssh, http and https", u.Scheme)
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportSecret(secret)
|
||||
}
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("secret '%s' created in '%s' namespace", name, namespace)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateKeyPair(ctx context.Context, alg flags.PublicKeyAlgorithm, rsa flags.RSAKeyBits, ecdsa flags.ECDSACurve) (*ssh.KeyPair, error) {
|
||||
var keyGen ssh.KeyPairGenerator
|
||||
switch algorithm := alg.String(); algorithm {
|
||||
case "rsa":
|
||||
keyGen = ssh.NewRSAGenerator(int(rsa))
|
||||
case "ecdsa":
|
||||
keyGen = ssh.NewECDSAGenerator(ecdsa.Curve)
|
||||
case "ed25519":
|
||||
keyGen = ssh.NewEd25519Generator()
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported public key algorithm: %s", algorithm)
|
||||
}
|
||||
pair, err := keyGen.Generate()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("key pair generation failed, error: %w", err)
|
||||
}
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
func scanHostKey(ctx context.Context, url *url.URL) ([]byte, error) {
|
||||
host := url.Host
|
||||
if url.Port() == "" {
|
||||
host = host + ":22"
|
||||
}
|
||||
hostKey, err := ssh.ScanHostKey(host, 30*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SSH key scan for host %s failed, error: %w", host, err)
|
||||
}
|
||||
return hostKey, nil
|
||||
}
|
||||
141
cmd/flux/create_secret_helm.go
Normal file
141
cmd/flux/create_secret_helm.go
Normal file
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var createSecretHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Create or update a Kubernetes secret for Helm repository authentication",
|
||||
Long: `
|
||||
The create secret helm command generates a Kubernetes secret with basic authentication credentials.`,
|
||||
Example: ` # Create a Helm authentication secret on disk and encrypt it with Mozilla SOPS
|
||||
|
||||
flux create secret helm repo-auth \
|
||||
--namespace=my-namespace \
|
||||
--username=my-username \
|
||||
--password=my-password \
|
||||
--export > repo-auth.yaml
|
||||
|
||||
sops --encrypt --encrypted-regex '^(data|stringData)$' \
|
||||
--in-place repo-auth.yaml
|
||||
|
||||
# Create an authentication secret using a custom TLS cert
|
||||
flux create secret helm repo-auth \
|
||||
--username=username \
|
||||
--password=password \
|
||||
--cert-file=./cert.crt \
|
||||
--key-file=./key.crt \
|
||||
--ca-file=./ca.crt
|
||||
`,
|
||||
RunE: createSecretHelmCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
secretHelmUsername string
|
||||
secretHelmPassword string
|
||||
secretHelmCertFile string
|
||||
secretHelmKeyFile string
|
||||
secretHelmCAFile string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createSecretHelmCmd.Flags().StringVarP(&secretHelmUsername, "username", "u", "", "basic authentication username")
|
||||
createSecretHelmCmd.Flags().StringVarP(&secretHelmPassword, "password", "p", "", "basic authentication password")
|
||||
createSecretHelmCmd.Flags().StringVar(&secretHelmCertFile, "cert-file", "", "TLS authentication cert file path")
|
||||
createSecretHelmCmd.Flags().StringVar(&secretHelmKeyFile, "key-file", "", "TLS authentication key file path")
|
||||
createSecretHelmCmd.Flags().StringVar(&secretHelmCAFile, "ca-file", "", "TLS authentication CA file path")
|
||||
|
||||
createSecretCmd.AddCommand(createSecretHelmCmd)
|
||||
}
|
||||
|
||||
func createSecretHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("secret name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
secretLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: secretLabels,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
}
|
||||
|
||||
if secretHelmUsername != "" && secretHelmPassword != "" {
|
||||
secret.StringData["username"] = secretHelmUsername
|
||||
secret.StringData["password"] = secretHelmPassword
|
||||
}
|
||||
|
||||
if secretHelmCertFile != "" && secretHelmKeyFile != "" {
|
||||
cert, err := ioutil.ReadFile(secretHelmCertFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository cert file '%s': %w", secretHelmCertFile, err)
|
||||
}
|
||||
secret.StringData["certFile"] = string(cert)
|
||||
|
||||
key, err := ioutil.ReadFile(secretHelmKeyFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository key file '%s': %w", secretHelmKeyFile, err)
|
||||
}
|
||||
secret.StringData["keyFile"] = string(key)
|
||||
}
|
||||
|
||||
if secretHelmCAFile != "" {
|
||||
ca, err := ioutil.ReadFile(secretHelmCAFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository CA file '%s': %w", secretHelmCAFile, err)
|
||||
}
|
||||
secret.StringData["caFile"] = string(ca)
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportSecret(secret)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("secret '%s' created in '%s' namespace", name, namespace)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -154,6 +154,7 @@ func createSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
}
|
||||
|
||||
@@ -23,23 +23,21 @@ import (
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/ssh"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var createSourceGitCmd = &cobra.Command{
|
||||
@@ -94,10 +92,11 @@ var (
|
||||
sourceGitUsername string
|
||||
sourceGitPassword string
|
||||
|
||||
sourceGitKeyAlgorithm flags.PublicKeyAlgorithm = "rsa"
|
||||
sourceGitRSABits flags.RSAKeyBits = 2048
|
||||
sourceGitECDSACurve = flags.ECDSACurve{Curve: elliptic.P384()}
|
||||
sourceGitSecretRef string
|
||||
sourceGitKeyAlgorithm flags.PublicKeyAlgorithm = "rsa"
|
||||
sourceGitRSABits flags.RSAKeyBits = 2048
|
||||
sourceGitECDSACurve = flags.ECDSACurve{Curve: elliptic.P384()}
|
||||
sourceGitSecretRef string
|
||||
sourceGitImplementation string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -111,6 +110,7 @@ func init() {
|
||||
createSourceGitCmd.Flags().Var(&sourceGitRSABits, "ssh-rsa-bits", sourceGitRSABits.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceGitECDSACurve, "ssh-ecdsa-curve", sourceGitECDSACurve.Description())
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceGitSecretRef, "secret-ref", "", "", "the name of an existing secret containing SSH or basic credentials")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitImplementation, "git-implementation", "", "the git implementation to use, can be 'go-git' or 'libgit2'")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceGitCmd)
|
||||
}
|
||||
@@ -141,6 +141,10 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if !utils.ContainsItemString([]string{sourcev1.GoGitImplementation, sourcev1.LibGit2Implementation, ""}, sourceGitImplementation) {
|
||||
return fmt.Errorf("Invalid git implementation %q", sourceGitImplementation)
|
||||
}
|
||||
|
||||
gitRepository := sourcev1.GitRepository{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
@@ -152,7 +156,8 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
Reference: &sourcev1.GitRepositoryRef{},
|
||||
Reference: &sourcev1.GitRepositoryRef{},
|
||||
GitImplementation: sourceGitImplementation,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -186,13 +191,13 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if sourceGitSecretRef != "" {
|
||||
withAuth = true
|
||||
} else if u.Scheme == "ssh" {
|
||||
logger.Actionf("generating deploy key pair")
|
||||
pair, err := generateKeyPair(ctx)
|
||||
logger.Generatef("generating deploy key pair")
|
||||
pair, err := generateKeyPair(ctx, sourceGitKeyAlgorithm, sourceGitRSABits, sourceGitECDSACurve)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("%s", pair.PublicKey)
|
||||
logger.Successf("deploy key: %s", pair.PublicKey)
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Have you added the deploy key to your repository",
|
||||
IsConfirm: true,
|
||||
@@ -206,14 +211,14 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("collected public key from SSH server:")
|
||||
fmt.Printf("%s", hostKey)
|
||||
logger.Successf("collected public key from SSH server:\n%s", hostKey)
|
||||
|
||||
logger.Actionf("applying secret with keys")
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"identity": string(pair.PrivateKey),
|
||||
@@ -231,6 +236,7 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"username": sourceGitUsername,
|
||||
@@ -279,63 +285,6 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateKeyPair(ctx context.Context) (*ssh.KeyPair, error) {
|
||||
var keyGen ssh.KeyPairGenerator
|
||||
switch algorithm := sourceGitKeyAlgorithm.String(); algorithm {
|
||||
case "rsa":
|
||||
keyGen = ssh.NewRSAGenerator(int(sourceGitRSABits))
|
||||
case "ecdsa":
|
||||
keyGen = ssh.NewECDSAGenerator(sourceGitECDSACurve.Curve)
|
||||
case "ed25519":
|
||||
keyGen = ssh.NewEd25519Generator()
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported public key algorithm: %s", algorithm)
|
||||
}
|
||||
pair, err := keyGen.Generate()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("key pair generation failed, error: %w", err)
|
||||
}
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
func scanHostKey(ctx context.Context, url *url.URL) ([]byte, error) {
|
||||
host := url.Host
|
||||
if url.Port() == "" {
|
||||
host = host + ":22"
|
||||
}
|
||||
hostKey, err := ssh.ScanHostKey(host, 30*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SSH key scan for host %s failed, error: %w", host, err)
|
||||
}
|
||||
return hostKey, nil
|
||||
}
|
||||
|
||||
func upsertSecret(ctx context.Context, kubeClient client.Client, secret corev1.Secret) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: secret.GetNamespace(),
|
||||
Name: secret.GetName(),
|
||||
}
|
||||
|
||||
var existing corev1.Secret
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &secret); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
existing.StringData = secret.StringData
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertGitRepository(ctx context.Context, kubeClient client.Client,
|
||||
gitRepository *sourcev1.GitRepository) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
@@ -375,11 +324,11 @@ func isGitRepositoryReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(gitRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(gitRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,9 +23,11 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
@@ -149,6 +151,7 @@ func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
}
|
||||
@@ -242,3 +245,28 @@ func upsertHelmRepository(ctx context.Context, kubeClient client.Client,
|
||||
logger.Successf("source updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isHelmRepositoryReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRepository *sourcev1.HelmRepository) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRepository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if helmRepository.Generation != helmRepository.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(helmRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ var createTenantCmd = &cobra.Command{
|
||||
Use: "tenant",
|
||||
Short: "Create or update a tenant",
|
||||
Long: `
|
||||
The create tenant command generates namespaces and role bindings to limit the
|
||||
The create tenant command generates namespaces, service accounts and role bindings to limit the
|
||||
reconcilers scope to the tenant namespaces.`,
|
||||
Example: ` # Create a tenant with access to a namespace
|
||||
flux create tenant dev-team \
|
||||
@@ -55,8 +55,7 @@ reconcilers scope to the tenant namespaces.`,
|
||||
}
|
||||
|
||||
const (
|
||||
tenantLabel = "toolkit.fluxcd.io/tenant"
|
||||
tenantRoleBinding = "gotk-reconciler"
|
||||
tenantLabel = "toolkit.fluxcd.io/tenant"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -65,7 +64,6 @@ var (
|
||||
)
|
||||
|
||||
func init() {
|
||||
createTenantCmd.Hidden = true
|
||||
createTenantCmd.Flags().StringSliceVar(&tenantNamespaces, "with-namespace", nil, "namespace belonging to this tenant")
|
||||
createTenantCmd.Flags().StringVar(&tenantClusterRole, "cluster-role", "cluster-admin", "cluster role of the tenant role binding")
|
||||
createCmd.AddCommand(createTenantCmd)
|
||||
@@ -89,6 +87,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
var namespaces []corev1.Namespace
|
||||
var accounts []corev1.ServiceAccount
|
||||
var roleBindings []rbacv1.RoleBinding
|
||||
|
||||
for _, ns := range tenantNamespaces {
|
||||
@@ -111,9 +110,19 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
namespaces = append(namespaces, namespace)
|
||||
|
||||
account := corev1.ServiceAccount{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tenant,
|
||||
Namespace: ns,
|
||||
Labels: objLabels,
|
||||
},
|
||||
}
|
||||
|
||||
accounts = append(accounts, account)
|
||||
|
||||
roleBinding := rbacv1.RoleBinding{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tenantRoleBinding,
|
||||
Name: fmt.Sprintf("%s-reconciler", tenant),
|
||||
Namespace: ns,
|
||||
Labels: objLabels,
|
||||
},
|
||||
@@ -123,6 +132,11 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Kind: "User",
|
||||
Name: fmt.Sprintf("gotk:%s:reconciler", ns),
|
||||
},
|
||||
{
|
||||
Kind: "ServiceAccount",
|
||||
Name: tenant,
|
||||
Namespace: ns,
|
||||
},
|
||||
},
|
||||
RoleRef: rbacv1.RoleRef{
|
||||
APIGroup: "rbac.authorization.k8s.io",
|
||||
@@ -135,7 +149,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
if export {
|
||||
for i, _ := range tenantNamespaces {
|
||||
if err := exportTenant(namespaces[i], roleBindings[i]); err != nil {
|
||||
if err := exportTenant(namespaces[i], accounts[i], roleBindings[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -156,6 +170,11 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying service account %s", accounts[i].Name)
|
||||
if err := upsertServiceAccount(ctx, kubeClient, accounts[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying role binding %s", roleBindings[i].Name)
|
||||
if err := upsertRoleBinding(ctx, kubeClient, roleBindings[i]); err != nil {
|
||||
return err
|
||||
@@ -195,6 +214,35 @@ func upsertNamespace(ctx context.Context, kubeClient client.Client, namespace co
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertServiceAccount(ctx context.Context, kubeClient client.Client, account corev1.ServiceAccount) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: account.GetNamespace(),
|
||||
Name: account.GetName(),
|
||||
}
|
||||
|
||||
var existing corev1.ServiceAccount
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &account); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !equality.Semantic.DeepDerivative(account.Labels, existing.Labels) {
|
||||
existing.Labels = account.Labels
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertRoleBinding(ctx context.Context, kubeClient client.Client, roleBinding rbacv1.RoleBinding) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: roleBinding.GetNamespace(),
|
||||
@@ -228,7 +276,7 @@ func upsertRoleBinding(ctx context.Context, kubeClient client.Client, roleBindin
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportTenant(namespace corev1.Namespace, roleBinding rbacv1.RoleBinding) error {
|
||||
func exportTenant(namespace corev1.Namespace, account corev1.ServiceAccount, roleBinding rbacv1.RoleBinding) error {
|
||||
namespace.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Namespace",
|
||||
@@ -242,6 +290,19 @@ func exportTenant(namespace corev1.Namespace, roleBinding rbacv1.RoleBinding) er
|
||||
data = bytes.Replace(data, []byte("spec: {}\n"), []byte(""), 1)
|
||||
fmt.Println(resourceToString(data))
|
||||
|
||||
account.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "ServiceAccount",
|
||||
}
|
||||
data, err = yaml.Marshal(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
data = bytes.Replace(data, []byte("spec: {}\n"), []byte(""), 1)
|
||||
fmt.Println(resourceToString(data))
|
||||
|
||||
roleBinding.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "rbac.authorization.k8s.io/v1",
|
||||
Kind: "RoleBinding",
|
||||
|
||||
@@ -17,7 +17,14 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var deleteCmd = &cobra.Command{
|
||||
@@ -36,3 +43,52 @@ func init() {
|
||||
|
||||
rootCmd.AddCommand(deleteCmd)
|
||||
}
|
||||
|
||||
type deleteCommand struct {
|
||||
apiType
|
||||
object adapter // for getting the value, and later deleting it
|
||||
}
|
||||
|
||||
func (del deleteCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("%s name is required", del.humanKind)
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, del.object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this " + del.humanKind,
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting %s %s in %s namespace", del.humanKind, name, namespace)
|
||||
err = kubeClient.Delete(ctx, del.object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s deleted", del.humanKind)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
31
cmd/flux/delete_image.go
Normal file
31
cmd/flux/delete_image.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var deleteAutoCmd = &cobra.Command{
|
||||
Use: "auto",
|
||||
Short: "Delete automation objects",
|
||||
Long: "The delete auto sub-commands delete automation objects.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteAutoCmd)
|
||||
}
|
||||
40
cmd/flux/delete_image_policy.go
Normal file
40
cmd/flux/delete_image_policy.go
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var deleteImagePolicyCmd = &cobra.Command{
|
||||
Use: "image-policy [name]",
|
||||
Short: "Delete an ImagePolicy object",
|
||||
Long: "The delete auto image-policy command deletes the given ImagePolicy from the cluster.",
|
||||
Example: ` # Delete an image policy
|
||||
flux delete auto image-policy alpine3.x
|
||||
`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imagePolicyType,
|
||||
object: universalAdapter{&imagev1.ImagePolicy{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImagePolicyCmd)
|
||||
}
|
||||
40
cmd/flux/delete_image_repository.go
Normal file
40
cmd/flux/delete_image_repository.go
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var deleteImageRepositoryCmd = &cobra.Command{
|
||||
Use: "image-repository [name]",
|
||||
Short: "Delete an ImageRepository object",
|
||||
Long: "The delete auto image-repository command deletes the given ImageRepository from the cluster.",
|
||||
Example: ` # Delete an image repository
|
||||
flux delete auto image-repository alpine
|
||||
`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imageRepositoryType,
|
||||
object: universalAdapter{&imagev1.ImageRepository{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImageRepositoryCmd)
|
||||
}
|
||||
40
cmd/flux/delete_image_updateauto.go
Normal file
40
cmd/flux/delete_image_updateauto.go
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var deleteImageUpdateCmd = &cobra.Command{
|
||||
Use: "image-update [name]",
|
||||
Short: "Delete an ImageUpdateAutomation object",
|
||||
Long: "The delete auto image-update command deletes the given ImageUpdateAutomation from the cluster.",
|
||||
Example: ` # Delete an image update automation
|
||||
flux delete auto image-update latest-images
|
||||
`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
object: universalAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImageUpdateCmd)
|
||||
}
|
||||
@@ -18,8 +18,15 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var exportCmd = &cobra.Command{
|
||||
@@ -38,6 +45,80 @@ func init() {
|
||||
rootCmd.AddCommand(exportCmd)
|
||||
}
|
||||
|
||||
// exportable represents a type that you can fetch from the Kubernetes
|
||||
// API, then tidy up for serialising.
|
||||
type exportable interface {
|
||||
adapter
|
||||
export() interface{}
|
||||
}
|
||||
|
||||
// exportableList represents a type that has a list of values, each of
|
||||
// which is exportable.
|
||||
type exportableList interface {
|
||||
adapter
|
||||
len() int
|
||||
exportItem(i int) interface{}
|
||||
}
|
||||
|
||||
type exportCommand struct {
|
||||
object exportable
|
||||
list exportableList
|
||||
}
|
||||
|
||||
func (export exportCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
err = kubeClient.List(ctx, export.list.asRuntimeObject(), client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if export.list.len() == 0 {
|
||||
logger.Failuref("no objects found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for i := 0; i < export.list.len(); i++ {
|
||||
if err = printExport(export.list.exportItem(i)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
err = kubeClient.Get(ctx, namespacedName, export.object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printExport(export.object.export())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printExport(export interface{}) error {
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
func resourceToString(data []byte) string {
|
||||
data = bytes.Replace(data, []byte(" creationTimestamp: null\n"), []byte(""), 1)
|
||||
data = bytes.Replace(data, []byte("status: {}\n"), []byte(""), 1)
|
||||
|
||||
31
cmd/flux/export_image.go
Normal file
31
cmd/flux/export_image.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var exportImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Export image automation objects",
|
||||
Long: "The export image sub-commands export image automation objects in YAML format.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportImageCmd)
|
||||
}
|
||||
72
cmd/flux/export_image_policy.go
Normal file
72
cmd/flux/export_image_policy.go
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var exportImagePolicyCmd = &cobra.Command{
|
||||
Use: "policy [name]",
|
||||
Short: "Export ImagePolicy resources in YAML format",
|
||||
Long: "The export image policy command exports one or all ImagePolicy resources in YAML format.",
|
||||
Example: ` # Export all ImagePolicy resources
|
||||
flux export image policy --all > image-policies.yaml
|
||||
|
||||
# Export a specific policy
|
||||
flux export image policy alpine1x > alpine1x.yaml
|
||||
`,
|
||||
RunE: exportCommand{
|
||||
object: imagePolicyAdapter{&imagev1.ImagePolicy{}},
|
||||
list: imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportImageCmd.AddCommand(exportImagePolicyCmd)
|
||||
}
|
||||
|
||||
// Export returns a ImagePolicy value which has extraneous information
|
||||
// stripped out.
|
||||
func exportImagePolicy(item *imagev1.ImagePolicy) interface{} {
|
||||
gvk := imagev1.GroupVersion.WithKind(imagev1.ImagePolicyKind)
|
||||
export := imagev1.ImagePolicy{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: item.Name,
|
||||
Namespace: item.Namespace,
|
||||
Labels: item.Labels,
|
||||
Annotations: item.Annotations,
|
||||
},
|
||||
Spec: item.Spec,
|
||||
}
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex imagePolicyAdapter) export() interface{} {
|
||||
return exportImagePolicy(ex.ImagePolicy)
|
||||
}
|
||||
|
||||
func (ex imagePolicyListAdapter) exportItem(i int) interface{} {
|
||||
return exportImagePolicy(&ex.ImagePolicyList.Items[i])
|
||||
}
|
||||
70
cmd/flux/export_image_repository.go
Normal file
70
cmd/flux/export_image_repository.go
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var exportImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository [name]",
|
||||
Short: "Export ImageRepository resources in YAML format",
|
||||
Long: "The export image repository command exports one or all ImageRepository resources in YAML format.",
|
||||
Example: ` # Export all ImageRepository resources
|
||||
flux export image repository --all > image-repositories.yaml
|
||||
|
||||
# Export a specific ImageRepository resource
|
||||
flux export image repository alpine > alpine.yaml
|
||||
`,
|
||||
RunE: exportCommand{
|
||||
object: imageRepositoryAdapter{&imagev1.ImageRepository{}},
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportImageCmd.AddCommand(exportImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func exportImageRepository(repo *imagev1.ImageRepository) interface{} {
|
||||
gvk := imagev1.GroupVersion.WithKind(imagev1.ImageRepositoryKind)
|
||||
export := imagev1.ImageRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: repo.Name,
|
||||
Namespace: repo.Namespace,
|
||||
Labels: repo.Labels,
|
||||
Annotations: repo.Annotations,
|
||||
},
|
||||
Spec: repo.Spec,
|
||||
}
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex imageRepositoryAdapter) export() interface{} {
|
||||
return exportImageRepository(ex.ImageRepository)
|
||||
}
|
||||
|
||||
func (ex imageRepositoryListAdapter) exportItem(i int) interface{} {
|
||||
return exportImageRepository(&ex.ImageRepositoryList.Items[i])
|
||||
}
|
||||
72
cmd/flux/export_image_updateauto.go
Normal file
72
cmd/flux/export_image_updateauto.go
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var exportImageUpdateCmd = &cobra.Command{
|
||||
Use: "update [name]",
|
||||
Short: "Export ImageUpdateAutomation resources in YAML format",
|
||||
Long: "The export image update command exports one or all ImageUpdateAutomation resources in YAML format.",
|
||||
Example: ` # Export all ImageUpdateAutomation resources
|
||||
flux export image update --all > updates.yaml
|
||||
|
||||
# Export a specific automation
|
||||
flux export image update latest-images > latest.yaml
|
||||
`,
|
||||
RunE: exportCommand{
|
||||
object: imageUpdateAutomationAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
list: imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportImageCmd.AddCommand(exportImageUpdateCmd)
|
||||
}
|
||||
|
||||
// exportImageUpdate returns a value which has extraneous information
|
||||
// stripped out.
|
||||
func exportImageUpdate(item *autov1.ImageUpdateAutomation) interface{} {
|
||||
gvk := autov1.GroupVersion.WithKind(autov1.ImageUpdateAutomationKind)
|
||||
export := autov1.ImageUpdateAutomation{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: item.Name,
|
||||
Namespace: item.Namespace,
|
||||
Labels: item.Labels,
|
||||
Annotations: item.Annotations,
|
||||
},
|
||||
Spec: item.Spec,
|
||||
}
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex imageUpdateAutomationAdapter) export() interface{} {
|
||||
return exportImageUpdate(ex.ImageUpdateAutomation)
|
||||
}
|
||||
|
||||
func (ex imageUpdateAutomationListAdapter) exportItem(i int) interface{} {
|
||||
return exportImageUpdate(&ex.ImageUpdateAutomationList.Items[i])
|
||||
}
|
||||
@@ -17,7 +17,17 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var getCmd = &cobra.Command{
|
||||
@@ -33,3 +43,66 @@ func init() {
|
||||
"list the requested object(s) across all namespaces")
|
||||
rootCmd.AddCommand(getCmd)
|
||||
}
|
||||
|
||||
type summarisable interface {
|
||||
adapter
|
||||
len() int
|
||||
summariseItem(i int, includeNamespace bool) []string
|
||||
headers(includeNamespace bool) []string
|
||||
}
|
||||
|
||||
// --- these help with implementations of summarisable
|
||||
|
||||
func statusAndMessage(conditions []metav1.Condition) (string, string) {
|
||||
if c := apimeta.FindStatusCondition(conditions, meta.ReadyCondition); c != nil {
|
||||
return string(c.Status), c.Message
|
||||
}
|
||||
return string(metav1.ConditionFalse), "waiting to be reconciled"
|
||||
}
|
||||
|
||||
func nameColumns(item named, includeNamespace bool) []string {
|
||||
if includeNamespace {
|
||||
return []string{item.GetNamespace(), item.GetName()}
|
||||
}
|
||||
return []string{item.GetName()}
|
||||
}
|
||||
|
||||
var namespaceHeader = []string{"Namespace"}
|
||||
|
||||
type getCommand struct {
|
||||
apiType
|
||||
list summarisable
|
||||
}
|
||||
|
||||
func (get getCommand) run(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
err = kubeClient.List(ctx, get.list.asRuntimeObject(), listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if get.list.len() == 0 {
|
||||
logger.Failuref("no %s objects found in %s namespace", get.kind, namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := get.list.headers(allNamespaces)
|
||||
var rows [][]string
|
||||
for i := 0; i < get.list.len(); i++ {
|
||||
row := get.list.summariseItem(i, allNamespaces)
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
@@ -69,28 +70,26 @@ func getAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Suspended", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, alert := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
//alert.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
//alert.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
@@ -21,7 +21,8 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
@@ -74,7 +75,7 @@ func getAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
var rows [][]string
|
||||
for _, provider := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(c.Status),
|
||||
@@ -83,7 +84,7 @@ func getAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
} else {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,8 @@ import (
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
@@ -71,28 +72,28 @@ func getHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Suspended", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, helmRelease := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
helmRelease.GetName(),
|
||||
helmRelease.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(helmRelease.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
helmRelease.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(helmRelease.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
helmRelease.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
helmRelease.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(helmRelease.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
31
cmd/flux/get_image.go
Normal file
31
cmd/flux/get_image.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var getImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Get image automation object status",
|
||||
Long: "The get image sub-commands print the status of image automation objects.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getImageCmd)
|
||||
}
|
||||
57
cmd/flux/get_image_policy.go
Normal file
57
cmd/flux/get_image_policy.go
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var getImagePolicyCmd = &cobra.Command{
|
||||
Use: "policy",
|
||||
Short: "Get ImagePolicy status",
|
||||
Long: "The get image policy command prints the status of ImagePolicy objects.",
|
||||
Example: ` # List all image policies and their status
|
||||
flux get image policy
|
||||
|
||||
# List image policies from all namespaces
|
||||
flux get image policy --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imagePolicyType,
|
||||
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImagePolicyCmd)
|
||||
}
|
||||
|
||||
func (s imagePolicyListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace), status, msg, item.Status.LatestImage)
|
||||
}
|
||||
|
||||
func (s imagePolicyListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message", "Latest image"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
66
cmd/flux/get_image_repository.go
Normal file
66
cmd/flux/get_image_repository.go
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var getImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository",
|
||||
Short: "Get ImageRepository status",
|
||||
Long: "The get image repository command prints the status of ImageRepository objects.",
|
||||
Example: ` # List all image repositories and their status
|
||||
flux get image repository
|
||||
|
||||
# List image repositories from all namespaces
|
||||
flux get image repository --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imageRepositoryType,
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func (s imageRepositoryListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
var lastScan string
|
||||
if item.Status.LastScanResult != nil {
|
||||
lastScan = item.Status.LastScanResult.ScanTime.Time.Format(time.RFC3339)
|
||||
}
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
status, msg, lastScan, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
func (s imageRepositoryListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message", "Last scan", "Suspended"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
65
cmd/flux/get_image_updateauto.go
Normal file
65
cmd/flux/get_image_updateauto.go
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var getImageUpdateCmd = &cobra.Command{
|
||||
Use: "update",
|
||||
Short: "Get ImageUpdateAutomation status",
|
||||
Long: "The get image update command prints the status of ImageUpdateAutomation objects.",
|
||||
Example: ` # List all image update automation object and their status
|
||||
flux get image update
|
||||
|
||||
# List image update automations from all namespaces
|
||||
flux get image update --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImageUpdateCmd)
|
||||
}
|
||||
|
||||
func (s imageUpdateAutomationListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
var lastRun string
|
||||
if item.Status.LastAutomationRunTime != nil {
|
||||
lastRun = item.Status.LastAutomationRunTime.Time.Format(time.RFC3339)
|
||||
}
|
||||
return append(nameColumns(&item, includeNamespace), status, msg, lastRun, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
func (s imageUpdateAutomationListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message", "Last run", "Suspended"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
@@ -27,7 +27,8 @@ import (
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
@@ -70,28 +71,28 @@ func getKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Suspended", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, kustomization := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
kustomization.GetName(),
|
||||
kustomization.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(kustomization.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
kustomization.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(kustomization.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
kustomization.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
kustomization.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(kustomization.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
@@ -23,7 +23,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
@@ -69,26 +70,26 @@ func getReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Suspended", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, receiver := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
rows = append(rows, row)
|
||||
|
||||
@@ -19,13 +19,16 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
@@ -35,6 +38,9 @@ var getSourceBucketCmd = &cobra.Command{
|
||||
Long: "The get sources bucket command prints the status of the Bucket sources.",
|
||||
Example: ` # List all Buckets and their status
|
||||
flux get sources bucket
|
||||
|
||||
# List buckets from all namespaces
|
||||
flux get sources helm --all-namespaces
|
||||
`,
|
||||
RunE: getSourceBucketCmdRun,
|
||||
}
|
||||
@@ -67,7 +73,7 @@ func getSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
@@ -78,19 +84,21 @@ func getSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
111
cmd/flux/get_source_chart.go
Normal file
111
cmd/flux/get_source_chart.go
Normal file
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getSourceHelmChartCmd = &cobra.Command{
|
||||
Use: "chart",
|
||||
Short: "Get HelmChart statuses",
|
||||
Long: "The get sources chart command prints the status of the HelmCharts.",
|
||||
Example: ` # List all Helm charts and their status
|
||||
flux get sources chart
|
||||
|
||||
# List Helm charts from all namespaces
|
||||
flux get sources chart --all-namespaces
|
||||
`,
|
||||
RunE: getSourceHelmChartCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceHelmChartCmd)
|
||||
}
|
||||
|
||||
func getSourceHelmChartCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list sourcev1.HelmChartList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no chart sources found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, source := range list.Items {
|
||||
var row []string
|
||||
var revision string
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := apimeta.FindStatusCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{source.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
@@ -19,13 +19,16 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
@@ -35,6 +38,9 @@ var getSourceGitCmd = &cobra.Command{
|
||||
Long: "The get sources git command prints the status of the GitRepository sources.",
|
||||
Example: ` # List all Git repositories and their status
|
||||
flux get sources git
|
||||
|
||||
# List Git repositories from all namespaces
|
||||
flux get sources git --all-namespaces
|
||||
`,
|
||||
RunE: getSourceGitCmdRun,
|
||||
}
|
||||
@@ -67,7 +73,7 @@ func getSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
@@ -78,19 +84,21 @@ func getSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
@@ -19,13 +19,16 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
@@ -35,6 +38,9 @@ var getSourceHelmCmd = &cobra.Command{
|
||||
Long: "The get sources helm command prints the status of the HelmRepository sources.",
|
||||
Example: ` # List all Helm repositories and their status
|
||||
flux get sources helm
|
||||
|
||||
# List Helm repositories from all namespaces
|
||||
flux get sources helm --all-namespaces
|
||||
`,
|
||||
RunE: getSourceHelmCmdRun,
|
||||
}
|
||||
@@ -67,7 +73,7 @@ func getSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
header := []string{"Name", "Ready", "Message", "Revision", "Suspended"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
@@ -78,19 +84,21 @@ func getSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
revision,
|
||||
strings.Title(strconv.FormatBool(source.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
|
||||
115
cmd/flux/image.go
Normal file
115
cmd/flux/image.go
Normal file
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
// These are general-purpose adapters for attaching methods to, for
|
||||
// the various commands. The *List adapters implement len(), since
|
||||
// it's used in at least a couple of commands.
|
||||
|
||||
// imagev1.ImageRepository
|
||||
|
||||
var imageRepositoryType = apiType{
|
||||
kind: imagev1.ImageRepositoryKind,
|
||||
humanKind: "image repository",
|
||||
}
|
||||
|
||||
type imageRepositoryAdapter struct {
|
||||
*imagev1.ImageRepository
|
||||
}
|
||||
|
||||
func (a imageRepositoryAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImageRepository
|
||||
}
|
||||
|
||||
// imagev1.ImageRepositoryList
|
||||
|
||||
type imageRepositoryListAdapter struct {
|
||||
*imagev1.ImageRepositoryList
|
||||
}
|
||||
|
||||
func (a imageRepositoryListAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImageRepositoryList
|
||||
}
|
||||
|
||||
func (a imageRepositoryListAdapter) len() int {
|
||||
return len(a.ImageRepositoryList.Items)
|
||||
}
|
||||
|
||||
// imagev1.ImagePolicy
|
||||
|
||||
var imagePolicyType = apiType{
|
||||
kind: imagev1.ImagePolicyKind,
|
||||
humanKind: "image policy",
|
||||
}
|
||||
|
||||
type imagePolicyAdapter struct {
|
||||
*imagev1.ImagePolicy
|
||||
}
|
||||
|
||||
func (a imagePolicyAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImagePolicy
|
||||
}
|
||||
|
||||
// imagev1.ImagePolicyList
|
||||
|
||||
type imagePolicyListAdapter struct {
|
||||
*imagev1.ImagePolicyList
|
||||
}
|
||||
|
||||
func (a imagePolicyListAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImagePolicyList
|
||||
}
|
||||
|
||||
func (a imagePolicyListAdapter) len() int {
|
||||
return len(a.ImagePolicyList.Items)
|
||||
}
|
||||
|
||||
// autov1.ImageUpdateAutomation
|
||||
|
||||
var imageUpdateAutomationType = apiType{
|
||||
kind: autov1.ImageUpdateAutomationKind,
|
||||
humanKind: "image update automation",
|
||||
}
|
||||
|
||||
type imageUpdateAutomationAdapter struct {
|
||||
*autov1.ImageUpdateAutomation
|
||||
}
|
||||
|
||||
func (a imageUpdateAutomationAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImageUpdateAutomation
|
||||
}
|
||||
|
||||
// autov1.ImageUpdateAutomationList
|
||||
|
||||
type imageUpdateAutomationListAdapter struct {
|
||||
*autov1.ImageUpdateAutomationList
|
||||
}
|
||||
|
||||
func (a imageUpdateAutomationListAdapter) asRuntimeObject() runtime.Object {
|
||||
return a.ImageUpdateAutomationList
|
||||
}
|
||||
|
||||
func (a imageUpdateAutomationListAdapter) len() int {
|
||||
return len(a.ImageUpdateAutomationList.Items)
|
||||
}
|
||||
@@ -56,13 +56,15 @@ var (
|
||||
installDryRun bool
|
||||
installManifestsPath string
|
||||
installVersion string
|
||||
installComponents []string
|
||||
installDefaultComponents []string
|
||||
installExtraComponents []string
|
||||
installRegistry string
|
||||
installImagePullSecret string
|
||||
installWatchAllNamespaces bool
|
||||
installNetworkPolicy bool
|
||||
installArch = flags.Arch(defaults.Arch)
|
||||
installLogLevel = flags.LogLevel(defaults.LogLevel)
|
||||
installClusterDomain string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -72,8 +74,10 @@ func init() {
|
||||
"only print the object that would be applied")
|
||||
installCmd.Flags().StringVarP(&installVersion, "version", "v", defaults.Version,
|
||||
"toolkit version")
|
||||
installCmd.Flags().StringSliceVar(&installComponents, "components", defaults.Components,
|
||||
installCmd.Flags().StringSliceVar(&installDefaultComponents, "components", defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
installCmd.Flags().StringSliceVar(&installExtraComponents, "components-extra", nil,
|
||||
"list of components in addition to those supplied or defaulted, accepts comma-separated values")
|
||||
installCmd.Flags().StringVar(&installManifestsPath, "manifests", "", "path to the manifest directory")
|
||||
installCmd.Flags().MarkHidden("manifests")
|
||||
installCmd.Flags().StringVar(&installRegistry, "registry", defaults.Registry,
|
||||
@@ -86,6 +90,7 @@ func init() {
|
||||
installCmd.Flags().Var(&installLogLevel, "log-level", installLogLevel.Description())
|
||||
installCmd.Flags().BoolVar(&installNetworkPolicy, "network-policy", defaults.NetworkPolicy,
|
||||
"deny ingress access to the toolkit controllers from other namespaces using network policies")
|
||||
installCmd.Flags().StringVar(&installClusterDomain, "cluster-domain", defaults.ClusterDomain, "internal cluster domain")
|
||||
rootCmd.AddCommand(installCmd)
|
||||
}
|
||||
|
||||
@@ -103,11 +108,17 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
logger.Generatef("generating manifests")
|
||||
}
|
||||
|
||||
components := append(installDefaultComponents, installExtraComponents...)
|
||||
|
||||
if err := utils.ValidateComponents(components); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts := install.Options{
|
||||
BaseURL: installManifestsPath,
|
||||
Version: installVersion,
|
||||
Namespace: namespace,
|
||||
Components: installComponents,
|
||||
Components: components,
|
||||
Registry: installRegistry,
|
||||
ImagePullSecret: installImagePullSecret,
|
||||
Arch: installArch.String(),
|
||||
@@ -117,6 +128,7 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
NotificationController: defaults.NotificationController,
|
||||
ManifestFile: fmt.Sprintf("%s.yaml", namespace),
|
||||
Timeout: timeout,
|
||||
ClusterDomain: installClusterDomain,
|
||||
}
|
||||
|
||||
if installManifestsPath == "" {
|
||||
@@ -137,7 +149,7 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
} else if installExport {
|
||||
fmt.Println("---")
|
||||
fmt.Println("# GitOps Toolkit revision", installVersion)
|
||||
fmt.Println("# Components:", strings.Join(installComponents, ","))
|
||||
fmt.Println("# Components:", strings.Join(components, ","))
|
||||
fmt.Print(manifest.Content)
|
||||
fmt.Println("---")
|
||||
return nil
|
||||
@@ -155,7 +167,7 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
kubectlArgs = append(kubectlArgs, "--dry-run=client")
|
||||
applyOutput = utils.ModeOS
|
||||
}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubectlArgs...); err != nil {
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
@@ -167,9 +179,9 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
logger.Waitingf("verifying installation")
|
||||
for _, deployment := range installComponents {
|
||||
for _, deployment := range components {
|
||||
kubectlArgs = []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubectlArgs...); err != nil {
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubeconfig, kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
} else {
|
||||
logger.Successf("%s ready", deployment)
|
||||
|
||||
@@ -16,26 +16,31 @@ limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type printLogger struct{}
|
||||
|
||||
func (l printLogger) Actionf(format string, a ...interface{}) {
|
||||
fmt.Println(`►`, fmt.Sprintf(format, a...))
|
||||
type stderrLogger struct {
|
||||
stderr io.Writer
|
||||
}
|
||||
|
||||
func (l printLogger) Generatef(format string, a ...interface{}) {
|
||||
fmt.Println(`✚`, fmt.Sprintf(format, a...))
|
||||
func (l stderrLogger) Actionf(format string, a ...interface{}) {
|
||||
fmt.Fprintln(l.stderr, `►`, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
func (l printLogger) Waitingf(format string, a ...interface{}) {
|
||||
fmt.Println(`◎`, fmt.Sprintf(format, a...))
|
||||
func (l stderrLogger) Generatef(format string, a ...interface{}) {
|
||||
fmt.Fprintln(l.stderr, `✚`, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
func (l printLogger) Successf(format string, a ...interface{}) {
|
||||
fmt.Println(`✔`, fmt.Sprintf(format, a...))
|
||||
func (l stderrLogger) Waitingf(format string, a ...interface{}) {
|
||||
fmt.Fprintln(l.stderr, `◎`, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
func (l printLogger) Failuref(format string, a ...interface{}) {
|
||||
fmt.Println(`✗`, fmt.Sprintf(format, a...))
|
||||
func (l stderrLogger) Successf(format string, a ...interface{}) {
|
||||
fmt.Fprintln(l.stderr, `✔`, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
func (l stderrLogger) Failuref(format string, a ...interface{}) {
|
||||
fmt.Fprintln(l.stderr, `✗`, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ var (
|
||||
timeout time.Duration
|
||||
verbose bool
|
||||
pollInterval = 2 * time.Second
|
||||
logger fluxlog.Logger = printLogger{}
|
||||
logger fluxlog.Logger = stderrLogger{stderr: os.Stderr}
|
||||
defaults = install.MakeDefaultOptions()
|
||||
)
|
||||
|
||||
|
||||
64
cmd/flux/object.go
Normal file
64
cmd/flux/object.go
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// Most commands need one or both of the kind (e.g.,
|
||||
// `"ImageRepository"`) and a human-palatable name for the kind (e.g.,
|
||||
// `"image repository"`), to be interpolated into output. It's
|
||||
// convenient to package these up ahead of time, then the command
|
||||
// implementation can pick whichever it wants to use.
|
||||
type apiType struct {
|
||||
kind, humanKind string
|
||||
}
|
||||
|
||||
// adapter is an interface for a wrapper or alias from which we can
|
||||
// get a controller-runtime deserialisable value. This is used so that
|
||||
// you can wrap an API type to give it other useful methods, but still
|
||||
// use values of the wrapper with `client.Client`, which only deals
|
||||
// with types that have been added to the schema.
|
||||
type adapter interface {
|
||||
asRuntimeObject() runtime.Object
|
||||
}
|
||||
|
||||
// universalAdapter is an adapter for any runtime.Object. Use this if
|
||||
// there are no other methods needed.
|
||||
type universalAdapter struct {
|
||||
obj runtime.Object
|
||||
}
|
||||
|
||||
func (c universalAdapter) asRuntimeObject() runtime.Object {
|
||||
return c.obj
|
||||
}
|
||||
|
||||
// named is for adapters that have Name and Namespace fields, which
|
||||
// are sometimes handy to get hold of. ObjectMeta implements these, so
|
||||
// they shouldn't need any extra work.
|
||||
type named interface {
|
||||
GetName() string
|
||||
GetNamespace() string
|
||||
SetName(string)
|
||||
SetNamespace(string)
|
||||
}
|
||||
|
||||
func copyName(target, source named) {
|
||||
target.SetName(source.GetName())
|
||||
target.SetNamespace(source.GetNamespace())
|
||||
}
|
||||
@@ -17,7 +17,20 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/client-go/util/retry"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var reconcileCmd = &cobra.Command{
|
||||
@@ -29,3 +42,101 @@ var reconcileCmd = &cobra.Command{
|
||||
func init() {
|
||||
rootCmd.AddCommand(reconcileCmd)
|
||||
}
|
||||
|
||||
type reconcileCommand struct {
|
||||
apiType
|
||||
object reconcilable
|
||||
}
|
||||
|
||||
type reconcilable interface {
|
||||
adapter // to be able to load from the cluster
|
||||
suspendable // to tell if it's suspended
|
||||
|
||||
// these are implemented by anything embedding metav1.ObjectMeta
|
||||
GetAnnotations() map[string]string
|
||||
SetAnnotations(map[string]string)
|
||||
|
||||
// this is usually implemented by GOTK types, since it's used for meta.SetResourceCondition
|
||||
GetStatusConditions() *[]metav1.Condition
|
||||
|
||||
lastHandledReconcileRequest() string // what was the last handled reconcile request?
|
||||
successMessage() string // what do you want to tell people when successfully reconciled?
|
||||
}
|
||||
|
||||
func (reconcile reconcileCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("%s name is required", reconcile.kind)
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, reconcile.object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if reconcile.object.isSuspended() {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
|
||||
logger.Actionf("annotating %s %s in %s namespace", reconcile.kind, name, namespace)
|
||||
if err := requestReconciliation(ctx, kubeClient, namespacedName, reconcile.object); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s annotated", reconcile.kind)
|
||||
|
||||
lastHandledReconcileAt := reconcile.object.lastHandledReconcileRequest()
|
||||
logger.Waitingf("waiting for %s reconciliation", reconcile.kind)
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
reconciliationHandled(ctx, kubeClient, namespacedName, reconcile.object, lastHandledReconcileAt)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s reconciliation completed", reconcile.kind)
|
||||
|
||||
if apimeta.IsStatusConditionFalse(*reconcile.object.GetStatusConditions(), meta.ReadyCondition) {
|
||||
return fmt.Errorf("%s reconciliation failed", reconcile.kind)
|
||||
}
|
||||
logger.Successf(reconcile.object.successMessage())
|
||||
return nil
|
||||
}
|
||||
|
||||
func reconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, obj reconcilable, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, obj.asRuntimeObject())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return obj.lastHandledReconcileRequest() != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, obj reconcilable) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, obj.asRuntimeObject()); err != nil {
|
||||
return err
|
||||
}
|
||||
if ann := obj.GetAnnotations(); ann == nil {
|
||||
obj.SetAnnotations(map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
})
|
||||
} else {
|
||||
ann[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
obj.SetAnnotations(ann)
|
||||
}
|
||||
return kubeClient.Update(ctx, obj.asRuntimeObject())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,13 +64,17 @@ func reconcileAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Alert %s in %s namespace", name, namespace)
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if alert.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Alert %s in %s namespace", name, namespace)
|
||||
if alert.Annotations == nil {
|
||||
alert.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
@@ -78,6 +82,7 @@ func reconcileAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
} else {
|
||||
alert.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
if err := kubeClient.Update(ctx, &alert); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/client-go/util/retry"
|
||||
@@ -85,6 +86,10 @@ func reconcileHrCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if helmRelease.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
|
||||
if syncHrWithSource {
|
||||
switch helmRelease.Spec.Chart.Spec.SourceRef.Kind {
|
||||
case sourcev1.HelmRepositoryKind:
|
||||
@@ -118,9 +123,9 @@ func reconcileHrCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return fmt.Errorf("HelmRelease reconciliation failed: %s", c.Message)
|
||||
default:
|
||||
logger.Successf("reconciled revision %s", helmRelease.Status.LastAppliedRevision)
|
||||
|
||||
31
cmd/flux/reconcile_image.go
Normal file
31
cmd/flux/reconcile_image.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var reconcileImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Reconcile image automation objects",
|
||||
Long: "The reconcile sub-commands trigger a reconciliation of image automation objects.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileCmd.AddCommand(reconcileImageCmd)
|
||||
}
|
||||
50
cmd/flux/reconcile_image_repository.go
Normal file
50
cmd/flux/reconcile_image_repository.go
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var reconcileImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository [name]",
|
||||
Short: "Reconcile an ImageRepository",
|
||||
Long: `The reconcile image repository command triggers a reconciliation of an ImageRepository resource and waits for it to finish.`,
|
||||
Example: ` # Trigger an scan for an existing image repository
|
||||
flux reconcile image repository alpine
|
||||
`,
|
||||
RunE: reconcileCommand{
|
||||
apiType: imageRepositoryType,
|
||||
object: imageRepositoryAdapter{&imagev1.ImageRepository{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileImageCmd.AddCommand(reconcileImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func (obj imageRepositoryAdapter) lastHandledReconcileRequest() string {
|
||||
return obj.Status.GetLastHandledReconcileRequest()
|
||||
}
|
||||
|
||||
func (obj imageRepositoryAdapter) successMessage() string {
|
||||
return fmt.Sprintf("scan fetched %d tags", obj.Status.LastScanResult.TagCount)
|
||||
}
|
||||
62
cmd/flux/reconcile_image_updateauto.go
Normal file
62
cmd/flux/reconcile_image_updateauto.go
Normal file
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
meta "github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var reconcileImageUpdateCmd = &cobra.Command{
|
||||
Use: "update [name]",
|
||||
Short: "Reconcile an ImageUpdateAutomation",
|
||||
Long: `The reconcile image update command triggers a reconciliation of an ImageUpdateAutomation resource and waits for it to finish.`,
|
||||
Example: ` # Trigger an automation run for an existing image update automation
|
||||
flux reconcile image update latest-images
|
||||
`,
|
||||
RunE: reconcileCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
object: imageUpdateAutomationAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileImageCmd.AddCommand(reconcileImageUpdateCmd)
|
||||
}
|
||||
|
||||
func (obj imageUpdateAutomationAdapter) suspended() bool {
|
||||
return obj.ImageUpdateAutomation.Spec.Suspend
|
||||
}
|
||||
|
||||
func (obj imageUpdateAutomationAdapter) lastHandledReconcileRequest() string {
|
||||
return obj.Status.GetLastHandledReconcileRequest()
|
||||
}
|
||||
|
||||
func (obj imageUpdateAutomationAdapter) successMessage() string {
|
||||
if rc := apimeta.FindStatusCondition(obj.Status.Conditions, meta.ReadyCondition); rc != nil {
|
||||
return rc.Message
|
||||
}
|
||||
if obj.Status.LastAutomationRunTime != nil {
|
||||
return "last run " + obj.Status.LastAutomationRunTime.Time.Format(time.RFC3339)
|
||||
}
|
||||
return "automation not yet run"
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/client-go/util/retry"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
@@ -84,6 +84,10 @@ func reconcileKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if kustomization.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
|
||||
if syncKsWithSource {
|
||||
switch kustomization.Spec.SourceRef.Kind {
|
||||
case sourcev1.GitRepositoryKind:
|
||||
@@ -112,14 +116,10 @@ func reconcileKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
logger.Successf("Kustomization reconciliation completed")
|
||||
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionFalse:
|
||||
return fmt.Errorf("Kustomization reconciliation failed")
|
||||
default:
|
||||
logger.Successf("reconciled revision %s", kustomization.Status.LastAppliedRevision)
|
||||
}
|
||||
if apimeta.IsStatusConditionFalse(kustomization.Status.Conditions, meta.ReadyCondition) {
|
||||
return fmt.Errorf("Kustomization reconciliation failed")
|
||||
}
|
||||
logger.Successf("reconciled revision %s", kustomization.Status.LastAppliedRevision)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -64,13 +64,17 @@ func reconcileReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Receiver %s in %s namespace", name, namespace)
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if receiver.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Receiver %s in %s namespace", name, namespace)
|
||||
if receiver.Annotations == nil {
|
||||
receiver.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
|
||||
@@ -21,11 +21,14 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"k8s.io/client-go/util/retry"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -65,35 +68,34 @@ func reconcileSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Bucket source %s in %s namespace", name, namespace)
|
||||
var bucket sourcev1.Bucket
|
||||
err = kubeClient.Get(ctx, namespacedName, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bucket.Annotations == nil {
|
||||
bucket.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
bucket.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
if bucket.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &bucket); err != nil {
|
||||
|
||||
lastHandledReconcileAt := bucket.Status.LastHandledReconcileAt
|
||||
logger.Actionf("annotating Bucket source %s in %s namespace", name, namespace)
|
||||
if err := requestBucketReconciliation(ctx, kubeClient, namespacedName, &bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket source annotated")
|
||||
|
||||
logger.Waitingf("waiting for Bucket source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isBucketReady(ctx, kubeClient, namespacedName, &bucket)); err != nil {
|
||||
if err := wait.PollImmediate(
|
||||
pollInterval, timeout,
|
||||
bucketReconciliationHandled(ctx, kubeClient, namespacedName, &bucket, lastHandledReconcileAt),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket source reconciliation completed")
|
||||
|
||||
if bucket.Status.Artifact == nil {
|
||||
return fmt.Errorf("Bucket source reconciliation completed but no artifact was found")
|
||||
if apimeta.IsStatusConditionFalse(bucket.Status.Conditions, meta.ReadyCondition) {
|
||||
return fmt.Errorf("Bucket source reconciliation failed")
|
||||
}
|
||||
logger.Successf("fetched revision %s", bucket.Status.Artifact.Revision)
|
||||
return nil
|
||||
@@ -112,14 +114,42 @@ func isBucketReady(ctx context.Context, kubeClient client.Client,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(bucket.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(bucket.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func bucketReconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, bucket *sourcev1.Bucket, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, bucket)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return bucket.Status.LastHandledReconcileAt != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestBucketReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, bucket *sourcev1.Bucket) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
if bucket.Annotations == nil {
|
||||
bucket.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
bucket.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
return kubeClient.Update(ctx, bucket)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ import (
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/client-go/util/retry"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
@@ -63,36 +66,61 @@ func reconcileSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating GitRepository source %s in %s namespace", name, namespace)
|
||||
var gitRepository sourcev1.GitRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &gitRepository)
|
||||
var repository sourcev1.GitRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if gitRepository.Annotations == nil {
|
||||
gitRepository.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
gitRepository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
if repository.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &gitRepository); err != nil {
|
||||
|
||||
logger.Actionf("annotating GitRepository source %s in %s namespace", name, namespace)
|
||||
if err := requestGitRepositoryReconciliation(ctx, kubeClient, namespacedName, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("GitRepository source annotated")
|
||||
|
||||
lastHandledReconcileAt := repository.Status.LastHandledReconcileAt
|
||||
logger.Waitingf("waiting for GitRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, namespacedName, &gitRepository)); err != nil {
|
||||
gitRepositoryReconciliationHandled(ctx, kubeClient, namespacedName, &repository, lastHandledReconcileAt)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("GitRepository source reconciliation completed")
|
||||
|
||||
if gitRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("GitRepository source reconciliation completed but no artifact was found")
|
||||
if apimeta.IsStatusConditionFalse(repository.Status.Conditions, meta.ReadyCondition) {
|
||||
return fmt.Errorf("GitRepository source reconciliation failed")
|
||||
}
|
||||
logger.Successf("fetched revision %s", gitRepository.Status.Artifact.Revision)
|
||||
logger.Successf("fetched revision %s", repository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func gitRepositoryReconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.GitRepository, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, repository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return repository.Status.LastHandledReconcileAt != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestGitRepositoryReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.GitRepository) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if repository.Annotations == nil {
|
||||
repository.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
repository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
return kubeClient.Update(ctx, repository)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -21,11 +21,13 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"k8s.io/client-go/util/retry"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -65,61 +67,61 @@ func reconcileSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating HelmRepository source %s in %s namespace", name, namespace)
|
||||
var helmRepository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRepository)
|
||||
var repository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if helmRepository.Annotations == nil {
|
||||
helmRepository.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
helmRepository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
if repository.Spec.Suspend {
|
||||
return fmt.Errorf("resource is suspended")
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &helmRepository); err != nil {
|
||||
|
||||
logger.Actionf("annotating HelmRepository source %s in %s namespace", name, namespace)
|
||||
if err := requestHelmRepositoryReconciliation(ctx, kubeClient, namespacedName, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository source annotated")
|
||||
|
||||
lastHandledReconcileAt := repository.Status.LastHandledReconcileAt
|
||||
logger.Waitingf("waiting for HelmRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmRepositoryReady(ctx, kubeClient, namespacedName, &helmRepository)); err != nil {
|
||||
helmRepositoryReconciliationHandled(ctx, kubeClient, namespacedName, &repository, lastHandledReconcileAt)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository source reconciliation completed")
|
||||
|
||||
if helmRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("HelmRepository source reconciliation completed but no artifact was found")
|
||||
if apimeta.IsStatusConditionFalse(repository.Status.Conditions, meta.ReadyCondition) {
|
||||
return fmt.Errorf("HelmRepository source reconciliation failed")
|
||||
}
|
||||
logger.Successf("fetched revision %s", helmRepository.Status.Artifact.Revision)
|
||||
logger.Successf("fetched revision %s", repository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHelmRepositoryReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRepository *sourcev1.HelmRepository) wait.ConditionFunc {
|
||||
func helmRepositoryReconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.HelmRepository, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRepository)
|
||||
err := kubeClient.Get(ctx, namespacedName, repository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if helmRepository.Generation != helmRepository.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(helmRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
return repository.Status.LastHandledReconcileAt != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestHelmRepositoryReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.HelmRepository) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if repository.Annotations == nil {
|
||||
repository.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
repository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
return kubeClient.Update(ctx, repository)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -17,7 +17,14 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
var resumeCmd = &cobra.Command{
|
||||
@@ -29,3 +36,56 @@ var resumeCmd = &cobra.Command{
|
||||
func init() {
|
||||
rootCmd.AddCommand(resumeCmd)
|
||||
}
|
||||
|
||||
type resumable interface {
|
||||
adapter
|
||||
statusable
|
||||
setUnsuspended()
|
||||
successMessage() string
|
||||
}
|
||||
|
||||
type resumeCommand struct {
|
||||
apiType
|
||||
object resumable
|
||||
}
|
||||
|
||||
func (resume resumeCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("%s name is required", resume.humanKind)
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, resume.object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming %s %s in %s namespace", resume.humanKind, name, namespace)
|
||||
resume.object.setUnsuspended()
|
||||
if err := kubeClient.Update(ctx, resume.object.asRuntimeObject()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s resumed", resume.humanKind)
|
||||
|
||||
logger.Waitingf("waiting for %s reconciliation", resume.kind)
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isReady(ctx, kubeClient, namespacedName, resume.object)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("%s reconciliation completed", resume.kind)
|
||||
logger.Successf(resume.object.successMessage())
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ import (
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -95,11 +96,11 @@ func isAlertResumed(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ import (
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -103,14 +104,11 @@ func isHelmReleaseResumed(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
31
cmd/flux/resume_image.go
Normal file
31
cmd/flux/resume_image.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var resumeImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Resume image automation objects",
|
||||
Long: "The resume image sub-commands resume suspended image automation objects.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeCmd.AddCommand(resumeImageCmd)
|
||||
}
|
||||
48
cmd/flux/resume_image_repository.go
Normal file
48
cmd/flux/resume_image_repository.go
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var resumeImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository [name]",
|
||||
Short: "Resume a suspended ImageRepository",
|
||||
Long: `The resume command marks a previously suspended ImageRepository resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing ImageRepository
|
||||
flux resume image repository alpine
|
||||
`,
|
||||
RunE: resumeCommand{
|
||||
apiType: imageRepositoryType,
|
||||
object: imageRepositoryAdapter{&imagev1.ImageRepository{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeImageCmd.AddCommand(resumeImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func (obj imageRepositoryAdapter) getObservedGeneration() int64 {
|
||||
return obj.ImageRepository.Status.ObservedGeneration
|
||||
}
|
||||
|
||||
func (obj imageRepositoryAdapter) setUnsuspended() {
|
||||
obj.ImageRepository.Spec.Suspend = false
|
||||
}
|
||||
48
cmd/flux/resume_image_updateauto.go
Normal file
48
cmd/flux/resume_image_updateauto.go
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var resumeImageUpdateCmd = &cobra.Command{
|
||||
Use: "update [name]",
|
||||
Short: "Resume a suspended ImageUpdateAutomation",
|
||||
Long: `The resume command marks a previously suspended ImageUpdateAutomation resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing ImageUpdateAutomation
|
||||
flux resume image update latest-images
|
||||
`,
|
||||
RunE: resumeCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
object: imageUpdateAutomationAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeImageCmd.AddCommand(resumeImageUpdateCmd)
|
||||
}
|
||||
|
||||
func (obj imageUpdateAutomationAdapter) setUnsuspended() {
|
||||
obj.ImageUpdateAutomation.Spec.Suspend = false
|
||||
}
|
||||
|
||||
func (obj imageUpdateAutomationAdapter) getObservedGeneration() int64 {
|
||||
return obj.ImageUpdateAutomation.Status.ObservedGeneration
|
||||
}
|
||||
@@ -25,7 +25,8 @@ import (
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -102,14 +103,11 @@ func isKustomizationResumed(ctx context.Context, kubeClient client.Client,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ import (
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -96,11 +97,11 @@ func isReceiverResumed(ctx context.Context, kubeClient client.Client,
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
if c := apimeta.FindStatusCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
case metav1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
31
cmd/flux/resume_source.go
Normal file
31
cmd/flux/resume_source.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright 2020 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 (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var resumeSourceCmd = &cobra.Command{
|
||||
Use: "source",
|
||||
Short: "Resume sources",
|
||||
Long: "The resume sub-commands resume a suspended source.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeCmd.AddCommand(resumeSourceCmd)
|
||||
}
|
||||
115
cmd/flux/resume_source_bucket.go
Normal file
115
cmd/flux/resume_source_bucket.go
Normal file
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket [name]",
|
||||
Short: "Resume a suspended Bucket",
|
||||
Long: `The resume command marks a previously suspended Bucket resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing Bucket
|
||||
flux resume source bucket podinfo
|
||||
`,
|
||||
RunE: resumeSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeSourceCmd.AddCommand(resumeSourceBucketCmd)
|
||||
}
|
||||
|
||||
func resumeSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var bucket sourcev1.Bucket
|
||||
err = kubeClient.Get(ctx, namespacedName, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming source %s in %s namespace", name, namespace)
|
||||
bucket.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source resumed")
|
||||
|
||||
logger.Waitingf("waiting for Bucket reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isBucketResumed(ctx, kubeClient, namespacedName, &bucket)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket reconciliation completed")
|
||||
|
||||
logger.Successf("fetched revision %s", bucket.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isBucketResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, bucket *sourcev1.Bucket) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, bucket)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if bucket.Generation != bucket.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(bucket.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
115
cmd/flux/resume_source_chart.go
Normal file
115
cmd/flux/resume_source_chart.go
Normal file
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeSourceHelmChartCmd = &cobra.Command{
|
||||
Use: "chart [name]",
|
||||
Short: "Resume a suspended HelmChart",
|
||||
Long: `The resume command marks a previously suspended HelmChart resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing HelmChart
|
||||
flux resume source chart podinfo
|
||||
`,
|
||||
RunE: resumeSourceHelmChartCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeSourceCmd.AddCommand(resumeSourceHelmChartCmd)
|
||||
}
|
||||
|
||||
func resumeSourceHelmChartCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var repository sourcev1.HelmChart
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming source %s in %s namespace", name, namespace)
|
||||
repository.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source resumed")
|
||||
|
||||
logger.Waitingf("waiting for HelmChart reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmChartResumed(ctx, kubeClient, namespacedName, &repository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmChart reconciliation completed")
|
||||
|
||||
logger.Successf("fetched revision %s", repository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHelmChartResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, chart *sourcev1.HelmChart) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, chart)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if chart.Generation != chart.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(chart.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
115
cmd/flux/resume_source_git.go
Normal file
115
cmd/flux/resume_source_git.go
Normal file
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeSourceGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Resume a suspended GitRepository",
|
||||
Long: `The resume command marks a previously suspended GitRepository resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing GitRepository
|
||||
flux resume source git podinfo
|
||||
`,
|
||||
RunE: resumeSourceGitCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeSourceCmd.AddCommand(resumeSourceGitCmd)
|
||||
}
|
||||
|
||||
func resumeSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var repository sourcev1.GitRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming source %s in %s namespace", name, namespace)
|
||||
repository.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source resumed")
|
||||
|
||||
logger.Waitingf("waiting for GitRepository reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryResumed(ctx, kubeClient, namespacedName, &repository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("GitRepository reconciliation completed")
|
||||
|
||||
logger.Successf("fetched revision %s", repository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isGitRepositoryResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.GitRepository) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, repository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if repository.Generation != repository.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(repository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
115
cmd/flux/resume_source_helm.go
Normal file
115
cmd/flux/resume_source_helm.go
Normal file
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Resume a suspended HelmRepository",
|
||||
Long: `The resume command marks a previously suspended HelmRepository resource for reconciliation and waits for it to finish.`,
|
||||
Example: ` # Resume reconciliation for an existing HelmRepository
|
||||
flux resume source helm bitnami
|
||||
`,
|
||||
RunE: resumeSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeSourceCmd.AddCommand(resumeSourceHelmCmd)
|
||||
}
|
||||
|
||||
func resumeSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var repository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming source %s in %s namespace", name, namespace)
|
||||
repository.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source resumed")
|
||||
|
||||
logger.Waitingf("waiting for HelmRepository reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmRepositoryResumed(ctx, kubeClient, namespacedName, &repository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository reconciliation completed")
|
||||
|
||||
logger.Successf("fetched revision %s", repository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHelmRepositoryResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, repository *sourcev1.HelmRepository) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, repository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if repository.Generation != repository.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(repository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
65
cmd/flux/status.go
Normal file
65
cmd/flux/status.go
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
// statusable is used to see if a resource is considered ready in the usual way
|
||||
type statusable interface {
|
||||
adapter
|
||||
// this is implemented by ObjectMeta
|
||||
GetGeneration() int64
|
||||
getObservedGeneration() int64
|
||||
// this is usually implemented by GOTK API objects because it's used by pkg/apis/meta
|
||||
GetStatusConditions() *[]metav1.Condition
|
||||
}
|
||||
|
||||
func isReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, object statusable) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, object.asRuntimeObject())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if object.GetGeneration() != object.getObservedGeneration() {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := apimeta.FindStatusCondition(*object.GetStatusConditions(), meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case metav1.ConditionTrue:
|
||||
return true, nil
|
||||
case metav1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user