Chore: use functions from kubevela/pkg (#4693)

* Chore: use functions from kubevela/pkg

Signed-off-by: Somefive <yd219913@alibaba-inc.com>

* Chore: rename multiclusterpkg to pkgmulticluster

Signed-off-by: Somefive <yd219913@alibaba-inc.com>

Signed-off-by: Somefive <yd219913@alibaba-inc.com>
This commit is contained in:
Somefive
2022-09-09 15:10:18 +08:00
committed by GitHub
parent 15004d9ad8
commit cea9ef5c97
36 changed files with 111 additions and 974 deletions

View File

@@ -29,6 +29,7 @@ import (
"strconv"
"time"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
flag "github.com/spf13/pflag"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/klog/v2"
@@ -36,6 +37,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
velaclient "github.com/kubevela/pkg/controller/client"
"github.com/kubevela/workflow/pkg/cue/packages"
_ "github.com/kubevela/workflow/pkg/features"
wfTypes "github.com/kubevela/workflow/pkg/types"
@@ -43,7 +45,6 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/auth"
ctrlClient "github.com/oam-dev/kubevela/pkg/client"
standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
@@ -149,6 +150,7 @@ func main() {
flag.IntVar(&wfTypes.MaxWorkflowWaitBackoffTime, "max-workflow-wait-backoff-time", 60, "Set the max workflow wait backoff time, default is 60")
flag.IntVar(&wfTypes.MaxWorkflowFailedBackoffTime, "max-workflow-failed-backoff-time", 300, "Set the max workflow wait backoff time, default is 300")
flag.IntVar(&wfTypes.MaxWorkflowStepErrorRetryTimes, "max-workflow-step-error-retry-times", 10, "Set the max workflow step error retry times, default is 10")
pkgmulticluster.AddClusterGatewayClientFlags(flag.CommandLine)
utilfeature.DefaultMutableFeatureGate.AddFlag(flag.CommandLine)
// setup logging
@@ -256,7 +258,7 @@ func main() {
// of controller-runtime. Additionally, set this value will affect not only application
// controller but also all other controllers like definition controller. Therefore, for
// functionalities like state-keep, they should be invented in other ways.
NewClient: ctrlClient.DefaultNewControllerClient,
NewClient: velaclient.DefaultNewControllerClient,
})
if err != nil {
klog.ErrorS(err, "Unable to create a controller manager")

21
go.mod
View File

@@ -53,7 +53,7 @@ require (
github.com/imdario/mergo v0.3.12
github.com/klauspost/compress v1.15.9
github.com/koding/websocketproxy v0.0.0-20181220232114-7ed82d81a28c
github.com/kubevela/pkg v0.0.0-20220905083925-331e331a12e1
github.com/kubevela/pkg v0.0.0-20220907071953-81b2807e4bd1
github.com/kubevela/prism v1.4.1-0.20220613123457-94f1190f87c2
github.com/kubevela/workflow v0.0.0-20220905111757-ae9387b554de
github.com/kyokomi/emoji v2.2.4+incompatible
@@ -115,7 +115,6 @@ require (
)
require (
cloud.google.com/go/compute v1.7.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest v0.11.18 // indirect
@@ -200,8 +199,6 @@ require (
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/huandu/xstrings v1.3.2 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
@@ -211,7 +208,6 @@ require (
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/kr/text v0.2.0 // indirect
@@ -244,8 +240,6 @@ require (
github.com/nxadm/tail v1.4.8 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 // indirect
github.com/opencontainers/runc v1.1.3 // indirect
github.com/openkruise/rollouts v0.1.1-0.20220622054609-149e5a48da5e
github.com/openshift/library-go v0.0.0-20220112153822-ac82336bd076 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
@@ -267,7 +261,6 @@ require (
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tjfoc/gmsm v1.3.2 // indirect
github.com/xanzy/ssh-agent v0.3.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.0.2 // indirect
github.com/xdg-go/stringprep v1.0.2 // indirect
@@ -301,7 +294,6 @@ require (
golang.org/x/time v0.0.0-20220224211638-0e9765cccd65 // indirect
golang.org/x/tools v0.1.12 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03 // indirect
google.golang.org/grpc v1.47.0 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
@@ -326,6 +318,17 @@ require (
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect
)
require (
cloud.google.com/go/compute v1.7.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.0 // indirect
github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 // indirect
github.com/opencontainers/runc v1.1.3 // indirect
github.com/openkruise/rollouts v0.1.1-0.20220622054609-149e5a48da5e
github.com/xanzy/ssh-agent v0.3.0 // indirect
google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03 // indirect
)
replace (
github.com/docker/cli => github.com/docker/cli v20.10.9+incompatible
github.com/docker/docker => github.com/moby/moby v17.12.0-ce-rc1.0.20200618181300-9dc6525e6118+incompatible

16
go.sum
View File

@@ -1378,8 +1378,9 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kubevela/pkg v0.0.0-20220905083925-331e331a12e1 h1:T7I0/LE5t4MZMScwsQsW1u9LqHtVx1J+3KFRFIsj1uQ=
github.com/kubevela/pkg v0.0.0-20220905083925-331e331a12e1/go.mod h1:281yP5rMV+jYzxngUtM/FeZvAbqWEIow9tSamHHcDvI=
github.com/kubevela/pkg v0.0.0-20220907071953-81b2807e4bd1 h1:kYz+x/AKtdXzWuciMSxavF7Y6dxcdaJ+OwMqe/7vvvY=
github.com/kubevela/pkg v0.0.0-20220907071953-81b2807e4bd1/go.mod h1:281yP5rMV+jYzxngUtM/FeZvAbqWEIow9tSamHHcDvI=
github.com/kubevela/prism v1.4.1-0.20220613123457-94f1190f87c2 h1:TaHlO4raKI3ehVSYY8QixYMHdI0VwKHY1KPNWcUre3I=
github.com/kubevela/prism v1.4.1-0.20220613123457-94f1190f87c2/go.mod h1:RP69+bRb57Occer6BeeF5zK3hrD1IhnYf2RNRsIdh9E=
github.com/kubevela/workflow v0.0.0-20220905111757-ae9387b554de h1:n5vkROgxW64Jq+Or6Ku9w/PDPRNypav2Ud1vJDxukWs=
@@ -1644,8 +1645,6 @@ github.com/onsi/ginkgo v1.16.1/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvw
github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU=
@@ -2254,7 +2253,6 @@ go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
golang.org/x/arch v0.0.0-20180920145803-b19384d3c130/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
@@ -2431,7 +2429,6 @@ golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211215060638-4ddde0e984e9/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
@@ -3163,7 +3160,6 @@ k8s.io/api v0.21.3/go.mod h1:hUgeYHUbBp23Ue4qdX9tR8/ANi/g3ehylAqDn9NWVOg=
k8s.io/api v0.22.1/go.mod h1:bh13rkTp3F1XEaLGykbyRD2QaTTzPm0e/BMd8ptFONY=
k8s.io/api v0.22.2/go.mod h1:y3ydYpLJAaDI+BbSe2xmGcqxiWHmWjkEeIbiwHvnPR8=
k8s.io/api v0.22.4/go.mod h1:Rgs+9gIGYC5laXQSZZ9JqT5NevNgoGiOdVWi1BAB3qk=
k8s.io/api v0.22.4/go.mod h1:Rgs+9gIGYC5laXQSZZ9JqT5NevNgoGiOdVWi1BAB3qk=
k8s.io/api v0.22.6/go.mod h1:q1F7IfaNrbi/83ebLy3YFQYLjPSNyunZ/IXQxMmbwCg=
k8s.io/api v0.23.0/go.mod h1:8wmDdLBHBNxtOIytwLstXt5E9PddnZb0GaMcqsvDBpg=
k8s.io/api v0.23.1/go.mod h1:WfXnOnwSqNtG62Y1CdjoMxh7r7u9QXGCkA1u0na2jgo=
@@ -3235,7 +3231,6 @@ k8s.io/apiserver v0.21.3/go.mod h1:eDPWlZG6/cCCMj/JBcEpDoK+I+6i3r9GsChYBHSbAzU=
k8s.io/apiserver v0.22.1/go.mod h1:2mcM6dzSt+XndzVQJX21Gx0/Klo7Aen7i0Ai6tIa400=
k8s.io/apiserver v0.22.2/go.mod h1:vrpMmbyjWrgdyOvZTSpsusQq5iigKNWv9o9KlDAbBHI=
k8s.io/apiserver v0.22.4/go.mod h1:38WmcUZiiy41A7Aty8/VorWRa8vDGqoUzDf2XYlku0E=
k8s.io/apiserver v0.22.4/go.mod h1:38WmcUZiiy41A7Aty8/VorWRa8vDGqoUzDf2XYlku0E=
k8s.io/apiserver v0.22.6/go.mod h1:OlL1rGa2kKWGj2JEXnwBcul/BwC9Twe95gm4ohtiIIs=
k8s.io/apiserver v0.23.0/go.mod h1:Cec35u/9zAepDPPFyT+UMrgqOCjgJ5qtfVJDxjZYmt4=
k8s.io/apiserver v0.23.1/go.mod h1:Bqt0gWbeM2NefS8CjWswwd2VNAKN6lUKR85Ft4gippY=
@@ -3288,7 +3283,6 @@ k8s.io/code-generator v0.18.2/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRV
k8s.io/code-generator v0.18.6/go.mod h1:TgNEVx9hCyPGpdtCWA34olQYLkh3ok9ar7XfSsr8b6c=
k8s.io/code-generator v0.20.0/go.mod h1:UsqdF+VX4PU2g46NC2JRs4gc+IfrctnwHb76RNbWHJg=
k8s.io/code-generator v0.20.10/go.mod h1:i6FmG+QxaLxvJsezvZp0q/gAEzzOz3U53KFibghWToU=
k8s.io/code-generator v0.20.10/go.mod h1:i6FmG+QxaLxvJsezvZp0q/gAEzzOz3U53KFibghWToU=
k8s.io/code-generator v0.21.2/go.mod h1:8mXJDCB7HcRo1xiEQstcguZkbxZaqeUOrO9SsicWs3U=
k8s.io/code-generator v0.21.3/go.mod h1:K3y0Bv9Cz2cOW2vXUrNZlFbflhuPvuadW6JdnN6gGKo=
k8s.io/code-generator v0.22.0/go.mod h1:eV77Y09IopzeXOJzndrDyCI88UBok2h6WxAlBwpxa+o=
@@ -3373,7 +3367,6 @@ k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAG
k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7/go.mod h1:wXW5VT87nVfh/iLV8FpR2uDvrFyomxbtb1KivDbvPTE=
k8s.io/kube-openapi v0.0.0-20210421082810-95288971da7e/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw=
k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw=
k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw=
k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65 h1:E3J9oCLlaobFUqsjG9DfKbP2BmgwBL2p7pn0A3dG9W4=
k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk=
k8s.io/kubectl v0.0.0-20191219154910-1528d4eea6dd/go.mod h1:9ehGcuUGjXVZh0qbYSB0vvofQw2JQe6c6cO0k4wu/Oo=
@@ -3401,7 +3394,6 @@ k8s.io/utils v0.0.0-20210707171843-4b05e18ac7d9/go.mod h1:jPW/WVKK9YHAvNhRxK0md/
k8s.io/utils v0.0.0-20210722164352-7f3ee0f31471/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20210820185131-d34e5cb4466e/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
k8s.io/utils v0.0.0-20211116205334-6203023598ed/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
@@ -3490,11 +3482,7 @@ sigs.k8s.io/structured-merge-diff/v4 v4.1.0/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK
sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4=
sigs.k8s.io/structured-merge-diff/v4 v4.2.0/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4=
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 h1:bKCqE9GvQ5tiVHn5rfn1r+yao3aLQEaLzkkmAkf+A6Y=
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 h1:bKCqE9GvQ5tiVHn5rfn1r+yao3aLQEaLzkkmAkf+A6Y=
sigs.k8s.io/structured-merge-diff/v4 v4.2.1/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4=
sigs.k8s.io/structured-merge-diff/v4 v4.2.1/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4=
sigs.k8s.io/structured-merge-diff/v4 v4.2.1/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4=
sigs.k8s.io/testing_frameworks v0.1.2/go.mod h1:ToQrwSC3s8Xf/lADdZp3Mktcql9CG0UAmdJG9th5i0w=
sigs.k8s.io/testing_frameworks v0.1.2/go.mod h1:ToQrwSC3s8Xf/lADdZp3Mktcql9CG0UAmdJG9th5i0w=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc=

View File

@@ -24,9 +24,6 @@ import (
"strings"
"time"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
"github.com/oam-dev/terraform-controller/api/types"
"github.com/oam-dev/terraform-controller/api/v1beta1"
"github.com/pkg/errors"
v12 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
@@ -34,6 +31,11 @@ import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubevela/pkg/util/rand"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
"github.com/oam-dev/terraform-controller/api/types"
"github.com/oam-dev/terraform-controller/api/v1beta1"
velatypes "github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/apiserver/domain/model"
"github.com/oam-dev/kubevela/pkg/apiserver/infrastructure/clients"
@@ -197,7 +199,7 @@ func (c *clusterServiceImpl) ListKubeClusters(ctx context.Context, query string,
}
func joinClusterByKubeConfigString(ctx context.Context, k8sClient client.Client, clusterName string, kubeConfig string) (string, error) {
tmpFileName := fmt.Sprintf("/tmp/cluster-secret-%s-%d.kubeconfig", utils.RandomString(8), time.Now().UnixNano())
tmpFileName := fmt.Sprintf("/tmp/cluster-secret-%s-%d.kubeconfig", rand.RandomString(8), time.Now().UnixNano())
if err := ioutil.WriteFile(tmpFileName, []byte(kubeConfig), 0600); err != nil {
return "", errors.Wrapf(err, "failed to write kubeconfig to temp file %s", tmpFileName)
}
@@ -329,7 +331,7 @@ func (c *clusterServiceImpl) ModifyKubeCluster(ctx context.Context, req apis.Cre
if newCluster.KubeConfig == "" && newCluster.KubeConfigSecret != "" {
return nil, bcode.ErrKubeConfigSecretNotSupport
}
newClusterTempName := newCluster.Name + "_tmp_" + utils.RandomString(8)
newClusterTempName := newCluster.Name + "_tmp_" + rand.RandomString(8)
newCluster.APIServerURL, err = joinClusterByKubeConfigString(ctx, c.K8sClient, newCluster.Name, newCluster.KubeConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to join new cluster %s", newCluster.Name)

View File

@@ -20,21 +20,22 @@ import (
"context"
"time"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
clustergatewayv1alpha1 "github.com/oam-dev/cluster-gateway/pkg/apis/cluster/v1alpha1"
clustergatewaycommon "github.com/oam-dev/cluster-gateway/pkg/common"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubevela/pkg/util/rand"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
clustergatewayv1alpha1 "github.com/oam-dev/cluster-gateway/pkg/apis/cluster/v1alpha1"
clustergatewaycommon "github.com/oam-dev/cluster-gateway/pkg/common"
"github.com/oam-dev/kubevela/pkg/apiserver/domain/model"
"github.com/oam-dev/kubevela/pkg/apiserver/infrastructure/datastore"
"github.com/oam-dev/kubevela/pkg/apiserver/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/utils/bcode"
"github.com/oam-dev/kubevela/pkg/oam/util"
pkgutil "github.com/oam-dev/kubevela/pkg/utils"
)
var _ = Describe("Test cluster service function", func() {
@@ -46,7 +47,7 @@ var _ = Describe("Test cluster service function", func() {
)
BeforeEach(func() {
ds, err = NewDatastore(datastore.Config{Type: "kubeapi", Database: "cluster-test-kubevela-" + pkgutil.RandomString(4)})
ds, err = NewDatastore(datastore.Config{Type: "kubeapi", Database: "cluster-test-kubevela-" + rand.RandomString(4)})
Expect(err).Should(Succeed())
cache = utils.NewMemoryCacheStore(context.Background())
ctx = context.Background()

View File

@@ -37,6 +37,7 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
velaclient "github.com/kubevela/pkg/controller/client"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/kubevela/workflow/pkg/cue/model/value"
"github.com/kubevela/workflow/pkg/cue/process"
@@ -47,7 +48,6 @@ import (
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/helm"
"github.com/oam-dev/kubevela/pkg/auth"
velaclient "github.com/oam-dev/kubevela/pkg/client"
"github.com/oam-dev/kubevela/pkg/component"
"github.com/oam-dev/kubevela/pkg/cue/definition"
velaprocess "github.com/oam-dev/kubevela/pkg/cue/process"

View File

@@ -31,6 +31,7 @@ import (
utilfeature "k8s.io/apiserver/pkg/util/feature"
"sigs.k8s.io/controller-runtime/pkg/client"
monitorContext "github.com/kubevela/pkg/monitor/context"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/kubevela/workflow/pkg/cue/packages"
@@ -42,7 +43,6 @@ import (
"github.com/oam-dev/kubevela/pkg/component"
"github.com/oam-dev/kubevela/pkg/cue/definition"
"github.com/oam-dev/kubevela/pkg/features"
monitorContext "github.com/oam-dev/kubevela/pkg/monitor/context"
"github.com/oam-dev/kubevela/pkg/monitor/metrics"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/oam/discoverymapper"

View File

@@ -1,115 +0,0 @@
/*
Copyright 2021 The KubeVela 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 client
import (
"context"
"strings"
"sync"
"github.com/oam-dev/kubevela/pkg/resourcetracker"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest"
cache2 "k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/monitor/metrics"
)
var (
// CachedGVKs identifies the GVKs of resources to be cached during dispatching
CachedGVKs = ""
rtCount = 0
lock = sync.Mutex{}
)
// DefaultNewControllerClient function for creating controller client
func DefaultNewControllerClient(cache cache.Cache, config *rest.Config, options client.Options, uncachedObjects ...client.Object) (c client.Client, err error) {
rawClient, err := client.New(config, options)
if err != nil {
return nil, errors.Wrapf(err, "failed to get raw client")
}
mClient := &monitorClient{rawClient}
if err := resourcetracker.AddResourceTrackerCacheIndex(cache); err != nil {
return nil, errors.Wrapf(err, "failed to add app index to ResourceTracker cache")
}
mCache := &monitorCache{cache}
uncachedStructuredGVKs := map[schema.GroupVersionKind]struct{}{}
for _, obj := range uncachedObjects {
gvk, err := apiutil.GVKForObject(obj, mClient.Scheme())
if err != nil {
return nil, err
}
uncachedStructuredGVKs[gvk] = struct{}{}
}
cachedUnstructuredGVKs := map[schema.GroupVersionKind]struct{}{}
for _, s := range strings.Split(CachedGVKs, ",") {
s = strings.Trim(s, " ")
if len(s) > 0 {
gvk, _ := schema.ParseKindArg(s)
if gvk == nil {
return nil, errors.Errorf("invalid cached gvk: %s", s)
}
cachedUnstructuredGVKs[*gvk] = struct{}{}
}
}
informer, err := cache.GetInformerForKind(context.Background(), v1beta1.ResourceTrackerKindVersionKind)
if err != nil {
return nil, err
}
informer.AddEventHandler(cache2.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
lock.Lock()
rtCount++
metrics.ResourceTrackerNumberGauge.WithLabelValues("application").Set(float64(rtCount))
lock.Unlock()
},
DeleteFunc: func(obj interface{}) {
lock.Lock()
rtCount--
metrics.ResourceTrackerNumberGauge.WithLabelValues("application").Set(float64(rtCount))
lock.Unlock()
},
})
dClient := &delegatingClient{
scheme: mClient.Scheme(),
mapper: mClient.RESTMapper(),
Reader: &delegatingReader{
CacheReader: mCache,
ClientReader: mClient,
scheme: mClient.Scheme(),
uncachedStructuredGVKs: uncachedStructuredGVKs,
cachedUnstructuredGVKs: cachedUnstructuredGVKs,
},
Writer: mClient,
StatusClient: mClient,
}
return dClient, nil
}

View File

@@ -1,107 +0,0 @@
/*
Copyright 2021 The KubeVela 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 client
import (
"context"
"strings"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/resourcetracker"
)
type delegatingClient struct {
client.Reader
client.Writer
client.StatusClient
scheme *runtime.Scheme
mapper meta.RESTMapper
}
// Scheme returns the scheme this client is using.
func (d *delegatingClient) Scheme() *runtime.Scheme {
return d.scheme
}
// RESTMapper returns the rest mapper this client is using.
func (d *delegatingClient) RESTMapper() meta.RESTMapper {
return d.mapper
}
// delegatingReader extend the delegatingReader from controller-runtime/pkg/client
// 1. for requests not in local cluster, disable cache
// 2. for structured types, inherit the cache blacklist
// 3. for unstructured types, use cache whitelist
type delegatingReader struct {
CacheReader client.Reader
ClientReader client.Reader
uncachedStructuredGVKs map[schema.GroupVersionKind]struct{}
cachedUnstructuredGVKs map[schema.GroupVersionKind]struct{}
scheme *runtime.Scheme
}
func (d *delegatingReader) shouldBypassCache(ctx context.Context, obj runtime.Object) (bool, error) {
// non-local resource cannot use cache
if !multicluster.IsInLocalCluster(ctx) {
return true, nil
}
gvk, err := apiutil.GVKForObject(obj, d.scheme)
if err != nil {
return false, err
}
if meta.IsListType(obj) {
gvk.Kind = strings.TrimSuffix(gvk.Kind, "List")
}
_, isUnstructured := obj.(*unstructured.Unstructured)
_, isUnstructuredList := obj.(*unstructured.UnstructuredList)
if isUnstructured || isUnstructuredList {
_, shouldCache := d.cachedUnstructuredGVKs[gvk]
return !shouldCache, nil
}
_, shouldNotCache := d.uncachedStructuredGVKs[gvk]
return shouldNotCache, nil
}
// Get retrieves an obj for a given object key from the Kubernetes Cluster.
func (d *delegatingReader) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error {
if isUncached, err := d.shouldBypassCache(ctx, obj); err != nil {
return err
} else if isUncached {
return d.ClientReader.Get(ctx, key, obj)
}
return d.CacheReader.Get(ctx, key, obj)
}
// List retrieves list of objects for a given namespace and list options.
func (d *delegatingReader) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
opts = resourcetracker.ExtendResourceTrackerListOption(list, opts)
if isUncached, err := d.shouldBypassCache(ctx, list); err != nil {
return err
} else if isUncached {
return d.ClientReader.List(ctx, list, opts...)
}
return d.CacheReader.List(ctx, list, opts...)
}

View File

@@ -1,46 +0,0 @@
/*
Copyright 2021 The KubeVela 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 client
import (
"context"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// DelegatingHandlerClient override the original client's function
type DelegatingHandlerClient struct {
client.Client
Getter func(ctx context.Context, key client.ObjectKey, obj client.Object) error
Lister func(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error
}
// Get resource by overridden getter
func (c DelegatingHandlerClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error {
if c.Getter != nil {
return c.Getter(ctx, key, obj)
}
return c.Client.Get(ctx, key, obj)
}
// List resource by overridden lister
func (c DelegatingHandlerClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
if c.Lister != nil {
return c.Lister(ctx, list, opts...)
}
return c.Client.List(ctx, list, opts...)
}

View File

@@ -1,142 +0,0 @@
/*
Copyright 2021 The KubeVela 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 client
import (
"context"
"reflect"
"strings"
"time"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/pkg/monitor/metrics"
"github.com/oam-dev/kubevela/pkg/multicluster"
)
func monitor(ctx context.Context, verb string, obj runtime.Object) func() {
o := obj.GetObjectKind().GroupVersionKind()
_, isUnstructured := obj.(*unstructured.Unstructured)
_, isUnstructuredList := obj.(*unstructured.UnstructuredList)
un := "structured"
if isUnstructured || isUnstructuredList {
un = "unstructured"
}
clusterName := multicluster.ClusterNameInContext(ctx)
if clusterName == "" {
clusterName = multicluster.ClusterLocalName
}
kind := o.Kind
if kind == "" {
if t := reflect.TypeOf(obj); t.Kind() == reflect.Ptr {
kind = t.Elem().Name()
} else {
kind = t.Name()
}
}
kind = strings.TrimSuffix(kind, "List")
begin := time.Now()
return func() {
v := time.Since(begin).Seconds()
metrics.ClientRequestHistogram.WithLabelValues(verb, kind, o.GroupVersion().String(), un, clusterName).Observe(v)
}
}
type monitorCache struct {
cache.Cache
}
func (c *monitorCache) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error {
cb := monitor(ctx, "GetCache", obj)
defer cb()
return c.Cache.Get(ctx, key, obj)
}
func (c *monitorCache) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
cb := monitor(ctx, "ListCache", list)
defer cb()
return c.Cache.List(ctx, list, opts...)
}
type monitorClient struct {
client.Client
}
func (c *monitorClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error {
cb := monitor(ctx, "Get", obj)
defer cb()
return c.Client.Get(ctx, key, obj)
}
func (c *monitorClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
cb := monitor(ctx, "List", list)
defer cb()
return c.Client.List(ctx, list, opts...)
}
func (c *monitorClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error {
cb := monitor(ctx, "Create", obj)
defer cb()
return c.Client.Create(ctx, obj, opts...)
}
func (c *monitorClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {
cb := monitor(ctx, "Delete", obj)
defer cb()
return c.Client.Delete(ctx, obj, opts...)
}
func (c *monitorClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error {
cb := monitor(ctx, "Update", obj)
defer cb()
return c.Client.Update(ctx, obj, opts...)
}
func (c *monitorClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
cb := monitor(ctx, "Patch", obj)
defer cb()
return c.Client.Patch(ctx, obj, patch, opts...)
}
func (c *monitorClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error {
cb := monitor(ctx, "DeleteAllOf", obj)
defer cb()
return c.Client.DeleteAllOf(ctx, obj, opts...)
}
func (c *monitorClient) Status() client.StatusWriter {
return &monitorStatusWriter{c.Client.Status()}
}
type monitorStatusWriter struct {
client.StatusWriter
}
func (w *monitorStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error {
cb := monitor(ctx, "StatusUpdate", obj)
defer cb()
return w.StatusWriter.Update(ctx, obj, opts...)
}
func (w *monitorStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
cb := monitor(ctx, "StatusPatch", obj)
defer cb()
return w.StatusWriter.Patch(ctx, obj, patch, opts...)
}

View File

@@ -23,8 +23,9 @@ import (
"k8s.io/client-go/util/flowcontrol"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubevela/pkg/multicluster"
cmdutil "github.com/oam-dev/kubevela/pkg/cmd/util"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/utils/common"
)
@@ -96,7 +97,7 @@ func (f *defaultFactory) Config() *rest.Config {
func NewDefaultFactory(cfg *rest.Config) Factory {
copiedCfg := *cfg
copiedCfg.RateLimiter = DefaultRateLimiter
copiedCfg.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
copiedCfg.Wrap(multicluster.NewTransportWrapper())
return &defaultFactory{cfg: &copiedCfg}
}

View File

@@ -32,9 +32,10 @@ import (
utilfeature "k8s.io/apiserver/pkg/util/feature"
"sigs.k8s.io/controller-runtime/pkg/client"
velaclient "github.com/kubevela/pkg/controller/client"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
velaclient "github.com/oam-dev/kubevela/pkg/client"
"github.com/oam-dev/kubevela/pkg/features"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"

View File

@@ -20,9 +20,6 @@ import (
"context"
"sync"
terraformtypes "github.com/oam-dev/terraform-controller/api/types"
terraforv1beta1 "github.com/oam-dev/terraform-controller/api/v1beta1"
terraforv1beta2 "github.com/oam-dev/terraform-controller/api/v1beta2"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
@@ -30,11 +27,16 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
monitorContext "github.com/kubevela/pkg/monitor/context"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
terraformtypes "github.com/oam-dev/terraform-controller/api/types"
terraforv1beta1 "github.com/oam-dev/terraform-controller/api/v1beta1"
terraforv1beta2 "github.com/oam-dev/terraform-controller/api/v1beta2"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile"
monitorContext "github.com/oam-dev/kubevela/pkg/monitor/context"
"github.com/oam-dev/kubevela/pkg/monitor/metrics"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"
@@ -265,7 +267,7 @@ func (h *AppHandler) collectHealthStatus(ctx context.Context, wl *appfile.Worklo
traitOverrideNamespace := overrideNamespace
if tr.FullTemplate.TraitDefinition.Spec.ControlPlaneOnly {
traitOverrideNamespace = appRev.GetNamespace()
wl.Ctx.SetCtx(context.WithValue(wl.Ctx.GetCtx(), multicluster.ClusterContextKey, multicluster.ClusterLocalName))
wl.Ctx.SetCtx(pkgmulticluster.WithCluster(wl.Ctx.GetCtx(), pkgmulticluster.Local))
}
_accessor := util.NewApplicationResourceNamespaceAccessor(h.app.Namespace, traitOverrideNamespace)
var traitStatus = common.ApplicationTraitStatus{
@@ -284,7 +286,7 @@ func (h *AppHandler) collectHealthStatus(ctx context.Context, wl *appfile.Worklo
status.Message = traitStatus.Message
}
traitStatusList = append(traitStatusList, traitStatus)
wl.Ctx.SetCtx(context.WithValue(wl.Ctx.GetCtx(), multicluster.ClusterContextKey, status.Cluster))
wl.Ctx.SetCtx(pkgmulticluster.WithCluster(wl.Ctx.GetCtx(), status.Cluster))
}
status.Traits = traitStatusList

View File

@@ -36,6 +36,7 @@ import (
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
monitorContext "github.com/kubevela/pkg/monitor/context"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
@@ -50,7 +51,6 @@ import (
"github.com/oam-dev/kubevela/pkg/controller/utils"
"github.com/oam-dev/kubevela/pkg/cue/process"
"github.com/oam-dev/kubevela/pkg/features"
monitorContext "github.com/oam-dev/kubevela/pkg/monitor/context"
"github.com/oam-dev/kubevela/pkg/monitor/metrics"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"

View File

@@ -19,11 +19,11 @@ package controller
import (
flag "github.com/spf13/pflag"
velaclient "github.com/kubevela/pkg/controller/client"
wfContext "github.com/kubevela/workflow/pkg/context"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/auth"
ctrlClient "github.com/oam-dev/kubevela/pkg/client"
"github.com/oam-dev/kubevela/pkg/component"
"github.com/oam-dev/kubevela/pkg/controller/core.oam.dev/v1alpha2/application"
"github.com/oam-dev/kubevela/pkg/resourcekeeper"
@@ -34,7 +34,7 @@ import (
// AddOptimizeFlags add flags
func AddOptimizeFlags() {
// optimize client
flag.StringVar(&ctrlClient.CachedGVKs, "optimize-cached-gvks", "", "Types of resources to be cached. For example, --optimize-cached-gvks=Deployment.v1.apps,Job.v1.batch . If you have dedicated resources to be managed in your system, you can turn it on to improve performance. NOTE: this optimization only works for single-cluster.")
flag.StringVar(&velaclient.CachedGVKs, "optimize-cached-gvks", "", "Types of resources to be cached. For example, --optimize-cached-gvks=Deployment.v1.apps,Job.v1.batch . If you have dedicated resources to be managed in your system, you can turn it on to improve performance. NOTE: this optimization only works for single-cluster.")
flag.BoolVar(&resourcetracker.OptimizeListOp, "optimize-resource-tracker-list-op", true, "Optimize ResourceTracker List Op by adding index. This will increase the use of memory and accelerate the list operation of ResourceTracker. Default to enable it . If you want to reduce the memory use of KubeVela, you can switch it off.")
// optimize controller reconcile loop

View File

@@ -1,173 +0,0 @@
/*
Copyright 2021. The KubeVela 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 context
import (
stdctx "context"
"fmt"
"time"
"github.com/oam-dev/kubevela/pkg/utils"
"k8s.io/klog/v2"
)
const (
// spanTagID is the tag name of span ID.
spanTagID = "spanID"
)
// Context keep the trace info
type Context interface {
stdctx.Context
Logger
GetContext() stdctx.Context
SetContext(ctx stdctx.Context)
AddTag(keysAndValues ...interface{}) Context
Fork(name string, exporters ...Exporter) Context
Commit(msg string)
}
// Logger represents the ability to log messages, both errors and not.
type Logger interface {
InfoDepth(depth int, msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Error(err error, msg string, keysAndValues ...interface{})
ErrorDepth(depth int, err error, msg string, keysAndValues ...interface{})
Printf(format string, args ...interface{})
V(level int)
}
type traceContext struct {
stdctx.Context
id string
beginTimestamp time.Time
logLevel int
tags []interface{}
exporters []Exporter
parent *traceContext
}
// Fork a child Context extends parent Context
func (t *traceContext) Fork(id string, exporters ...Exporter) Context {
if id == "" {
id = t.id
} else {
id = t.id + "." + id
}
return &traceContext{
Context: t.Context,
id: id,
tags: copySlice(t.tags),
logLevel: t.logLevel,
parent: t,
beginTimestamp: time.Now(),
exporters: exporters,
}
}
// Commit finish the span record
func (t *traceContext) Commit(msg string) {
msg = fmt.Sprintf("[Finished]: %s(%s)", t.id, msg)
duration := time.Since(t.beginTimestamp)
for _, export := range t.exporters {
export(t, duration.Seconds())
}
if t.logLevel == 0 {
klog.InfoSDepth(1, msg, t.getTagsWith("duration", duration.String())...)
}
}
func (t *traceContext) getTagsWith(keysAndValues ...interface{}) []interface{} {
tags := t.tags
tags = append(tags, keysAndValues...)
return append(tags, spanTagID, t.id)
}
// Info logs a non-error message with the given key/value pairs as context.
func (t *traceContext) Info(msg string, keysAndValues ...interface{}) {
klog.InfoSDepth(1, msg, t.getTagsWith(keysAndValues...)...)
}
// GetContext get raw context.
func (t *traceContext) GetContext() stdctx.Context {
return t.Context
}
// SetContext set raw context.
func (t *traceContext) SetContext(ctx stdctx.Context) {
t.Context = ctx
}
// InfoDepth acts as Info but uses depth to determine which call frame to log.
func (t *traceContext) InfoDepth(depth int, msg string, keysAndValues ...interface{}) {
klog.InfoSDepth(depth+1, msg, t.getTagsWith(keysAndValues...)...)
}
// Error logs an error, with the given message and key/value pairs as context.
func (t *traceContext) Error(err error, msg string, keysAndValues ...interface{}) {
klog.ErrorSDepth(1, err, msg, t.getTagsWith(keysAndValues...)...)
}
// ErrorDepth acts as Error but uses depth to determine which call frame to log.
func (t *traceContext) ErrorDepth(depth int, err error, msg string, keysAndValues ...interface{}) {
klog.ErrorSDepth(depth+1, err, msg, t.getTagsWith(keysAndValues...)...)
}
// Printf formats according to a format specifier and logs.
func (t *traceContext) Printf(format string, args ...interface{}) {
klog.InfoSDepth(1, fmt.Sprintf(format, args...), t.getTagsWith()...)
}
// V reports whether verbosity at the call site is at least the requested level.
func (t *traceContext) V(level int) {
t.logLevel = level
}
// AddTag adds some key-value pairs of context to a logger.
func (t *traceContext) AddTag(keysAndValues ...interface{}) Context {
t.tags = append(t.tags, keysAndValues...)
return t
}
// NewTraceContext new a TraceContext
func NewTraceContext(ctx stdctx.Context, id string) Context {
if id == "" {
id = "i-" + utils.RandomString(8)
}
return &traceContext{
Context: ctx,
id: id,
beginTimestamp: time.Now(),
}
}
func copySlice(in []interface{}) []interface{} {
out := make([]interface{}, len(in))
copy(out, in)
return out
}
// Exporter export context info.
type Exporter func(t *traceContext, duration float64)
// DurationMetric export context duration metric.
func DurationMetric(h func(v float64)) Exporter {
return func(t *traceContext, duration float64) {
h(duration)
}
}

View File

@@ -1,45 +0,0 @@
/*
Copyright 2021. The KubeVela 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 context
import (
"context"
"fmt"
"testing"
"time"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/types"
)
func TestLog(t *testing.T) {
ctx := NewTraceContext(context.Background(), types.NamespacedName{
Namespace: "default",
Name: "test-app",
}.String())
ctx.AddTag("controller", "application")
ctx.Info("init")
ctx.InfoDepth(1, "init")
defer ctx.Commit("close")
spanCtx := ctx.Fork("child1", DurationMetric(func(v float64) {
fmt.Println(v)
}))
time.Sleep(time.Millisecond * 30)
err := errors.New("mock error")
ctx.Error(err, "test case", "generated", "test_log")
ctx.ErrorDepth(1, err, "test case", "generated", "test_log")
spanCtx.Commit("finished")
}

View File

@@ -18,6 +18,8 @@ package metrics
import (
"github.com/prometheus/client_golang/prometheus"
velametrics "github.com/kubevela/pkg/monitor/metrics"
)
var (
@@ -25,7 +27,7 @@ var (
CreateAppHandlerDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "create_app_handler_time_seconds",
Help: "create appHandler duration distributions, this operate will list ResourceTrackers.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller"})
@@ -33,7 +35,7 @@ var (
HandleFinalizersDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "handle_finalizers_time_seconds",
Help: "handle finalizers duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller", "type"})
@@ -41,7 +43,7 @@ var (
ParseAppFileDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "parse_appFile_time_seconds",
Help: "parse appFile duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller"})
@@ -49,7 +51,7 @@ var (
PrepareCurrentAppRevisionDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "prepare_current_appRevision_time_seconds",
Help: "parse current appRevision duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller"})
@@ -57,7 +59,7 @@ var (
ApplyAppRevisionDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "apply_appRevision_time_seconds",
Help: "apply appRevision duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller"})
@@ -65,7 +67,7 @@ var (
ApplyPoliciesDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "apply_policies",
Help: "render and dispatch policy duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller"})
@@ -73,23 +75,15 @@ var (
GCResourceTrackersDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "gc_resourceTrackers_time_seconds",
Help: "gc resourceTrackers duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"stage"})
// ClientRequestHistogram report the client request execution duration.
ClientRequestHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "client_request_time_seconds",
Help: "client request duration distributions.",
Buckets: histogramBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"verb", "Kind", "apiVersion", "unstructured", "cluster"})
// ApplicationReconcileTimeHistogram report the reconciling time cost of application controller with state transition recorded
ApplicationReconcileTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "application_reconcile_time_seconds",
Help: "application reconcile duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"begin_phase", "end_phase"})
@@ -97,7 +91,7 @@ var (
ApplyComponentTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "apply_component_time_seconds",
Help: "apply component duration distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"stage"})
@@ -105,7 +99,7 @@ var (
WorkflowFinishedTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "workflow_finished_time_seconds",
Help: "workflow finished time distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"phase"})

View File

@@ -17,17 +17,16 @@ import (
"github.com/prometheus/client_golang/prometheus"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/metrics"
)
var histogramBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40, 50, 60}
velametrics "github.com/kubevela/pkg/monitor/metrics"
)
var (
// StepDurationHistogram report the step execution duration.
StepDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "step_duration_ms",
Help: "step latency distributions.",
Buckets: histogramBuckets,
Buckets: velametrics.FineGrainedBuckets,
ConstLabels: prometheus.Labels{},
}, []string{"controller", "step_type"})
)
@@ -42,7 +41,6 @@ var collectorGroup = []prometheus.Collector{
StepDurationHistogram,
GCResourceTrackersDurationHistogram,
ListResourceTrackerCounter,
ClientRequestHistogram,
ApplicationReconcileTimeHistogram,
ApplyComponentTimeHistogram,
WorkflowFinishedTimeHistogram,

View File

@@ -1,111 +0,0 @@
/*
Copyright 2021 The KubeVela 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 multicluster
import (
"net/http"
"strings"
clusterapi "github.com/oam-dev/cluster-gateway/pkg/apis/cluster/v1alpha1"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/client-go/transport"
"github.com/oam-dev/kubevela/pkg/utils"
)
var _ utilnet.RoundTripperWrapper = &secretMultiClusterRoundTripper{}
type secretMultiClusterRoundTripper struct {
rt http.RoundTripper
}
// NewSecretModeMultiClusterRoundTripper will re-write the API path to one of the multi-cluster resource for a request if context has the value
func NewSecretModeMultiClusterRoundTripper(rt http.RoundTripper) http.RoundTripper {
return &secretMultiClusterRoundTripper{
rt: rt,
}
}
// FormatProxyURL will format the request API path by the cluster gateway resources rule
func FormatProxyURL(clusterName, originalPath string) string {
originalPath = strings.TrimPrefix(originalPath, "/")
return strings.Join([]string{"/apis", clusterapi.SchemeGroupVersion.Group, clusterapi.SchemeGroupVersion.Version, "clustergateways", clusterName, "proxy", originalPath}, "/")
}
// RoundTrip is the main function for the re-write API path logic
func (rt *secretMultiClusterRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
clusterName, ok := ctx.Value(ClusterContextKey).(string)
if !ok || clusterName == "" || clusterName == ClusterLocalName {
return rt.rt.RoundTrip(req)
}
req = req.Clone(ctx)
req.URL.Path = FormatProxyURL(clusterName, req.URL.Path)
return rt.rt.RoundTrip(req)
}
// CancelRequest will try cancel request with the inner round tripper
func (rt *secretMultiClusterRoundTripper) CancelRequest(req *http.Request) {
utils.TryCancelRequest(rt.WrappedRoundTripper(), req)
}
// WrappedRoundTripper can get the wrapped RoundTripper
func (rt *secretMultiClusterRoundTripper) WrappedRoundTripper() http.RoundTripper {
return rt.rt
}
var _ utilnet.RoundTripperWrapper = &secretMultiClusterRoundTripperForCluster{}
type secretMultiClusterRoundTripperForCluster struct {
rt http.RoundTripper
clusterName string
}
// RoundTrip is the main function for the re-write API path logic
func (rt *secretMultiClusterRoundTripperForCluster) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
if rt.clusterName != "" && rt.clusterName != ClusterLocalName {
req = req.Clone(ctx)
req.URL.Path = FormatProxyURL(rt.clusterName, req.URL.Path)
}
return rt.rt.RoundTrip(req)
}
// CancelRequest will try cancel request with the inner round tripper
func (rt *secretMultiClusterRoundTripperForCluster) CancelRequest(req *http.Request) {
utils.TryCancelRequest(rt.WrappedRoundTripper(), req)
}
// WrappedRoundTripper can get the wrapped RoundTripper
func (rt *secretMultiClusterRoundTripperForCluster) WrappedRoundTripper() http.RoundTripper {
return rt.rt
}
// NewSecretModeMultiClusterRoundTripperForCluster will re-write the API path to the specific cluster
func NewSecretModeMultiClusterRoundTripperForCluster(rt http.RoundTripper, clusterName string) http.RoundTripper {
return &secretMultiClusterRoundTripperForCluster{
rt: rt,
clusterName: clusterName,
}
}
// NewClusterGatewayRoundTripperWrapperGenerator create RoundTripper WrapperFunc that redirect requests to target cluster
func NewClusterGatewayRoundTripperWrapperGenerator(clusterName string) transport.WrapperFunc {
return func(rt http.RoundTripper) http.RoundTripper {
return NewSecretModeMultiClusterRoundTripperForCluster(rt, clusterName)
}
}

View File

@@ -1,46 +0,0 @@
/*
Copyright 2021 The KubeVela 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 multicluster
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFormatProxyURL(t *testing.T) {
tests := []struct {
clusterName string
originalPath string
expectResult string
}{
{
clusterName: "myc",
originalPath: "/api/pods",
expectResult: "/apis/cluster.core.oam.dev/v1alpha1/clustergateways/myc/proxy/api/pods",
},
{
clusterName: "myc",
originalPath: "api/pods",
expectResult: "/apis/cluster.core.oam.dev/v1alpha1/clustergateways/myc/proxy/api/pods",
},
}
for _, cc := range tests {
gotResult := FormatProxyURL(cc.clusterName, cc.originalPath)
assert.Equal(t, cc.expectResult, gotResult)
}
}

View File

@@ -23,7 +23,6 @@ import (
"fmt"
"time"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
errors2 "github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
@@ -35,22 +34,19 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
"github.com/oam-dev/cluster-gateway/pkg/apis/cluster/v1alpha1"
clustercommon "github.com/oam-dev/cluster-gateway/pkg/common"
velatypes "github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils/common"
errors3 "github.com/oam-dev/kubevela/pkg/utils/errors"
)
type contextKey string
const (
// ClusterContextKey is the name of cluster using in client http context
ClusterContextKey = contextKey("ClusterName")
// ClusterLocalName specifies the local cluster
ClusterLocalName = velatypes.ClusterLocalName
ClusterLocalName = pkgmulticluster.Local
)
var (
@@ -60,27 +56,18 @@ var (
// ClusterNameInContext extract cluster name from context
func ClusterNameInContext(ctx context.Context) string {
clusterName := ctx.Value(ClusterContextKey)
if clusterName != nil {
return clusterName.(string)
}
return ""
cluster, _ := pkgmulticluster.ClusterFrom(ctx)
return cluster
}
// ContextWithClusterName create context with multi-cluster by cluster name
func ContextWithClusterName(ctx context.Context, clusterName string) context.Context {
return context.WithValue(ctx, ClusterContextKey, clusterName)
}
// IsInLocalCluster check if target cluster is local cluster
func IsInLocalCluster(ctx context.Context) bool {
clusterName := ClusterNameInContext(ctx)
return clusterName == "" || clusterName == ClusterLocalName
return pkgmulticluster.WithCluster(ctx, clusterName)
}
// ContextInLocalCluster create context in local cluster
func ContextInLocalCluster(ctx context.Context) context.Context {
return context.WithValue(ctx, ClusterContextKey, ClusterLocalName)
return pkgmulticluster.WithCluster(ctx, ClusterLocalName)
}
// ResourcesWithClusterName set cluster name for resources
@@ -154,7 +141,6 @@ func Initialize(restConfig *rest.Config, autoUpgrade bool) (client.Client, error
ClusterGatewaySecretNamespace = svc.Namespace
prismclusterv1alpha1.StorageNamespace = ClusterGatewaySecretNamespace
klog.Infof("find cluster gateway service %s/%s:%d", svc.Namespace, svc.Name, *svc.Port)
restConfig.Wrap(NewSecretModeMultiClusterRoundTripper)
if autoUpgrade {
if err = UpgradeExistingClusterSecret(context.Background(), c); err != nil {
// this error do not affect the running of current version

View File

@@ -37,6 +37,8 @@ import (
featuregatetesting "k8s.io/component-base/featuregate/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubevela/pkg/util/rand"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
@@ -44,7 +46,6 @@ import (
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/resourcetracker"
"github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/apply"
"github.com/oam-dev/kubevela/version"
)
@@ -54,7 +55,7 @@ var _ = Describe("Test ResourceKeeper garbage collection", func() {
var namespace string
BeforeEach(func() {
namespace = "test-ns-" + utils.RandomString(4)
namespace = "test-ns-" + rand.RandomString(4)
Expect(testClient.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}})).Should(Succeed())
})

View File

@@ -1,34 +0,0 @@
/*
Copyright 2021 The KubeVela 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 utils
import (
"math/rand"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyz123456789")
// RandomString generate random string.
func RandomString(n int) string {
randSrc := rand.NewSource(time.Now().UnixNano())
b := make([]rune, n)
for i := range b {
b[i] = letters[randSrc.Int63()%int64(len(letters))]
}
return string(b)
}

View File

@@ -1,35 +0,0 @@
/*
Copyright 2021 The KubeVela 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 utils
import (
"testing"
)
func TestRandom(t *testing.T) {
s1 := RandomString(10)
s2 := RandomString(10)
if s1 == s2 {
t.Error("random generate same string")
}
if len(s1) != 10 {
t.Error("s1 length != 10")
}
if len(s2) != 10 {
t.Error("s2 length != 10")
}
}

View File

@@ -24,14 +24,16 @@ import (
"github.com/crossplane/crossplane-runtime/pkg/meta"
"github.com/fatih/color"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
"github.com/oam-dev/cluster-gateway/pkg/config"
"github.com/oam-dev/cluster-gateway/pkg/generated/clientset/versioned"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
prismclusterv1alpha1 "github.com/kubevela/prism/pkg/apis/cluster/v1alpha1"
"github.com/oam-dev/cluster-gateway/pkg/config"
"github.com/oam-dev/cluster-gateway/pkg/generated/clientset/versioned"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/utils/common"
@@ -69,7 +71,7 @@ func ClusterCommandGroup(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Comm
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
k8sClient, err := c.GetClient()
if err != nil {
return errors.Wrapf(err, "failed to get k8s client")

View File

@@ -28,6 +28,8 @@ import (
cmdexec "k8s.io/kubectl/pkg/cmd/exec"
k8scmdutil "k8s.io/kubectl/pkg/cmd/util"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
@@ -193,7 +195,7 @@ func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []s
var namespace = selectPod.Metadata.Namespace
cf.Namespace = &namespace
cf.WrapConfigFn = func(cfg *rest.Config) *rest.Config {
cfg.Wrap(multicluster.NewClusterGatewayRoundTripperWrapperGenerator(selectPod.Cluster))
cfg.Wrap(pkgmulticluster.NewTransportWrapper(pkgmulticluster.ForCluster(selectPod.Cluster)))
return cfg
}
o.f = k8scmdutil.NewFactory(k8scmdutil.NewMatchVersionFlags(cf))
@@ -204,7 +206,7 @@ func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []s
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
k8sClient, err := kubernetes.NewForConfig(config)
if err != nil {
return err

View File

@@ -36,6 +36,8 @@ import (
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
@@ -232,7 +234,7 @@ func (o *VelaPortForwardOptions) Init(ctx context.Context, cmd *cobra.Command, a
cf := genericclioptions.NewConfigFlags(true)
cf.Namespace = pointer.String(o.targetResource.namespace)
cf.WrapConfigFn = func(cfg *rest.Config) *rest.Config {
cfg.Wrap(multicluster.NewClusterGatewayRoundTripperWrapperGenerator(o.targetResource.cluster))
cfg.Wrap(pkgmulticluster.NewTransportWrapper(pkgmulticluster.ForCluster(o.targetResource.cluster)))
return cfg
}
o.f = k8scmdutil.NewFactory(k8scmdutil.NewMatchVersionFlags(cf))
@@ -241,7 +243,7 @@ func (o *VelaPortForwardOptions) Init(ctx context.Context, cmd *cobra.Command, a
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
forwardClient, err := client.New(config, client.Options{Scheme: common.Scheme})
if err != nil {
return err

View File

@@ -33,6 +33,7 @@ import (
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
commontypes "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
@@ -436,7 +437,7 @@ func printApplicationTree(c common.Args, cmd *cobra.Command, appName string, app
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
cli, err := c.GetClient()
if err != nil {
return err

View File

@@ -26,10 +26,10 @@ import (
"github.com/spf13/cobra"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
"github.com/kubevela/workflow/pkg/cue/model/value"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/common"
"github.com/oam-dev/kubevela/pkg/utils/util"
@@ -372,7 +372,7 @@ func QueryValue(ctx context.Context, velaC common.Args, queryView *velaql.QueryV
if err != nil {
return nil, err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
client, err := velaC.GetClient()
if err != nil {
return nil, err

View File

@@ -23,9 +23,10 @@ import (
"github.com/spf13/cobra"
k8stypes "k8s.io/apimachinery/pkg/types"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils/common"
cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
@@ -77,7 +78,7 @@ func NewWorkflowSuspendCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
cli, err := c.GetClient()
if err != nil {
return err
@@ -115,7 +116,7 @@ func NewWorkflowResumeCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
cli, err := c.GetClient()
if err != nil {
return err
@@ -186,7 +187,7 @@ func NewWorkflowRestartCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
cli, err := c.GetClient()
if err != nil {
return err
@@ -223,7 +224,7 @@ func NewWorkflowRollbackCommand(c common.Args, ioStream cmdutil.IOStreams) *cobr
if err != nil {
return err
}
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(pkgmulticluster.NewTransportWrapper())
cli, err := c.GetClient()
if err != nil {
return err

View File

@@ -25,9 +25,10 @@ import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/kubevela/pkg/util/rand"
v1 "github.com/oam-dev/kubevela/pkg/apiserver/interfaces/api/dto/v1"
"github.com/oam-dev/kubevela/pkg/multicluster"
util "github.com/oam-dev/kubevela/pkg/utils"
)
const (
@@ -42,7 +43,7 @@ var _ = Describe("Test cluster rest api", func() {
var clusterName string
BeforeEach(func() {
clusterName = WorkerClusterName + "-" + util.RandomString(8)
clusterName = WorkerClusterName + "-" + rand.RandomString(8)
kubeconfigBytes, err := ioutil.ReadFile(WorkerClusterKubeConfigPath)
Expect(err).Should(Succeed())
resp := post("/clusters", v1.CreateClusterRequest{
@@ -112,7 +113,7 @@ var _ = Describe("Test cluster rest api", func() {
var clusterName string
BeforeEach(func() {
clusterName = WorkerClusterName + "-" + util.RandomString(8)
clusterName = WorkerClusterName + "-" + rand.RandomString(8)
})
AfterEach(func() {

View File

@@ -39,12 +39,13 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/kubevela/pkg/util/rand"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils"
)
func initializeContext() (hubCtx context.Context, workerCtx context.Context) {
@@ -56,7 +57,7 @@ func initializeContext() (hubCtx context.Context, workerCtx context.Context) {
func initializeContextAndNamespace() (hubCtx context.Context, workerCtx context.Context, namespace string) {
hubCtx, workerCtx = initializeContext()
// initialize test namespace
namespace = "test-mc-" + utils.RandomString(4)
namespace = "test-mc-" + rand.RandomString(4)
ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}
Expect(k8sClient.Create(hubCtx, ns.DeepCopy())).Should(Succeed())
Expect(k8sClient.Create(workerCtx, ns.DeepCopy())).Should(Succeed())

View File

@@ -29,9 +29,10 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"github.com/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
oamutil "github.com/oam-dev/kubevela/pkg/oam/util"
"github.com/oam-dev/kubevela/pkg/utils/common"
"github.com/oam-dev/kubevela/pkg/utils/util"
@@ -69,7 +70,7 @@ var _ = BeforeSuite(func() {
// initialize clients
options := client.Options{Scheme: common.Scheme}
config := config.GetConfigOrDie()
config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)
config.Wrap(multicluster.NewTransportWrapper())
k8sClient, err = client.New(config, options)
Expect(err).Should(Succeed())
k8sCli, err = kubernetes.NewForConfig(config)

View File

@@ -32,10 +32,11 @@ import (
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubevela/pkg/util/rand"
common2 "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/condition"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/common"
)
@@ -43,7 +44,7 @@ var _ = Describe("Application Resource-Related Policy Tests", func() {
ctx := context.Background()
var namespace string
BeforeEach(func() {
namespace = "test-resource-policy-" + utils.RandomString(4)
namespace = "test-resource-policy-" + rand.RandomString(4)
Expect(k8sClient.Create(ctx, &v1.Namespace{ObjectMeta: v12.ObjectMeta{Name: namespace}})).Should(Succeed())
})