Add golangci-lint workflow (#4999)
* fix lint workflow * add golang lint * close http response body
This commit is contained in:
13
.golangci.yaml
Normal file
13
.golangci.yaml
Normal file
@@ -0,0 +1,13 @@
|
||||
linters:
|
||||
# Disable all linters.
|
||||
# Default: false
|
||||
disable-all: true
|
||||
# Enable specific linter
|
||||
# https://golangci-lint.run/usage/linters/#enabled-by-default-linters
|
||||
enable:
|
||||
- deadcode
|
||||
- unused
|
||||
- varcheck
|
||||
- ineffassign
|
||||
- staticcheck
|
||||
- gosimple
|
||||
3
Makefile
3
Makefile
@@ -159,3 +159,6 @@ clientset: ;$(info $(M)...Begin to find or download controller-gen.) @ ## Find
|
||||
# Fix invalid file's license.
|
||||
update-licenses: ;$(info $(M)...Begin to update licenses.)
|
||||
@hack/update-licenses.sh
|
||||
|
||||
golint:
|
||||
@hack/verify-golangci-lint.sh
|
||||
|
||||
@@ -27,7 +27,6 @@ EXCLUDED_PATTERNS=(
|
||||
"verify-linkcheck.sh" # runs in separate Jenkins job once per day due to high network usage
|
||||
"verify-*-dockerized.sh" # Don't run any scripts that intended to be run dockerized
|
||||
"verify-govet-levee.sh" # Do not run levee analysis by default while KEP-1933 implementation is in alpha.
|
||||
"verify-golangci-lint.sh" # Experimental - intended to be run by hand periodically
|
||||
"verify-licenses.sh"
|
||||
)
|
||||
|
||||
|
||||
24
hack/verify-golangci-lint.sh
Normal file → Executable file
24
hack/verify-golangci-lint.sh
Normal file → Executable file
@@ -35,14 +35,24 @@ PATH="${GOBIN}:${PATH}"
|
||||
# Explicitly opt into go modules, even though we're inside a GOPATH directory
|
||||
export GO111MODULE=on
|
||||
|
||||
if ! command -v golangci-lint ; then
|
||||
# Install golangci-lint
|
||||
echo 'installing golangci-lint '
|
||||
pushd "${KUBE_ROOT}/hack/tools" >/dev/null
|
||||
go install github.com/golangci/golangci-lint/cmd/golangci-lint
|
||||
popd >/dev/null
|
||||
echo 'installing golangci-lint '
|
||||
pushd "${KUBE_ROOT}/hack/tools" >/dev/null
|
||||
GO111MODULE=auto go install -mod= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.44.2
|
||||
popd >/dev/null
|
||||
fi
|
||||
|
||||
cd "${KUBE_ROOT}"
|
||||
|
||||
function error_exit {
|
||||
if [ $? -eq 1 ]; then
|
||||
echo "Please run the following command:"
|
||||
echo " make golint"
|
||||
fi
|
||||
}
|
||||
trap "error_exit" EXIT
|
||||
|
||||
echo 'running golangci-lint '
|
||||
golangci-lint run \
|
||||
--timeout 30m \
|
||||
@@ -50,4 +60,8 @@ golangci-lint run \
|
||||
-E deadcode \
|
||||
-E unused \
|
||||
-E varcheck \
|
||||
-E ineffassign
|
||||
-E ineffassign \
|
||||
-E staticcheck \
|
||||
-E gosimple \
|
||||
-E bodyclose \
|
||||
pkg/... cmd/... tools/... test/... kube/...
|
||||
|
||||
@@ -179,7 +179,7 @@ func (p *pvcEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageS
|
||||
var _ quota.Evaluator = &pvcEvaluator{}
|
||||
|
||||
func toExternalPersistentVolumeClaimOrError(obj runtime.Object) (*corev1.PersistentVolumeClaim, error) {
|
||||
pvc := &corev1.PersistentVolumeClaim{}
|
||||
var pvc *corev1.PersistentVolumeClaim
|
||||
switch t := obj.(type) {
|
||||
case *corev1.PersistentVolumeClaim:
|
||||
pvc = t
|
||||
|
||||
@@ -144,10 +144,7 @@ func (p *podEvaluator) GroupResource() schema.GroupResource {
|
||||
// Handles returns true if the evaluator should handle the specified attributes.
|
||||
func (p *podEvaluator) Handles(a admission.Attributes) bool {
|
||||
op := a.GetOperation()
|
||||
if op == admission.Create {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return op == admission.Create
|
||||
}
|
||||
|
||||
// Matches returns true if the evaluator matches the specified quota with the provided input item
|
||||
@@ -276,7 +273,7 @@ func podComputeUsageHelper(requests corev1.ResourceList, limits corev1.ResourceL
|
||||
}
|
||||
|
||||
func toExternalPodOrError(obj runtime.Object) (*corev1.Pod, error) {
|
||||
pod := &corev1.Pod{}
|
||||
var pod *corev1.Pod
|
||||
switch t := obj.(type) {
|
||||
case *corev1.Pod:
|
||||
pod = t
|
||||
|
||||
@@ -94,7 +94,7 @@ func (p *serviceEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedRes
|
||||
|
||||
// convert the input object to an internal service object or error.
|
||||
func toExternalServiceOrError(obj runtime.Object) (*corev1.Service, error) {
|
||||
svc := &corev1.Service{}
|
||||
var svc *corev1.Service
|
||||
switch t := obj.(type) {
|
||||
case *corev1.Service:
|
||||
svc = t
|
||||
|
||||
@@ -381,9 +381,7 @@ func getMatchedLimitedScopes(evaluator quota.Evaluator, inputObject runtime.Obje
|
||||
klog.Errorf("Error while matching limited Scopes: %v", err)
|
||||
return []corev1.ScopedResourceSelectorRequirement{}, err
|
||||
}
|
||||
for _, scope := range matched {
|
||||
scopes = append(scopes, scope)
|
||||
}
|
||||
scopes = append(scopes, matched...)
|
||||
}
|
||||
return scopes, nil
|
||||
}
|
||||
@@ -443,9 +441,7 @@ func CheckRequest(quotas []corev1.ResourceQuota, a admission.Attributes, evaluat
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error matching scopes of quota %s, err: %v", resourceQuota.Name, err)
|
||||
}
|
||||
for _, scope := range localRestrictedScopes {
|
||||
restrictedScopes = append(restrictedScopes, scope)
|
||||
}
|
||||
restrictedScopes = append(restrictedScopes, localRestrictedScopes...)
|
||||
|
||||
match, err := evaluator.Matches(&resourceQuota, inputObject)
|
||||
if err != nil {
|
||||
@@ -578,9 +574,7 @@ func getScopeSelectorsFromQuota(quota corev1.ResourceQuota) []corev1.ScopedResou
|
||||
Operator: corev1.ScopeSelectorOpExists})
|
||||
}
|
||||
if quota.Spec.ScopeSelector != nil {
|
||||
for _, scopeSelector := range quota.Spec.ScopeSelector.MatchExpressions {
|
||||
selectors = append(selectors, scopeSelector)
|
||||
}
|
||||
selectors = append(selectors, quota.Spec.ScopeSelector.MatchExpressions...)
|
||||
}
|
||||
return selectors
|
||||
}
|
||||
|
||||
@@ -394,7 +394,6 @@ func ParseAlertingRuleQueryParams(req *restful.Request) (*AlertingRuleQueryParam
|
||||
q.PageNum, err = strconv.Atoi(req.QueryParameter("page"))
|
||||
if err != nil {
|
||||
q.PageNum = 1
|
||||
err = nil
|
||||
}
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
@@ -420,7 +419,6 @@ func ParseAlertQueryParams(req *restful.Request) (*AlertQueryParams, error) {
|
||||
q.PageNum, err = strconv.Atoi(req.QueryParameter("page"))
|
||||
if err != nil {
|
||||
q.PageNum = 1
|
||||
err = nil
|
||||
}
|
||||
if q.PageNum <= 0 {
|
||||
q.PageNum = 1
|
||||
|
||||
@@ -199,7 +199,7 @@ func monitorRequest(r *restful.Request, response *restful.Response, chain *restf
|
||||
reqInfo, exists := request.RequestInfoFrom(r.Request.Context())
|
||||
if exists && reqInfo.APIGroup != "" {
|
||||
RequestCounter.WithLabelValues(reqInfo.Verb, reqInfo.APIGroup, reqInfo.APIVersion, reqInfo.Resource, strconv.Itoa(response.StatusCode())).Inc()
|
||||
elapsedSeconds := time.Now().Sub(start).Seconds()
|
||||
elapsedSeconds := time.Since(start).Seconds()
|
||||
RequestLatencies.WithLabelValues(reqInfo.Verb, reqInfo.APIGroup, reqInfo.APIVersion, reqInfo.Resource).Observe(elapsedSeconds)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func (b *Backend) sendEvents(events *v1alpha1.EventList) {
|
||||
start := time.Now()
|
||||
defer func() {
|
||||
stopCh <- struct{}{}
|
||||
klog.V(8).Infof("send %d auditing logs used %d", len(events.Items), time.Now().Sub(start).Milliseconds())
|
||||
klog.V(8).Infof("send %d auditing logs used %d", len(events.Items), time.Since(start).Milliseconds())
|
||||
}()
|
||||
|
||||
bs, err := b.eventToBytes(events)
|
||||
@@ -172,6 +172,7 @@ func (b *Backend) sendEvents(events *v1alpha1.EventList) {
|
||||
klog.Errorf("send audit events error, %s", err)
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
klog.Errorf("send audit events error[%d]", response.StatusCode)
|
||||
|
||||
@@ -92,10 +92,7 @@ func (a *auditing) getAuditLevel() audit.Level {
|
||||
func (a *auditing) Enabled() bool {
|
||||
|
||||
level := a.getAuditLevel()
|
||||
if level.Less(audit.LevelMetadata) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return !level.Less(audit.LevelMetadata)
|
||||
}
|
||||
|
||||
func (a *auditing) K8sAuditingEnabled() bool {
|
||||
@@ -294,5 +291,6 @@ func (c *ResponseCapture) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
|
||||
// CloseNotify is part of http.CloseNotifier interface
|
||||
func (c *ResponseCapture) CloseNotify() <-chan bool {
|
||||
//nolint:staticcheck
|
||||
return c.ResponseWriter.(http.CloseNotifier).CloseNotify()
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/authentication/v1"
|
||||
@@ -41,8 +40,6 @@ import (
|
||||
"kubesphere.io/kubesphere/pkg/utils/iputil"
|
||||
)
|
||||
|
||||
var noResyncPeriodFunc = func() time.Duration { return 0 }
|
||||
|
||||
func TestGetAuditLevel(t *testing.T) {
|
||||
webhook := &auditingv1alpha1.Webhook{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
|
||||
@@ -120,9 +120,9 @@ func desensitize(data map[string]interface{}) map[string]interface{} {
|
||||
if isSensitiveData(k) {
|
||||
continue
|
||||
}
|
||||
switch v.(type) {
|
||||
switch v := v.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
output[k] = desensitize(convert(v.(map[interface{}]interface{})))
|
||||
output[k] = desensitize(convert(v))
|
||||
default:
|
||||
output[k] = v
|
||||
}
|
||||
@@ -134,9 +134,9 @@ func desensitize(data map[string]interface{}) map[string]interface{} {
|
||||
func convert(m map[interface{}]interface{}) map[string]interface{} {
|
||||
output := make(map[string]interface{})
|
||||
for k, v := range m {
|
||||
switch k.(type) {
|
||||
switch k := k.(type) {
|
||||
case string:
|
||||
output[k.(string)] = v
|
||||
output[k] = v
|
||||
}
|
||||
}
|
||||
return output
|
||||
|
||||
@@ -189,7 +189,7 @@ func (s *issuer) Verify(token string) (*VerifiedResponse, error) {
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
if claims.VerifyExpiresAt(now, false) == false {
|
||||
if !claims.VerifyExpiresAt(now, false) {
|
||||
delta := time.Unix(now, 0).Sub(time.Unix(claims.ExpiresAt, 0))
|
||||
err = fmt.Errorf("jwt: token is expired by %v", delta)
|
||||
klog.V(4).Info(err)
|
||||
@@ -198,7 +198,7 @@ func (s *issuer) Verify(token string) (*VerifiedResponse, error) {
|
||||
|
||||
// allowing a clock skew when checking the time-based values.
|
||||
skewedTime := now + int64(s.maximumClockSkew.Seconds())
|
||||
if claims.VerifyIssuedAt(skewedTime, false) == false {
|
||||
if !claims.VerifyIssuedAt(skewedTime, false) {
|
||||
err = fmt.Errorf("jwt: token used before issued, iat:%v, now:%v", claims.IssuedAt, now)
|
||||
klog.Warning(err)
|
||||
return nil, err
|
||||
|
||||
@@ -303,8 +303,10 @@ func Test_issuer_Verify(t *testing.T) {
|
||||
|
||||
func Test_issuer_keyFunc(t *testing.T) {
|
||||
type fields struct {
|
||||
name string
|
||||
secret []byte
|
||||
//nolint:unused
|
||||
name string
|
||||
secret []byte
|
||||
//nolint:unused
|
||||
maximumClockSkew time.Duration
|
||||
}
|
||||
type args struct {
|
||||
@@ -342,7 +344,7 @@ func Test_issuer_keyFunc(t *testing.T) {
|
||||
return
|
||||
}
|
||||
iss := s.(*issuer)
|
||||
got, err := iss.keyFunc(tt.args.token)
|
||||
got, _ := iss.keyFunc(tt.args.token)
|
||||
assert.NotNil(t, got)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func (authzHandler unionAuthzRulesHandler) RulesFor(user user.Info, namespace st
|
||||
for _, currAuthzHandler := range authzHandler {
|
||||
resourceRules, nonResourceRules, incomplete, err := currAuthzHandler.RulesFor(user, namespace)
|
||||
|
||||
if incomplete == true {
|
||||
if incomplete {
|
||||
incompleteStatus = true
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -56,7 +56,7 @@ func (c *clusterDispatch) Dispatch(w http.ResponseWriter, req *http.Request, han
|
||||
|
||||
if len(info.Cluster) == 0 {
|
||||
klog.Warningf("Request with empty cluster, %v", req.URL)
|
||||
http.Error(w, fmt.Sprintf("Bad request, empty cluster"), http.StatusBadRequest)
|
||||
http.Error(w, "Bad request, empty cluster", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -38,9 +38,6 @@ const (
|
||||
|
||||
// auditKey is the context key for the audit event.
|
||||
auditKey
|
||||
|
||||
// audiencesKey is the context key for request audiences.
|
||||
audiencesKey
|
||||
)
|
||||
|
||||
// NewContext instantiates a base context object for request flows.
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestNamespaceContext(t *testing.T) {
|
||||
}
|
||||
|
||||
ctx = NewContext()
|
||||
result, ok = NamespaceFrom(ctx)
|
||||
_, ok = NamespaceFrom(ctx)
|
||||
if ok {
|
||||
t.Fatalf("Should not be ok because there is no namespace on the context")
|
||||
}
|
||||
|
||||
@@ -66,6 +66,5 @@ func (cb *ContainerBuilder) Register(funcs ...func(*restful.Container) error) {
|
||||
func NewContainerBuilder(funcs ...func(*restful.Container) error) ContainerBuilder {
|
||||
var cb ContainerBuilder
|
||||
cb.Register(funcs...)
|
||||
|
||||
return cb
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ func (c *Controller) Approve(csr *certificatesv1.CertificateSigningRequest) erro
|
||||
}
|
||||
|
||||
// approve csr
|
||||
csr, err := c.k8sclient.CertificatesV1().CertificateSigningRequests().UpdateApproval(context.Background(), csr.Name, csr, metav1.UpdateOptions{})
|
||||
_, err := c.k8sclient.CertificatesV1().CertificateSigningRequests().UpdateApproval(context.Background(), csr.Name, csr, metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
klog.Errorln(err)
|
||||
return err
|
||||
|
||||
@@ -79,25 +79,16 @@ const (
|
||||
maxRetries = 15
|
||||
|
||||
kubefedNamespace = "kube-federation-system"
|
||||
openpitrixRuntime = "openpitrix.io/runtime"
|
||||
kubesphereManaged = "kubesphere.io/managed"
|
||||
|
||||
// Actually host cluster name can be anything, there is only necessary when calling JoinFederation function
|
||||
hostClusterName = "kubesphere"
|
||||
|
||||
// allocate kubernetesAPIServer port in range [portRangeMin, portRangeMax] for agents if port is not specified
|
||||
// kubesphereAPIServer port is defaulted to kubernetesAPIServerPort + 10000
|
||||
portRangeMin = 6000
|
||||
portRangeMax = 7000
|
||||
|
||||
// proxy format
|
||||
proxyFormat = "%s/api/v1/namespaces/kubesphere-system/services/:ks-apiserver:80/proxy/%s"
|
||||
|
||||
// mulitcluster configuration name
|
||||
configzMultiCluster = "multicluster"
|
||||
|
||||
// probe cluster timeout
|
||||
probeClusterTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
// Cluster template for reconcile host cluster if there is none.
|
||||
@@ -372,7 +363,7 @@ func (c *clusterController) syncCluster(key string) error {
|
||||
|
||||
// currently we didn't set cluster.Spec.Enable when creating cluster at client side, so only check
|
||||
// if we enable cluster.Spec.JoinFederation now
|
||||
if cluster.Spec.JoinFederation == false {
|
||||
if !cluster.Spec.JoinFederation {
|
||||
klog.V(5).Infof("Skipping to join cluster %s cause it is not expected to join", cluster.Name)
|
||||
return nil
|
||||
}
|
||||
@@ -590,6 +581,8 @@ func (c *clusterController) tryToFetchKubeSphereComponents(host string, transpor
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
klog.V(4).Infof("Response status code isn't 200.")
|
||||
return nil, fmt.Errorf("response code %d", response.StatusCode)
|
||||
@@ -616,6 +609,8 @@ func (c *clusterController) tryFetchKubeSphereVersion(host string, transport htt
|
||||
return "", err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
klog.V(4).Infof("Response status code isn't 200.")
|
||||
return "", fmt.Errorf("response code %d", response.StatusCode)
|
||||
@@ -671,16 +666,6 @@ func (c *clusterController) handleErr(err error, key interface{}) {
|
||||
utilruntime.HandleError(err)
|
||||
}
|
||||
|
||||
// isConditionTrue checks cluster specific condition value is True, return false if condition not exists
|
||||
func isConditionTrue(cluster *clusterv1alpha1.Cluster, conditionType clusterv1alpha1.ClusterConditionType) bool {
|
||||
for _, condition := range cluster.Status.Conditions {
|
||||
if condition.Type == conditionType && condition.Status == v1.ConditionTrue {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// updateClusterCondition updates condition in cluster conditions using giving condition
|
||||
// adds condition if not existed
|
||||
func (c *clusterController) updateClusterCondition(cluster *clusterv1alpha1.Cluster, condition clusterv1alpha1.ClusterCondition) {
|
||||
|
||||
@@ -403,8 +403,6 @@ func (v *DestinationRuleController) addDeployment(obj interface{}) {
|
||||
for key := range services {
|
||||
v.queue.Add(key)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (v *DestinationRuleController) deleteDeployment(obj interface{}) {
|
||||
|
||||
@@ -76,7 +76,8 @@ type Controller struct {
|
||||
// Kubernetes API.
|
||||
recorder record.EventRecorder
|
||||
multiClusterEnabled bool
|
||||
devopsClient devops.Interface
|
||||
//nolint:unused
|
||||
devopsClient devops.Interface
|
||||
}
|
||||
|
||||
func NewController(k8sClient kubernetes.Interface, ksClient kubesphere.Interface,
|
||||
|
||||
@@ -27,7 +27,6 @@ import (
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/kubernetes/scheme"
|
||||
@@ -62,7 +61,6 @@ const (
|
||||
|
||||
type Controller struct {
|
||||
controller.BaseController
|
||||
scheme *runtime.Scheme
|
||||
k8sClient kubernetes.Interface
|
||||
ksClient kubesphere.Interface
|
||||
groupInformer iamv1alpha2informers.GroupInformer
|
||||
@@ -220,7 +218,7 @@ func (c *Controller) reconcile(key string) error {
|
||||
return item == finalizer
|
||||
})
|
||||
|
||||
if group, err = c.ksClient.IamV1alpha2().Groups().Update(context.Background(), group, metav1.UpdateOptions{}); err != nil {
|
||||
if _, err = c.ksClient.IamV1alpha2().Groups().Update(context.Background(), group, metav1.UpdateOptions{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,6 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
alwaysReady = func() bool { return true }
|
||||
noResyncPeriodFunc = func() time.Duration { return 0 }
|
||||
)
|
||||
|
||||
@@ -152,6 +151,7 @@ func (f *fixture) run(userName string) {
|
||||
f.runController(userName, true, false)
|
||||
}
|
||||
|
||||
//nolint:unused
|
||||
func (f *fixture) runExpectError(userName string) {
|
||||
f.runController(userName, true, true)
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/kubernetes/scheme"
|
||||
@@ -59,7 +58,6 @@ const (
|
||||
|
||||
type Controller struct {
|
||||
controller.BaseController
|
||||
scheme *runtime.Scheme
|
||||
k8sClient kubernetes.Interface
|
||||
ksClient kubesphere.Interface
|
||||
groupBindingLister iamv1alpha2listers.GroupBindingLister
|
||||
@@ -137,7 +135,7 @@ func (c *Controller) reconcile(key string) error {
|
||||
}
|
||||
}
|
||||
if g != nil {
|
||||
if groupBinding, err = c.ksClient.IamV1alpha2().GroupBindings().Update(context.Background(), g, metav1.UpdateOptions{}); err != nil {
|
||||
if _, err = c.ksClient.IamV1alpha2().GroupBindings().Update(context.Background(), g, metav1.UpdateOptions{}); err != nil {
|
||||
return err
|
||||
}
|
||||
// Skip reconcile when group is updated.
|
||||
@@ -156,7 +154,7 @@ func (c *Controller) reconcile(key string) error {
|
||||
return item == finalizer
|
||||
})
|
||||
|
||||
if groupBinding, err = c.ksClient.IamV1alpha2().GroupBindings().Update(context.Background(), groupBinding, metav1.UpdateOptions{}); err != nil {
|
||||
if _, err = c.ksClient.IamV1alpha2().GroupBindings().Update(context.Background(), groupBinding, metav1.UpdateOptions{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,8 @@ type fixture struct {
|
||||
ksclient *fake.Clientset
|
||||
k8sclient *k8sfake.Clientset
|
||||
// Objects to put in the store.
|
||||
groupBindingLister []*v1alpha2.GroupBinding
|
||||
groupBindingLister []*v1alpha2.GroupBinding
|
||||
//nolint:unused
|
||||
fedgroupBindingLister []*fedv1beta1types.FederatedGroupBinding
|
||||
userLister []*v1alpha2.User
|
||||
// Actions expected to happen on the client.
|
||||
@@ -163,6 +164,7 @@ func (f *fixture) run(userName string) {
|
||||
f.runController(userName, true, false)
|
||||
}
|
||||
|
||||
//nolint:unused
|
||||
func (f *fixture) runExpectError(userName string) {
|
||||
f.runController(userName, true, true)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/klog/klogr"
|
||||
ctrl "sigs.k8s.io/controller-runtime"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
logf "sigs.k8s.io/controller-runtime/pkg/log"
|
||||
|
||||
"kubesphere.io/kubesphere/pkg/simple/client/gateway"
|
||||
@@ -40,7 +39,6 @@ import (
|
||||
|
||||
var cfg *rest.Config
|
||||
var testEnv *envtest.Environment
|
||||
var k8sClient client.Client
|
||||
|
||||
func TestApplicationController(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
|
||||
@@ -37,7 +37,6 @@ import (
|
||||
|
||||
clientset "k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"k8s.io/client-go/util/workqueue"
|
||||
)
|
||||
|
||||
@@ -52,9 +51,7 @@ const (
|
||||
)
|
||||
|
||||
type JobController struct {
|
||||
client clientset.Interface
|
||||
eventBroadcaster record.EventBroadcaster
|
||||
eventRecorder record.EventRecorder
|
||||
client clientset.Interface
|
||||
|
||||
jobLister batchv1listers.JobLister
|
||||
jobSynced cache.InformerSynced
|
||||
@@ -172,16 +169,6 @@ func (v *JobController) syncJob(key string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// When a job is added, figure out which service it will be used
|
||||
// and enqueue it. obj must have *batchv1.Job type
|
||||
func (v *JobController) addJob(obj interface{}) {
|
||||
deploy := obj.(*batchv1.Job)
|
||||
|
||||
v.queue.Add(deploy.Name)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (v *JobController) handleErr(err error, key interface{}) {
|
||||
if err == nil {
|
||||
v.queue.Forget(key)
|
||||
|
||||
@@ -38,11 +38,13 @@ var (
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
t *testing.T
|
||||
kubeclient *k8sfake.Clientset
|
||||
t *testing.T
|
||||
kubeclient *k8sfake.Clientset
|
||||
//nolint:unused
|
||||
jobController *JobController
|
||||
jobLister []*batchv1.Job
|
||||
|
||||
//nolint:unused
|
||||
kubeactions []core.Action
|
||||
actions []core.Action
|
||||
|
||||
|
||||
@@ -56,9 +56,7 @@ type loginRecordController struct {
|
||||
k8sClient kubernetes.Interface
|
||||
ksClient kubesphere.Interface
|
||||
loginRecordLister iamv1alpha2listers.LoginRecordLister
|
||||
loginRecordSynced cache.InformerSynced
|
||||
userLister iamv1alpha2listers.UserLister
|
||||
userSynced cache.InformerSynced
|
||||
loginHistoryRetentionPeriod time.Duration
|
||||
loginHistoryMaximumEntries int
|
||||
// recorder is an event recorder for recording Event resources to the
|
||||
|
||||
@@ -48,10 +48,6 @@ func TestIPPoolSuit(t *testing.T) {
|
||||
RunSpecs(t, "IPPool Suite")
|
||||
}
|
||||
|
||||
var (
|
||||
alwaysReady = func() bool { return true }
|
||||
)
|
||||
|
||||
var _ = Describe("test ippool", func() {
|
||||
pool := &v1alpha1.IPPool{
|
||||
TypeMeta: v1.TypeMeta{},
|
||||
@@ -138,11 +134,7 @@ var _ = Describe("test ippool", func() {
|
||||
|
||||
Eventually(func() bool {
|
||||
result, _ := ksclient.NetworkV1alpha1().IPPools().Get(context.TODO(), pool.Name, v1.GetOptions{})
|
||||
if result.Status.Allocations != 1 {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
return result.Status.Allocations == 1
|
||||
}, 3*time.Second).Should(Equal(true))
|
||||
})
|
||||
|
||||
@@ -153,11 +145,7 @@ var _ = Describe("test ippool", func() {
|
||||
ipamClient.ReleaseByHandle("testhandle")
|
||||
Eventually(func() bool {
|
||||
result, _ := ksclient.NetworkV1alpha1().IPPools().Get(context.TODO(), pool.Name, v1.GetOptions{})
|
||||
if result.Status.Allocations != 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
return result.Status.Allocations == 0
|
||||
}, 3*time.Second).Should(Equal(true))
|
||||
|
||||
err := ksclient.NetworkV1alpha1().IPPools().Delete(context.TODO(), pool.Name, v1.DeleteOptions{})
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
netv1 "k8s.io/api/networking/v1"
|
||||
"k8s.io/apimachinery/pkg/util/yaml"
|
||||
kubeinformers "k8s.io/client-go/informers"
|
||||
informerv1 "k8s.io/client-go/informers/core/v1"
|
||||
kubefake "k8s.io/client-go/kubernetes/fake"
|
||||
"k8s.io/klog"
|
||||
|
||||
@@ -37,21 +36,15 @@ import (
|
||||
|
||||
ksfake "kubesphere.io/kubesphere/pkg/client/clientset/versioned/fake"
|
||||
ksinformers "kubesphere.io/kubesphere/pkg/client/informers/externalversions"
|
||||
nsnppolicyinformer "kubesphere.io/kubesphere/pkg/client/informers/externalversions/network/v1alpha1"
|
||||
workspaceinformer "kubesphere.io/kubesphere/pkg/client/informers/externalversions/tenant/v1alpha1"
|
||||
"kubesphere.io/kubesphere/pkg/constants"
|
||||
"kubesphere.io/kubesphere/pkg/controller/network/nsnetworkpolicy/provider"
|
||||
options "kubesphere.io/kubesphere/pkg/simple/client/network"
|
||||
)
|
||||
|
||||
var (
|
||||
c *NSNetworkPolicyController
|
||||
stopCh chan struct{}
|
||||
nsnpInformer nsnppolicyinformer.NamespaceNetworkPolicyInformer
|
||||
serviceInformer informerv1.ServiceInformer
|
||||
workspaceInformer workspaceinformer.WorkspaceInformer
|
||||
namespaceInformer informerv1.NamespaceInformer
|
||||
alwaysReady = func() bool { return true }
|
||||
c *NSNetworkPolicyController
|
||||
stopCh chan struct{}
|
||||
alwaysReady = func() bool { return true }
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -89,6 +89,7 @@ func (c *k8sPolicyController) run(threadiness int, reconcilerPeriod string, stop
|
||||
// Wait until we are in sync with the Kubernetes API before starting the
|
||||
// resource cache.
|
||||
klog.Info("Waiting to sync with Kubernetes API (NetworkPolicy)")
|
||||
//nolint:staticcheck
|
||||
if ok := cache.WaitForCacheSync(stopCh, c.hasSynced); !ok {
|
||||
}
|
||||
klog.Infof("Finished syncing with Kubernetes API (NetworkPolicy)")
|
||||
|
||||
@@ -279,13 +279,13 @@ func (c *Controller) multiClusterSync(ctx context.Context, obj client.Object) er
|
||||
return err
|
||||
}
|
||||
|
||||
switch obj.(type) {
|
||||
switch obj := obj.(type) {
|
||||
case *v2beta1.Config:
|
||||
return c.syncFederatedConfig(obj.(*v2beta1.Config))
|
||||
return c.syncFederatedConfig(obj)
|
||||
case *v2beta1.Receiver:
|
||||
return c.syncFederatedReceiver(obj.(*v2beta1.Receiver))
|
||||
return c.syncFederatedReceiver(obj)
|
||||
case *corev1.Secret:
|
||||
return c.syncFederatedSecret(obj.(*corev1.Secret))
|
||||
return c.syncFederatedSecret(obj)
|
||||
default:
|
||||
klog.Errorf("unknown type for notification, %v", obj)
|
||||
return nil
|
||||
|
||||
@@ -55,9 +55,6 @@ var (
|
||||
v2beta1.AddToScheme(scheme.Scheme)
|
||||
apis.AddToScheme(scheme.Scheme)
|
||||
|
||||
const timeout = time.Second * 30
|
||||
const interval = time.Second * 1
|
||||
|
||||
secret := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "foo",
|
||||
@@ -100,6 +97,7 @@ var (
|
||||
)
|
||||
BeforeEach(func() {
|
||||
k8sClient = fakek8s.NewSimpleClientset()
|
||||
//nolint:staticcheck
|
||||
cl = fake.NewFakeClientWithScheme(scheme.Scheme)
|
||||
informerCacheCtx = context.TODO()
|
||||
ksCache = &fakeCache{
|
||||
|
||||
@@ -41,10 +41,6 @@ func init() {
|
||||
registerMetrics()
|
||||
}
|
||||
|
||||
const (
|
||||
helmApplicationControllerName = "helm-application-controller"
|
||||
)
|
||||
|
||||
var _ reconcile.Reconciler = &ReconcileHelmApplication{}
|
||||
|
||||
// ReconcileHelmApplication reconciles a federated helm application object
|
||||
|
||||
@@ -96,10 +96,7 @@ var _ = Describe("helmApplication", func() {
|
||||
Eventually(func() bool {
|
||||
var ver v1alpha1.HelmApplicationVersion
|
||||
err := k8sClient.Get(context.Background(), types.NamespacedName{Name: appVer2.Name}, &ver)
|
||||
if apierrors.IsNotFound(err) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return apierrors.IsNotFound(err)
|
||||
}, timeout, interval).Should(BeTrue())
|
||||
|
||||
By("Active app version exists")
|
||||
|
||||
@@ -53,7 +53,7 @@ func (r *ReconcileHelmApplicationVersion) Reconcile(ctx context.Context, request
|
||||
start := time.Now()
|
||||
klog.V(4).Infof("sync helm application version: %s", request.String())
|
||||
defer func() {
|
||||
klog.V(4).Infof("sync helm application version end: %s, elapsed: %v", request.String(), time.Now().Sub(start))
|
||||
klog.V(4).Infof("sync helm application version end: %s, elapsed: %v", request.String(), time.Since(start))
|
||||
}()
|
||||
|
||||
appVersion := &v1alpha1.HelmApplicationVersion{}
|
||||
@@ -97,10 +97,7 @@ func (r *ReconcileHelmApplicationVersion) Reconcile(ctx context.Context, request
|
||||
|
||||
// Delete HelmApplicationVersion
|
||||
appVersion.ObjectMeta.Finalizers = sliceutil.RemoveString(appVersion.ObjectMeta.Finalizers, func(item string) bool {
|
||||
if item == HelmAppVersionFinalizer {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return item == HelmAppVersionFinalizer
|
||||
})
|
||||
if err := r.Update(context.Background(), appVersion); err != nil {
|
||||
return reconcile.Result{}, err
|
||||
|
||||
@@ -25,8 +25,6 @@ import (
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"k8s.io/client-go/util/workqueue"
|
||||
"k8s.io/klog"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -178,8 +176,6 @@ var _ reconcile.Reconciler = &ReconcileHelmCategory{}
|
||||
type ReconcileHelmCategory struct {
|
||||
client.Client
|
||||
//Scheme *runtime.Scheme
|
||||
recorder record.EventRecorder
|
||||
config *rest.Config
|
||||
}
|
||||
|
||||
func (r *ReconcileHelmCategory) SetupWithManager(mgr ctrl.Manager) error {
|
||||
@@ -195,7 +191,7 @@ func (r *ReconcileHelmCategory) Reconcile(ctx context.Context, request reconcile
|
||||
start := time.Now()
|
||||
klog.V(4).Infof("sync helm category: %s", request.String())
|
||||
defer func() {
|
||||
klog.V(4).Infof("sync helm category end: %s, elapsed: %v", request.String(), time.Now().Sub(start))
|
||||
klog.V(4).Infof("sync helm category end: %s, elapsed: %v", request.String(), time.Since(start))
|
||||
}()
|
||||
|
||||
instance := &v1alpha1.HelmCategory{}
|
||||
@@ -237,10 +233,7 @@ func (r *ReconcileHelmCategory) Reconcile(ctx context.Context, request reconcile
|
||||
}
|
||||
|
||||
instance.ObjectMeta.Finalizers = sliceutil.RemoveString(instance.ObjectMeta.Finalizers, func(item string) bool {
|
||||
if item == HelmCategoryFinalizer {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return item == HelmCategoryFinalizer
|
||||
})
|
||||
if err := r.Update(context.Background(), instance); err != nil {
|
||||
return reconcile.Result{}, err
|
||||
@@ -297,8 +290,7 @@ func (r *ReconcileHelmCategory) updateCategoryCount(id string) error {
|
||||
|
||||
func (r *ReconcileHelmCategory) countApplications(id string) (int, error) {
|
||||
list := v1alpha1.HelmApplicationList{}
|
||||
var err error
|
||||
err = r.List(context.TODO(), &list, client.MatchingLabels{
|
||||
err := r.List(context.TODO(), &list, client.MatchingLabels{
|
||||
constants.CategoryIdLabelKey: id,
|
||||
constants.ChartRepoIdLabelKey: v1alpha1.AppStoreRepoId,
|
||||
})
|
||||
|
||||
@@ -39,7 +39,7 @@ func (r *ReconcileHelmRelease) GetChartData(rls *v1alpha1.HelmRelease) (chartNam
|
||||
return chartName, chartData, ErrGetRepoFailed
|
||||
}
|
||||
|
||||
index, err := helmrepoindex.ByteArrayToSavedIndex([]byte(repo.Status.Data))
|
||||
index, _ := helmrepoindex.ByteArrayToSavedIndex([]byte(repo.Status.Data))
|
||||
|
||||
if version := index.GetApplicationVersion(rls.Spec.ApplicationId, rls.Spec.ApplicationVersionId); version != nil {
|
||||
url := version.Spec.URLs[0]
|
||||
|
||||
@@ -27,8 +27,6 @@ import (
|
||||
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"k8s.io/klog"
|
||||
ctrl "sigs.k8s.io/controller-runtime"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -68,10 +66,8 @@ type ReconcileHelmRelease struct {
|
||||
StorageClient s3.Interface
|
||||
KsFactory externalversions.SharedInformerFactory
|
||||
client.Client
|
||||
recorder record.EventRecorder
|
||||
// mock helm install && uninstall
|
||||
helmMock bool
|
||||
informer cache.SharedIndexInformer
|
||||
checkReleaseStatusBackoff *flowcontrol.Backoff
|
||||
|
||||
clusterClients clusterclient.ClusterClients
|
||||
@@ -163,10 +159,7 @@ func (r *ReconcileHelmRelease) Reconcile(ctx context.Context, request reconcile.
|
||||
klog.V(3).Infof("remove helm release %s finalizer", instance.Name)
|
||||
// remove finalizer
|
||||
instance.ObjectMeta.Finalizers = sliceutil.RemoveString(instance.ObjectMeta.Finalizers, func(item string) bool {
|
||||
if item == HelmReleaseFinalizer {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return item == HelmReleaseFinalizer
|
||||
})
|
||||
if err := r.Update(context.Background(), instance); err != nil {
|
||||
return reconcile.Result{}, err
|
||||
|
||||
@@ -102,7 +102,7 @@ func (r *ReconcileHelmRepo) Reconcile(ctx context.Context, request reconcile.Req
|
||||
start := time.Now()
|
||||
klog.Infof("sync repo: %s", request.Name)
|
||||
defer func() {
|
||||
klog.Infof("sync repo end: %s, elapsed: %v", request.Name, time.Now().Sub(start))
|
||||
klog.Infof("sync repo end: %s, elapsed: %v", request.Name, time.Since(start))
|
||||
}()
|
||||
// Fetch the helmrepoes instance
|
||||
instance := &v1alpha1.HelmRepo{}
|
||||
@@ -137,10 +137,7 @@ func (r *ReconcileHelmRepo) Reconcile(ctx context.Context, request reconcile.Req
|
||||
if sliceutil.HasString(instance.ObjectMeta.Finalizers, HelmRepoFinalizer) {
|
||||
// remove our finalizer from the list and update it.
|
||||
instance.ObjectMeta.Finalizers = sliceutil.RemoveString(instance.ObjectMeta.Finalizers, func(item string) bool {
|
||||
if item == HelmRepoFinalizer {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return item == HelmRepoFinalizer
|
||||
})
|
||||
if err := r.Update(context.Background(), instance); err != nil {
|
||||
return reconcile.Result{}, err
|
||||
|
||||
@@ -174,9 +174,8 @@ func (a *accessor) GetQuotas(namespaceName string) ([]corev1.ResourceQuota, erro
|
||||
func (a *accessor) waitForReadyResourceQuotaNames(namespaceName string) ([]string, error) {
|
||||
ctx := context.TODO()
|
||||
var resourceQuotaNames []string
|
||||
var err error
|
||||
// wait for a valid mapping cache. The overall response can be delayed for up to 10 seconds.
|
||||
err = utilwait.PollImmediate(100*time.Millisecond, 8*time.Second, func() (done bool, err error) {
|
||||
err := utilwait.PollImmediate(100*time.Millisecond, 8*time.Second, func() (done bool, err error) {
|
||||
resourceQuotaNames, err = resourceQuotaNamesFor(ctx, a.client, namespaceName)
|
||||
// if we can't find the namespace yet, just wait for the cache to update. Requests to non-existent namespaces
|
||||
// may hang, but those people are doing something wrong and namespace lifecycle should reject them.
|
||||
@@ -194,9 +193,8 @@ func (a *accessor) waitForReadyResourceQuotaNames(namespaceName string) ([]strin
|
||||
func (a *accessor) waitForReadyNamespacedResourceQuotas(namespaceName string) ([]corev1.ResourceQuota, error) {
|
||||
ctx := context.TODO()
|
||||
var resourceQuotas []corev1.ResourceQuota
|
||||
var err error
|
||||
// wait for a valid mapping cache. The overall response can be delayed for up to 10 seconds.
|
||||
err = utilwait.PollImmediate(100*time.Millisecond, 8*time.Second, func() (done bool, err error) {
|
||||
err := utilwait.PollImmediate(100*time.Millisecond, 8*time.Second, func() (done bool, err error) {
|
||||
resourceQuotaList := &corev1.ResourceQuotaList{}
|
||||
err = a.client.List(ctx, resourceQuotaList, &client.ListOptions{Namespace: namespaceName})
|
||||
if err != nil {
|
||||
|
||||
@@ -85,6 +85,7 @@ var _ = Describe("ServiceAccount", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
reconciler := &Reconciler{
|
||||
//nolint:staticcheck
|
||||
Client: fake.NewFakeClientWithScheme(scheme.Scheme),
|
||||
logger: ctrl.Log.WithName("controllers").WithName("acrpullbinding-controller"),
|
||||
scheme: scheme.Scheme,
|
||||
@@ -109,6 +110,7 @@ var _ = Describe("ServiceAccount", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
reconciler := &Reconciler{
|
||||
//nolint:staticcheck
|
||||
Client: fake.NewFakeClientWithScheme(scheme.Scheme),
|
||||
logger: ctrl.Log.WithName("controllers").WithName("acrpullbinding-controller"),
|
||||
scheme: scheme.Scheme,
|
||||
|
||||
@@ -154,7 +154,6 @@ func (c *StorageCapabilityController) enqueueStorageClassByCSI(csi interface{})
|
||||
c.enqueueStorageClass(obj)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *StorageCapabilityController) runWorker() {
|
||||
@@ -246,7 +245,6 @@ func (c *StorageCapabilityController) updateSnapshotAnnotation(storageClass *sto
|
||||
if _, err := strconv.ParseBool(storageClass.Annotations[annotationAllowSnapshot]); err != nil {
|
||||
storageClass.Annotations[annotationAllowSnapshot] = strconv.FormatBool(snapshotAllow)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *StorageCapabilityController) updateCloneVolumeAnnotation(storageClass *storagev1.StorageClass, cloneAllow bool) {
|
||||
@@ -256,7 +254,6 @@ func (c *StorageCapabilityController) updateCloneVolumeAnnotation(storageClass *
|
||||
if _, err := strconv.ParseBool(storageClass.Annotations[annotationAllowClone]); err != nil {
|
||||
storageClass.Annotations[annotationAllowClone] = strconv.FormatBool(cloneAllow)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *StorageCapabilityController) removeAnnotations(storageClass *storagev1.StorageClass) {
|
||||
|
||||
@@ -47,7 +47,8 @@ type fixture struct {
|
||||
snapshotSupported bool
|
||||
// Clients
|
||||
k8sClient *k8sfake.Clientset
|
||||
ksClient *ksfake.Clientset
|
||||
//nolint:unused
|
||||
ksClient *ksfake.Clientset
|
||||
// Objects from here preload into NewSimpleFake.
|
||||
storageObjects []runtime.Object // include StorageClass
|
||||
// Objects to put in the store.
|
||||
|
||||
@@ -45,12 +45,14 @@ var (
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
t *testing.T
|
||||
t *testing.T
|
||||
//nolint:unused
|
||||
snapshotSupported bool
|
||||
// Clients
|
||||
k8sClient *k8sFake.Clientset
|
||||
snapshotClassClient *snapFake.Clientset
|
||||
ksClient *ksfake.Clientset
|
||||
//nolint:unused
|
||||
ksClient *ksfake.Clientset
|
||||
// Objects from here preload into NewSimpleFake.
|
||||
storageObjects []runtime.Object // include StorageClass
|
||||
snapshotClassObjects []runtime.Object
|
||||
|
||||
@@ -19,7 +19,6 @@ package controller
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
@@ -28,9 +27,8 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
alwaysReady = func() bool { return true }
|
||||
noResyncPeriodFunc = func() time.Duration { return 0 }
|
||||
controllerName = "base-controler-test"
|
||||
alwaysReady = func() bool { return true }
|
||||
controllerName = "base-controler-test"
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
@@ -48,7 +46,6 @@ func (in *fakeObj) DeepCopyInto(out *fakeObj) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlobalRole.
|
||||
|
||||
@@ -227,6 +227,7 @@ func (v *VirtualServiceController) syncService(key string) error {
|
||||
}
|
||||
|
||||
// default component name to service name
|
||||
//nolint:ineffassign,staticcheck
|
||||
appName := name
|
||||
|
||||
defer func() {
|
||||
@@ -322,7 +323,6 @@ func (v *VirtualServiceController) syncService(key string) error {
|
||||
switch strategies[0].Spec.StrategyPolicy {
|
||||
case servicemeshv1alpha2.PolicyPause:
|
||||
vs.Spec = v.generateDefaultVirtualServiceSpec(name, subsets, service).Spec
|
||||
break
|
||||
case servicemeshv1alpha2.PolicyWaitForWorkloadReady:
|
||||
set := v.getSubsets(strategies[0])
|
||||
|
||||
|
||||
@@ -189,43 +189,6 @@ func newDestinationRule(name string, host string, labels map[string]string, subs
|
||||
return &dr
|
||||
}
|
||||
|
||||
func newStrategy(name string, service *v1.Service, principalVersion string) *v1alpha2.Strategy {
|
||||
st := v1alpha2.Strategy{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: service.Namespace,
|
||||
Labels: NewLabels().WithApp(""),
|
||||
Annotations: nil,
|
||||
},
|
||||
Spec: v1alpha2.StrategySpec{
|
||||
Type: v1alpha2.CanaryType,
|
||||
PrincipalVersion: principalVersion,
|
||||
GovernorVersion: "",
|
||||
Template: v1alpha2.VirtualServiceTemplateSpec{
|
||||
ObjectMeta: metav1.ObjectMeta{},
|
||||
Spec: apiv1alpha3.VirtualService{
|
||||
Hosts: []string{service.Name},
|
||||
Http: []*apiv1alpha3.HTTPRoute{
|
||||
{
|
||||
Route: []*apiv1alpha3.HTTPRouteDestination{
|
||||
{
|
||||
Destination: &apiv1alpha3.Destination{
|
||||
Host: service.Name,
|
||||
Subset: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
StrategyPolicy: v1alpha2.PolicyImmediately,
|
||||
},
|
||||
}
|
||||
|
||||
return &st
|
||||
}
|
||||
|
||||
func toHost(service *v1.Service) string {
|
||||
return fmt.Sprintf("%s.%s.svc", service.Name, service.Namespace)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ package workspacerolebinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo"
|
||||
@@ -55,7 +54,7 @@ var _ = Describe("WorkspaceRoleBinding", func() {
|
||||
It("Should create successfully", func() {
|
||||
workspaceAdminBinding := &iamv1alpha2.WorkspaceRoleBinding{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: fmt.Sprintf("admin-workspace1-admin"),
|
||||
Name: "admin-workspace1-admin",
|
||||
Labels: map[string]string{tenantv1alpha1.WorkspaceLabel: workspace.Name},
|
||||
},
|
||||
RoleRef: rbacv1.RoleRef{
|
||||
|
||||
@@ -46,6 +46,7 @@ var _ = Describe("WorkspaceTemplate", func() {
|
||||
BeforeEach(func() {
|
||||
|
||||
reconciler = &Reconciler{
|
||||
//nolint:staticcheck
|
||||
Client: fake.NewFakeClientWithScheme(scheme.Scheme),
|
||||
Logger: ctrl.Log.WithName("controllers").WithName("acrpullbinding-controller"),
|
||||
Recorder: record.NewFakeRecorder(5),
|
||||
|
||||
@@ -47,7 +47,6 @@ func AddToContainer(container *restful.Container, informers informers.InformerFa
|
||||
if informers == nil || promResourceClient == nil || ruleClient == nil || option == nil {
|
||||
h := func(req *restful.Request, resp *restful.Response) {
|
||||
ksapi.HandleBadRequest(resp, nil, alertingv2alpha1.ErrAlertingAPIV2NotEnabled)
|
||||
return
|
||||
}
|
||||
ws.Route(ws.GET("/{path:*}").To(h).Returns(http.StatusOK, ksapi.StatusOK, nil))
|
||||
ws.Route(ws.PUT("/{path:*}").To(h).Returns(http.StatusOK, ksapi.StatusOK, nil))
|
||||
|
||||
@@ -225,10 +225,10 @@ func (h *handler) generateDefaultDeployment(cluster *v1alpha1.Cluster, w io.Writ
|
||||
fmt.Sprintf("--name=%s", cluster.Name),
|
||||
fmt.Sprintf("--token=%s", cluster.Spec.Connection.Token),
|
||||
fmt.Sprintf("--proxy-server=%s", h.proxyAddress),
|
||||
fmt.Sprintf("--keepalive=10s"),
|
||||
fmt.Sprintf("--kubesphere-service=ks-apiserver.kubesphere-system.svc:80"),
|
||||
fmt.Sprintf("--kubernetes-service=kubernetes.default.svc:443"),
|
||||
fmt.Sprintf("--v=0"),
|
||||
"--keepalive=10s",
|
||||
"--kubesphere-service=ks-apiserver.kubesphere-system.svc:80",
|
||||
"--kubernetes-service=kubernetes.default.svc:443",
|
||||
"--v=0",
|
||||
},
|
||||
Image: h.agentImage,
|
||||
Resources: corev1.ResourceRequirements{
|
||||
@@ -421,6 +421,7 @@ func validateKubeSphereAPIServer(config *rest.Config) (*version.Info, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
responseBytes, _ := ioutil.ReadAll(response.Body)
|
||||
responseBody := string(responseBytes)
|
||||
|
||||
@@ -354,6 +354,7 @@ func TestValidateKubeConfig(t *testing.T) {
|
||||
env := &envtest.Environment{
|
||||
Config: config,
|
||||
ControlPlane: envtest.ControlPlane{
|
||||
//nolint:staticcheck
|
||||
APIServer: &envtest.APIServer{
|
||||
Args: envtest.DefaultKubeAPIServerFlags,
|
||||
URL: u,
|
||||
@@ -413,6 +414,7 @@ func TestValidateMemberClusterConfiguration(t *testing.T) {
|
||||
env := &envtest.Environment{
|
||||
Config: config,
|
||||
ControlPlane: envtest.ControlPlane{
|
||||
//nolint:staticcheck
|
||||
APIServer: &envtest.APIServer{
|
||||
Args: envtest.DefaultKubeAPIServerFlags,
|
||||
URL: u,
|
||||
|
||||
@@ -551,6 +551,4 @@ func ExportMetrics(resp *restful.Response, metrics model.Metrics, startTime, end
|
||||
api.HandleBadRequest(resp, nil, err)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -83,9 +83,6 @@ type Metric struct {
|
||||
Max float64 `json:"max"`
|
||||
}
|
||||
|
||||
func (m Metric) first() time.Time { return m.Samples[0].Timestamp }
|
||||
func (m Metric) last() time.Time { return m.Samples[len(m.Samples)-1].Timestamp }
|
||||
|
||||
// Sample is a single datapoint of a metric.
|
||||
type Sample struct {
|
||||
Timestamp time.Time `json:"date"`
|
||||
|
||||
@@ -655,7 +655,9 @@ func (h *handler) logout(req *restful.Request, resp *restful.Response) {
|
||||
|
||||
state := req.QueryParameter("state")
|
||||
if state != "" {
|
||||
redirectURL.Query().Add("state", state)
|
||||
qry := redirectURL.Query()
|
||||
qry.Add("state", state)
|
||||
redirectURL.RawQuery = qry.Encode()
|
||||
}
|
||||
|
||||
resp.Header().Set("Content-Type", "text/plain")
|
||||
|
||||
@@ -707,7 +707,6 @@ func (h *openpitrixHandler) DescribeApplication(req *restful.Request, resp *rest
|
||||
}
|
||||
|
||||
resp.WriteEntity(app)
|
||||
return
|
||||
}
|
||||
|
||||
func (h *openpitrixHandler) DeleteApplication(req *restful.Request, resp *restful.Response) {
|
||||
@@ -988,7 +987,7 @@ func (h *openpitrixHandler) CreateAttachment(req *restful.Request, resp *restful
|
||||
api.HandleBadRequest(resp, nil, err)
|
||||
return
|
||||
}
|
||||
data, err := ioutil.ReadAll(f)
|
||||
data, _ := ioutil.ReadAll(f)
|
||||
f.Close()
|
||||
|
||||
att, err = h.openpitrix.CreateAttachment(data)
|
||||
|
||||
@@ -84,7 +84,6 @@ func (h *openpitrixHandler) DescribeApplication(req *restful.Request, resp *rest
|
||||
}
|
||||
|
||||
resp.WriteEntity(app)
|
||||
return
|
||||
}
|
||||
|
||||
func (h *openpitrixHandler) ListApplications(req *restful.Request, resp *restful.Response) {
|
||||
|
||||
@@ -73,10 +73,6 @@ func newResourceHandler(k8sClient kubernetes.Interface, factory informers.Inform
|
||||
}
|
||||
}
|
||||
|
||||
func (r *resourceHandler) handleGetNamespacedResources(request *restful.Request, response *restful.Response) {
|
||||
r.handleListNamespaceResources(request, response)
|
||||
}
|
||||
|
||||
func (r *resourceHandler) handleListNamespaceResources(request *restful.Request, response *restful.Response) {
|
||||
namespace := request.PathParameter("namespace")
|
||||
resource := request.PathParameter("resources")
|
||||
|
||||
@@ -127,16 +127,12 @@ func (h *Handler) fallback(resourceType string, namespace string, q *query.Query
|
||||
switch field {
|
||||
case query.FieldName:
|
||||
conditions.Fuzzy[v1alpha2.Name] = string(value)
|
||||
break
|
||||
case query.FieldNames:
|
||||
conditions.Match[v1alpha2.Name] = string(value)
|
||||
break
|
||||
case query.FieldCreationTimeStamp:
|
||||
conditions.Match[v1alpha2.CreateTime] = string(value)
|
||||
break
|
||||
case query.FieldLastUpdateTimestamp:
|
||||
conditions.Match[v1alpha2.UpdateTime] = string(value)
|
||||
break
|
||||
case query.FieldLabel:
|
||||
values := strings.SplitN(string(value), ":", 2)
|
||||
if len(values) == 2 {
|
||||
@@ -144,7 +140,6 @@ func (h *Handler) fallback(resourceType string, namespace string, q *query.Query
|
||||
} else {
|
||||
conditions.Match[v1alpha2.Label] = values[0]
|
||||
}
|
||||
break
|
||||
case query.FieldAnnotation:
|
||||
values := strings.SplitN(string(value), ":", 2)
|
||||
if len(values) == 2 {
|
||||
@@ -152,16 +147,12 @@ func (h *Handler) fallback(resourceType string, namespace string, q *query.Query
|
||||
} else {
|
||||
conditions.Match[v1alpha2.Annotation] = values[0]
|
||||
}
|
||||
break
|
||||
case query.FieldStatus:
|
||||
conditions.Match[v1alpha2.Status] = string(value)
|
||||
break
|
||||
case query.FieldOwnerReference:
|
||||
conditions.Match[v1alpha2.Owner] = string(value)
|
||||
break
|
||||
default:
|
||||
conditions.Match[string(field)] = string(value)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,4 @@ func (h *tenantHandler) HandlePriceInfoQuery(req *restful.Request, resp *restful
|
||||
priceResponse.PvcPerGigabytesPerHour = priceInfo.PvcPerGigabytesPerHour
|
||||
|
||||
resp.WriteAsJson(priceResponse)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -91,8 +91,8 @@ func Test_passwordAuthenticator_Authenticate(t *testing.T) {
|
||||
ksClient := fakeks.NewSimpleClientset()
|
||||
ksInformerFactory := ksinformers.NewSharedInformerFactory(ksClient, 0)
|
||||
err := ksInformerFactory.Iam().V1alpha2().Users().Informer().GetIndexer().Add(newUser("user1", "100001", "fakepwd"))
|
||||
err = ksInformerFactory.Iam().V1alpha2().Users().Informer().GetIndexer().Add(newUser("user3", "100003", ""))
|
||||
err = ksInformerFactory.Iam().V1alpha2().Users().Informer().GetIndexer().Add(newActiveUser("user4", "password"))
|
||||
_ = ksInformerFactory.Iam().V1alpha2().Users().Informer().GetIndexer().Add(newUser("user3", "100003", ""))
|
||||
_ = ksInformerFactory.Iam().V1alpha2().Users().Informer().GetIndexer().Add(newActiveUser("user4", "password"))
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -126,6 +126,7 @@ func TestHandler_Get(t *testing.T) {
|
||||
h := NewTyped(&fakeClient{c}, cm1.GroupVersionKind(), Scheme)
|
||||
|
||||
type args struct {
|
||||
//nolint:unused
|
||||
gvk schema.GroupVersionKind
|
||||
key types.NamespacedName
|
||||
}
|
||||
|
||||
@@ -210,6 +210,7 @@ func (d devopsOperator) ListDevOpsProject(workspace string, limit, offset int) (
|
||||
if err != nil {
|
||||
return api.ListResult{}, nil
|
||||
}
|
||||
//nolint:staticcheck,ineffassign
|
||||
items := make([]interface{}, 0)
|
||||
var result []interface{}
|
||||
for _, item := range data {
|
||||
@@ -550,7 +551,7 @@ func (d devopsOperator) GetNodesDetail(projectName, pipelineName, runId string,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Nodes, err := json.Marshal(respNodes)
|
||||
Nodes, _ := json.Marshal(respNodes)
|
||||
err = json.Unmarshal(Nodes, &nodesDetails)
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
@@ -722,7 +723,7 @@ func (d devopsOperator) GetBranchNodesDetail(projectName, pipelineName, branchNa
|
||||
klog.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
Nodes, err := json.Marshal(respNodes)
|
||||
Nodes, _ := json.Marshal(respNodes)
|
||||
err = json.Unmarshal(Nodes, &nodesDetails)
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
@@ -982,9 +983,9 @@ func getInputReqBody(reqBody io.ReadCloser) (newReqBody io.ReadCloser, err error
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(Body, &checkBody)
|
||||
json.Unmarshal(Body, &checkBody)
|
||||
|
||||
if checkBody.Abort != true && checkBody.Parameters == nil {
|
||||
if !checkBody.Abort && checkBody.Parameters == nil {
|
||||
workRound.Parameters = []devops.CheckPlayloadParameters{}
|
||||
workRound.ID = checkBody.ID
|
||||
jsonBody, _ = json.Marshal(workRound)
|
||||
|
||||
@@ -39,7 +39,6 @@ import (
|
||||
|
||||
const (
|
||||
fileaContents = "This is a test file."
|
||||
fileaKey = "binary"
|
||||
fileaName = "filea.txt"
|
||||
boundary = `MyBoundary`
|
||||
ns = "testns"
|
||||
@@ -63,6 +62,7 @@ func TestS2iBinaryUploader(t *testing.T) {
|
||||
informerFactory := ksinformers.NewSharedInformerFactory(fakeKubeClient, 0)
|
||||
stopCh := make(chan struct{})
|
||||
s2iInformer := informerFactory.Devops().V1alpha1().S2iBinaries()
|
||||
//nolint:ineffassign,staticcheck
|
||||
err := s2iInformer.Informer().GetIndexer().Add(s2ib)
|
||||
defer close(stopCh)
|
||||
informerFactory.Start(stopCh)
|
||||
|
||||
@@ -53,6 +53,7 @@ func Test_gatewayOperator_GetGateways(t *testing.T) {
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
corev1.AddToScheme(Scheme)
|
||||
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
client.Create(context.TODO(), &v1alpha1.Gateway{
|
||||
@@ -69,9 +70,11 @@ func Test_gatewayOperator_GetGateways(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
//nolint:staticcheck
|
||||
client2 := fake.NewFakeClientWithScheme(Scheme)
|
||||
create_GlobalGateway(client2)
|
||||
|
||||
//nolint:staticcheck
|
||||
client3 := fake.NewFakeClientWithScheme(Scheme)
|
||||
create_LegacyGateway(client3, "project6")
|
||||
|
||||
@@ -316,7 +319,7 @@ func Test_gatewayOperator_CreateGateway(t *testing.T) {
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
corev1.AddToScheme(Scheme)
|
||||
appsv1.AddToScheme(Scheme)
|
||||
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
tests := []struct {
|
||||
@@ -420,6 +423,7 @@ func Test_gatewayOperator_DeleteGateway(t *testing.T) {
|
||||
|
||||
var Scheme = runtime.NewScheme()
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
client.Create(context.TODO(), &v1alpha1.Gateway{
|
||||
@@ -486,6 +490,7 @@ func Test_gatewayOperator_UpdateGateway(t *testing.T) {
|
||||
|
||||
var Scheme = runtime.NewScheme()
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
client.Create(context.TODO(), &v1alpha1.Gateway{
|
||||
@@ -569,10 +574,12 @@ func Test_gatewayOperator_UpgradeGateway(t *testing.T) {
|
||||
|
||||
var Scheme = runtime.NewScheme()
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
corev1.AddToScheme(Scheme)
|
||||
appsv1.AddToScheme(Scheme)
|
||||
//nolint:staticcheck
|
||||
client2 := fake.NewFakeClientWithScheme(Scheme)
|
||||
create_LegacyGateway(client2, "project2")
|
||||
create_LegacyGatewayConfigMap(client2, "project2")
|
||||
@@ -672,7 +679,7 @@ func Test_gatewayOperator_ListGateways(t *testing.T) {
|
||||
v1alpha1.AddToScheme(Scheme)
|
||||
corev1.AddToScheme(Scheme)
|
||||
appsv1.AddToScheme(Scheme)
|
||||
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
create_LegacyGateway(client, "project2")
|
||||
@@ -830,7 +837,9 @@ func Test_gatewayOperator_status(t *testing.T) {
|
||||
corev1.AddToScheme(Scheme)
|
||||
appsv1.AddToScheme(Scheme)
|
||||
|
||||
//nolint:staticcheck
|
||||
client := fake.NewFakeClientWithScheme(Scheme)
|
||||
//nolint:staticcheck
|
||||
client2 := fake.NewFakeClientWithScheme(Scheme)
|
||||
|
||||
fake := &corev1.Node{
|
||||
|
||||
@@ -141,6 +141,7 @@ func NewOperator(ksClient kubesphere.Interface, k8sClient kubernetes.Interface,
|
||||
}
|
||||
|
||||
func (am *amOperator) GetGlobalRoleOfUser(username string) (*iamv1alpha2.GlobalRole, error) {
|
||||
//nolint:ineffassign,staticcheck
|
||||
globalRoleBindings, err := am.ListGlobalRoleBindings(username)
|
||||
if len(globalRoleBindings) > 0 {
|
||||
// Usually, only one globalRoleBinding will be found which is created from ks-console.
|
||||
|
||||
@@ -159,8 +159,6 @@ func (as *AppStatistic) Aggregate() {
|
||||
as.NetBytesReceived += daemonsetObj.NetBytesReceived
|
||||
as.PVCBytesTotal += daemonsetObj.PVCBytesTotal
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
type ServiceStatistic struct {
|
||||
|
||||
@@ -528,6 +528,7 @@ func (mo monitoringOperator) GetAppWorkloads(ns string, apps []string) map[strin
|
||||
if applicationVersion != "" && appObject.Labels[constants.ApplicationVersion] != applicationVersion {
|
||||
return false
|
||||
}
|
||||
//nolint:staticcheck
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -547,41 +548,6 @@ func (mo monitoringOperator) GetAppWorkloads(ns string, apps []string) map[strin
|
||||
return componentsMap
|
||||
}
|
||||
|
||||
func (mo monitoringOperator) getApplicationPVCs(appObject *v1beta1.Application) []string {
|
||||
|
||||
var pvcList []string
|
||||
|
||||
ns := appObject.Namespace
|
||||
for _, com := range appObject.Status.ComponentList.Objects {
|
||||
|
||||
switch strings.Title(com.Kind) {
|
||||
case "Deployment":
|
||||
deployObj, err := mo.k8s.AppsV1().Deployments(ns).Get(context.Background(), com.Name, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
klog.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, vol := range deployObj.Spec.Template.Spec.Volumes {
|
||||
pvcList = append(pvcList, vol.PersistentVolumeClaim.ClaimName)
|
||||
}
|
||||
case "Statefulset":
|
||||
stsObj, err := mo.k8s.AppsV1().StatefulSets(ns).Get(context.Background(), com.Name, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
klog.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
for _, vol := range stsObj.Spec.Template.Spec.Volumes {
|
||||
pvcList = append(pvcList, vol.PersistentVolumeClaim.ClaimName)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return pvcList
|
||||
|
||||
}
|
||||
|
||||
func (mo monitoringOperator) GetSerivePodsMap(ns string, services []string) map[string][]string {
|
||||
var svcPodsMap = make(map[string][]string)
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ func (raw *Metrics) Sort(target, order, identifier string) *Metrics {
|
||||
for _, mv := range item.MetricValues {
|
||||
v, ok := mv.Metadata[identifier]
|
||||
if ok && v != "" {
|
||||
ordinal, _ := resourceOrdinal[v]
|
||||
ordinal := resourceOrdinal[v]
|
||||
sorted[ordinal] = mv
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,9 +31,6 @@ const (
|
||||
METER_RESOURCE_TYPE_NET_EGRESS
|
||||
METER_RESOURCE_TYPE_PVC
|
||||
|
||||
meteringConfigDir = "/etc/kubesphere/metering/"
|
||||
meteringConfigName = "ks-metering.yaml"
|
||||
|
||||
meteringDefaultPrecision = 10
|
||||
meteringFeePrecision = 3
|
||||
)
|
||||
|
||||
@@ -19,7 +19,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"kubesphere.io/kubesphere/pkg/apiserver/query"
|
||||
@@ -539,47 +538,6 @@ func (c *applicationOperator) modifyAppAttachment(app *v1alpha1.HelmApplication,
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// modify icon or attachment of the app
|
||||
// added: new attachments have been saved to store
|
||||
// deleted: attachments should be deleted
|
||||
func (c *applicationOperator) appAttachmentDiff(old, newApp *v1alpha1.HelmApplication) (added, deleted []string) {
|
||||
|
||||
added = make([]string, 0, 7)
|
||||
deleted = make([]string, 0, 7)
|
||||
|
||||
if old.Spec.Icon != newApp.Spec.Icon {
|
||||
if old.Spec.Icon != "" && !strings.HasPrefix(old.Spec.Icon, "http://") {
|
||||
deleted = append(deleted, old.Spec.Icon)
|
||||
}
|
||||
added = append(added, newApp.Spec.Icon)
|
||||
}
|
||||
|
||||
existsAtt := make(map[string]string, 6)
|
||||
newAtt := make(map[string]string, 6)
|
||||
|
||||
for _, id := range newApp.Spec.Attachments {
|
||||
newAtt[id] = ""
|
||||
}
|
||||
|
||||
for _, id := range old.Spec.Attachments {
|
||||
existsAtt[id] = ""
|
||||
}
|
||||
|
||||
for _, id := range newApp.Spec.Attachments {
|
||||
if _, exists := existsAtt[id]; !exists {
|
||||
added = append(added, id)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range old.Spec.Attachments {
|
||||
if _, exists := newAtt[id]; !exists {
|
||||
deleted = append(deleted, id)
|
||||
}
|
||||
}
|
||||
|
||||
return added, deleted
|
||||
}
|
||||
|
||||
func (c *applicationOperator) DescribeApp(id string) (*App, error) {
|
||||
var helmApp *v1alpha1.HelmApplication
|
||||
var ctg *v1alpha1.HelmCategory
|
||||
|
||||
@@ -58,7 +58,7 @@ func TestOpenPitrixApp(t *testing.T) {
|
||||
}
|
||||
|
||||
// validate corrupted package
|
||||
validateResp, err = appOperator.ValidatePackage(validateReq)
|
||||
_, err = appOperator.ValidatePackage(validateReq)
|
||||
if err == nil {
|
||||
klog.Errorf("validate package failed, error: %s", err)
|
||||
t.FailNow()
|
||||
@@ -79,7 +79,7 @@ func TestOpenPitrixApp(t *testing.T) {
|
||||
}
|
||||
|
||||
// add app to indexer
|
||||
apps, err := ksClient.ApplicationV1alpha1().HelmApplications().List(context.TODO(), metav1.ListOptions{})
|
||||
apps, _ := ksClient.ApplicationV1alpha1().HelmApplications().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, app := range apps.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmApplications().
|
||||
Informer().GetIndexer().Add(&app)
|
||||
@@ -90,7 +90,7 @@ func TestOpenPitrixApp(t *testing.T) {
|
||||
}
|
||||
|
||||
// add app version to indexer
|
||||
appvers, err := ksClient.ApplicationV1alpha1().HelmApplicationVersions().List(context.TODO(), metav1.ListOptions{})
|
||||
appvers, _ := ksClient.ApplicationV1alpha1().HelmApplicationVersions().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, ver := range appvers.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmApplicationVersions().
|
||||
Informer().GetIndexer().Add(&ver)
|
||||
|
||||
@@ -373,45 +373,27 @@ func (c *applicationOperator) DoAppVersionAction(versionId string, request *Acti
|
||||
|
||||
switch request.Action {
|
||||
case ActionCancel:
|
||||
if version.Status.State != v1alpha1.StateSubmitted {
|
||||
}
|
||||
state = v1alpha1.StateDraft
|
||||
audit.State = v1alpha1.StateDraft
|
||||
case ActionPass:
|
||||
if version.Status.State != v1alpha1.StateSubmitted {
|
||||
|
||||
}
|
||||
state = v1alpha1.StatePassed
|
||||
audit.State = v1alpha1.StatePassed
|
||||
case ActionRecover:
|
||||
if version.Status.State != v1alpha1.StateSuspended {
|
||||
|
||||
}
|
||||
state = v1alpha1.StateActive
|
||||
audit.State = v1alpha1.StateActive
|
||||
case ActionReject:
|
||||
if version.Status.State != v1alpha1.StateSubmitted {
|
||||
// todo check status
|
||||
}
|
||||
// todo check status
|
||||
state = v1alpha1.StateRejected
|
||||
audit.State = v1alpha1.StateRejected
|
||||
case ActionSubmit:
|
||||
if version.Status.State != v1alpha1.StateDraft {
|
||||
// todo check status
|
||||
}
|
||||
// todo check status
|
||||
state = v1alpha1.StateSubmitted
|
||||
audit.State = v1alpha1.StateSubmitted
|
||||
case ActionSuspend:
|
||||
if version.Status.State != v1alpha1.StateActive {
|
||||
// todo check status
|
||||
}
|
||||
state = v1alpha1.StateSuspended
|
||||
audit.State = v1alpha1.StateSuspended
|
||||
case ActionRelease:
|
||||
// release to app store
|
||||
if version.Status.State != v1alpha1.StatePassed {
|
||||
// todo check status
|
||||
}
|
||||
state = v1alpha1.StateActive
|
||||
audit.State = v1alpha1.StateActive
|
||||
default:
|
||||
|
||||
@@ -170,7 +170,7 @@ func (c *categoryOperator) ModifyCategory(id string, request *ModifyCategoryRequ
|
||||
|
||||
func (c *categoryOperator) DescribeCategory(id string) (*Category, error) {
|
||||
var err error
|
||||
ctg := &v1alpha1.HelmCategory{}
|
||||
var ctg *v1alpha1.HelmCategory
|
||||
ctg, err = c.ctgClient.HelmCategories().Get(context.TODO(), id, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestOpenPitrixCategory(t *testing.T) {
|
||||
}
|
||||
|
||||
// add category to indexer
|
||||
ctgs, err := ksClient.ApplicationV1alpha1().HelmCategories().List(context.TODO(), metav1.ListOptions{})
|
||||
ctgs, _ := ksClient.ApplicationV1alpha1().HelmCategories().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, ctg := range ctgs.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmCategories().
|
||||
Informer().GetIndexer().Add(&ctg)
|
||||
|
||||
@@ -30,6 +30,4 @@ var (
|
||||
|
||||
loadRepoInfoFailed = errors.New("load repo info failed")
|
||||
downloadFileFailed = errors.New("download file failed")
|
||||
readFileFailed = errors.New("read file failed")
|
||||
releaseExists = errors.New("release exists")
|
||||
)
|
||||
|
||||
@@ -128,9 +128,9 @@ func (c *releaseOperator) UpgradeApplication(request UpgradeClusterRequest) erro
|
||||
}
|
||||
|
||||
patch := client.MergeFrom(oldRls)
|
||||
data, err := patch.Data(newRls)
|
||||
data, _ := patch.Data(newRls)
|
||||
|
||||
newRls, err = c.rlsClient.Patch(context.TODO(), request.ClusterId, patch.Type(), data, metav1.PatchOptions{})
|
||||
_, err = c.rlsClient.Patch(context.TODO(), request.ClusterId, patch.Type(), data, metav1.PatchOptions{})
|
||||
if err != nil {
|
||||
klog.Errorf("patch release %s/%s failed, error: %s", request.Namespace, request.ClusterId, err)
|
||||
return err
|
||||
@@ -198,7 +198,7 @@ func (c *releaseOperator) CreateApplication(workspace, clusterName, namespace st
|
||||
rls.Labels[constants.ChartRepoIdLabelKey] = repoId
|
||||
}
|
||||
|
||||
rls, err = c.rlsClient.Create(context.TODO(), rls, metav1.CreateOptions{})
|
||||
_, err = c.rlsClient.Create(context.TODO(), rls, metav1.CreateOptions{})
|
||||
|
||||
if err != nil {
|
||||
klog.Errorln(err)
|
||||
@@ -379,7 +379,7 @@ func (c *releaseOperator) DescribeApplication(workspace, clusterName, namespace,
|
||||
|
||||
func (c *releaseOperator) DeleteApplication(workspace, clusterName, namespace, id string) error {
|
||||
|
||||
rls, err := c.rlsLister.Get(id)
|
||||
_, err := c.rlsLister.Get(id)
|
||||
if err != nil {
|
||||
if apierrors.IsNotFound(err) {
|
||||
return nil
|
||||
@@ -389,8 +389,6 @@ func (c *releaseOperator) DeleteApplication(workspace, clusterName, namespace, i
|
||||
}
|
||||
|
||||
// TODO, check workspace, cluster and namespace
|
||||
if rls.GetWorkspace() != workspace || rls.GetRlsCluster() != clusterName || rls.GetRlsNamespace() != namespace {
|
||||
}
|
||||
|
||||
err = c.rlsClient.Delete(context.TODO(), id, metav1.DeleteOptions{})
|
||||
|
||||
@@ -421,21 +419,3 @@ func (c *releaseOperator) getAppVersion(repoId, id string) (ret *v1alpha1.HelmAp
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// get app version from repo and helm application
|
||||
func (c *releaseOperator) getAppVersionWithData(repoId, id string) (ret *v1alpha1.HelmApplicationVersion, err error) {
|
||||
if ver, exists, _ := c.cachedRepos.GetAppVersionWithData(id); exists {
|
||||
return ver, nil
|
||||
}
|
||||
|
||||
if repoId != "" && repoId != v1alpha1.AppStoreRepoId {
|
||||
return nil, fmt.Errorf("not found")
|
||||
}
|
||||
ret, err = c.appVersionLister.Get(id)
|
||||
|
||||
if err != nil && !apierrors.IsNotFound(err) {
|
||||
klog.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestOpenPitrixRelease(t *testing.T) {
|
||||
}
|
||||
|
||||
// add app to indexer
|
||||
apps, err := ksClient.ApplicationV1alpha1().HelmApplications().List(context.TODO(), metav1.ListOptions{})
|
||||
apps, _ := ksClient.ApplicationV1alpha1().HelmApplications().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, app := range apps.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmApplications().
|
||||
Informer().GetIndexer().Add(&app)
|
||||
@@ -61,7 +61,7 @@ func TestOpenPitrixRelease(t *testing.T) {
|
||||
}
|
||||
|
||||
// add app version to indexer
|
||||
appvers, err := ksClient.ApplicationV1alpha1().HelmApplicationVersions().List(context.TODO(), metav1.ListOptions{})
|
||||
appvers, _ := ksClient.ApplicationV1alpha1().HelmApplicationVersions().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, ver := range appvers.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmApplicationVersions().
|
||||
Informer().GetIndexer().Add(&ver)
|
||||
@@ -87,7 +87,7 @@ func TestOpenPitrixRelease(t *testing.T) {
|
||||
}
|
||||
|
||||
// add app version to indexer
|
||||
rls, err := ksClient.ApplicationV1alpha1().HelmReleases().List(context.TODO(), metav1.ListOptions{})
|
||||
rls, _ := ksClient.ApplicationV1alpha1().HelmReleases().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, item := range rls.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmReleases().
|
||||
Informer().GetIndexer().Add(&item)
|
||||
|
||||
@@ -61,7 +61,7 @@ func TestOpenPitrixRepo(t *testing.T) {
|
||||
}
|
||||
|
||||
// validate the corrupt repo
|
||||
validateRes, err = repoOperator.ValidateRepo("http://www.baidu.com", &repo.Spec.Credential)
|
||||
_, err = repoOperator.ValidateRepo("http://www.baidu.com", &repo.Spec.Credential)
|
||||
if err == nil {
|
||||
klog.Errorf("validate category failed")
|
||||
t.Fail()
|
||||
@@ -75,7 +75,7 @@ func TestOpenPitrixRepo(t *testing.T) {
|
||||
}
|
||||
|
||||
// add category to indexer
|
||||
repos, err := ksClient.ApplicationV1alpha1().HelmRepos().List(context.TODO(), metav1.ListOptions{})
|
||||
repos, _ := ksClient.ApplicationV1alpha1().HelmRepos().List(context.TODO(), metav1.ListOptions{})
|
||||
for _, repo := range repos.Items {
|
||||
err := fakeInformerFactory.KubeSphereSharedInformerFactory().Application().V1alpha1().HelmRepos().
|
||||
Informer().GetIndexer().Add(&repo)
|
||||
|
||||
@@ -94,7 +94,7 @@ func (c *repoOperator) DoRepoAction(repoId string, request *RepoActionRequest) e
|
||||
klog.Errorf("create patch [%s] failed, error: %s", repoId, err)
|
||||
return err
|
||||
}
|
||||
repo, err = c.repoClient.HelmRepos().Patch(context.TODO(), repoId, types.MergePatchType, data, metav1.PatchOptions{})
|
||||
_, err = c.repoClient.HelmRepos().Patch(context.TODO(), repoId, types.MergePatchType, data, metav1.PatchOptions{})
|
||||
if err != nil {
|
||||
klog.Errorf("patch repo [%s] failed, error: %s", repoId, err)
|
||||
return err
|
||||
@@ -140,8 +140,7 @@ func (c *repoOperator) CreateRepo(repo *v1alpha1.HelmRepo) (*CreateRepoResponse,
|
||||
}
|
||||
|
||||
func (c *repoOperator) DeleteRepo(id string) error {
|
||||
var err error
|
||||
err = c.repoClient.HelmRepos().Delete(context.TODO(), id, metav1.DeleteOptions{})
|
||||
err := c.repoClient.HelmRepos().Delete(context.TODO(), id, metav1.DeleteOptions{})
|
||||
if err != nil && !apierrors.IsNotFound(err) {
|
||||
klog.Errorf("delete repo %s failed, error: %s", id, err)
|
||||
return err
|
||||
@@ -256,7 +255,7 @@ func (c *repoOperator) ModifyRepo(id string, request *ModifyRepoRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
repo, err = c.repoClient.HelmRepos().Patch(context.TODO(), id, patch.Type(), data, metav1.PatchOptions{})
|
||||
_, err = c.repoClient.HelmRepos().Patch(context.TODO(), id, patch.Type(), data, metav1.PatchOptions{})
|
||||
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
|
||||
@@ -165,7 +165,7 @@ func matchPackageFailedError(err error, res *ValidatePackageResponse) {
|
||||
|
||||
case strings.HasPrefix(errStr, "missing file ["):
|
||||
|
||||
matched := regexp.MustCompile("missing file \\[(.+)]").FindStringSubmatch(errStr)
|
||||
matched := regexp.MustCompile(`missing file \\[(.+)]`).FindStringSubmatch(errStr)
|
||||
if len(matched) > 0 {
|
||||
errorDetails[matched[1]] = "not found"
|
||||
}
|
||||
@@ -258,10 +258,8 @@ func convertApplication(rls *v1alpha1.HelmRelease, rlsInfos []*resource.Info) *A
|
||||
}
|
||||
|
||||
app.ReleaseInfo = make([]runtime.Object, 0, len(rlsInfos))
|
||||
if rlsInfos != nil {
|
||||
for _, info := range rlsInfos {
|
||||
app.ReleaseInfo = append(app.ReleaseInfo, info.Object)
|
||||
}
|
||||
for _, info := range rlsInfos {
|
||||
app.ReleaseInfo = append(app.ReleaseInfo, info.Object)
|
||||
}
|
||||
|
||||
return app
|
||||
@@ -605,10 +603,7 @@ func filterAppByName(app *v1alpha1.HelmApplication, namePart string) bool {
|
||||
}
|
||||
|
||||
name := app.GetTrueName()
|
||||
if strings.Contains(strings.ToLower(name), strings.ToLower(namePart)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return strings.Contains(strings.ToLower(name), strings.ToLower(namePart))
|
||||
}
|
||||
|
||||
func filterAppByStates(app *v1alpha1.HelmApplication, state []string) bool {
|
||||
@@ -749,7 +744,7 @@ func filterReleaseByStates(rls *v1alpha1.HelmRelease, state []string) bool {
|
||||
}
|
||||
|
||||
func filterReleasesWithAppVersions(releases []*v1alpha1.HelmRelease, appVersions map[string]*v1alpha1.HelmApplicationVersion) []*v1alpha1.HelmRelease {
|
||||
if appVersions == nil || len(appVersions) == 0 || len(releases) == 0 {
|
||||
if len(appVersions) == 0 || len(releases) == 0 {
|
||||
return []*v1alpha1.HelmRelease{}
|
||||
}
|
||||
|
||||
@@ -803,10 +798,6 @@ func dataKeyInStorage(workspace, id string) string {
|
||||
return path.Join(workspace, id)
|
||||
}
|
||||
|
||||
func attachmentKeyInStorage(ws, id string) string {
|
||||
return path.Join(ws, id)
|
||||
}
|
||||
|
||||
func convertAppVersionReview(app *v1alpha1.HelmApplication, appVersion *v1alpha1.HelmApplicationVersion) *AppVersionReview {
|
||||
review := &AppVersionReview{}
|
||||
status := appVersion.Status
|
||||
|
||||
@@ -56,7 +56,7 @@ type DockerURL struct {
|
||||
func (u *DockerURL) StringWithoutScheme() string {
|
||||
u.Scheme = ""
|
||||
s := u.String()
|
||||
return strings.Trim(s, "//")
|
||||
return strings.Trim(s, "/")
|
||||
}
|
||||
|
||||
func ParseDockerURL(rawurl string) (*DockerURL, error) {
|
||||
|
||||
@@ -27,8 +27,7 @@ import (
|
||||
const (
|
||||
// DefaultRegistry is the registry name that will be used if no registry
|
||||
// provided and the default is not overridden.
|
||||
DefaultRegistry = "index.docker.io"
|
||||
defaultRegistryAlias = "docker.io"
|
||||
DefaultRegistry = "index.docker.io"
|
||||
|
||||
// DefaultTag is the tag name that will be used if no tag provided and the
|
||||
// default is not overridden.
|
||||
|
||||
@@ -113,7 +113,7 @@ func (r *ResourceGetter) GetResource(namespace, resource, name string) (interfac
|
||||
}
|
||||
|
||||
func (r *ResourceGetter) ListResources(namespace, resource string, conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error) {
|
||||
items := make([]interface{}, 0)
|
||||
var items []interface{}
|
||||
var err error
|
||||
var result []interface{}
|
||||
|
||||
|
||||
@@ -103,8 +103,5 @@ func (s *roleSearcher) Search(namespace string, conditions *params.Conditions, o
|
||||
|
||||
// role created by user from kubesphere dashboard
|
||||
func isUserFacingRole(role *rbac.Role) bool {
|
||||
if role.Annotations[constants.CreatorAnnotationKey] != "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return role.Annotations[constants.CreatorAnnotationKey] != ""
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ func TestGetListClusterDashboards(t *testing.T) {
|
||||
t.Fatalf("unable add APIs to scheme: %v", err)
|
||||
}
|
||||
|
||||
//nolint:staticcheck
|
||||
c = fake.NewFakeClientWithScheme(sch)
|
||||
|
||||
var labelSet1 = map[string]string{"foo-1": "bar-1"}
|
||||
|
||||
@@ -47,6 +47,7 @@ func TestGetListDashboards(t *testing.T) {
|
||||
t.Fatalf("unable add APIs to scheme: %v", err)
|
||||
}
|
||||
|
||||
//nolint:staticcheck
|
||||
c = fake.NewFakeClientWithScheme(sch)
|
||||
|
||||
var labelSet1 = map[string]string{"foo-1": "bar-1"}
|
||||
|
||||
@@ -365,9 +365,9 @@ func (c *routerOperator) createOrUpdateRouterWorkload(namespace string, publishS
|
||||
}
|
||||
|
||||
if createDeployment {
|
||||
deployment, err = c.client.AppsV1().Deployments(ingressControllerNamespace).Create(context.Background(), deployment, metav1.CreateOptions{})
|
||||
_, err = c.client.AppsV1().Deployments(ingressControllerNamespace).Create(context.Background(), deployment, metav1.CreateOptions{})
|
||||
} else {
|
||||
deployment, err = c.client.AppsV1().Deployments(ingressControllerNamespace).Update(context.Background(), deployment, metav1.UpdateOptions{})
|
||||
_, err = c.client.AppsV1().Deployments(ingressControllerNamespace).Update(context.Background(), deployment, metav1.UpdateOptions{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -22,9 +22,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"kubesphere.io/kubesphere/pkg/constants"
|
||||
"kubesphere.io/kubesphere/pkg/models/metering"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
appv1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
@@ -40,6 +37,8 @@ import (
|
||||
"kubesphere.io/kubesphere/pkg/apiserver/authorization/authorizer"
|
||||
"kubesphere.io/kubesphere/pkg/apiserver/query"
|
||||
"kubesphere.io/kubesphere/pkg/apiserver/request"
|
||||
"kubesphere.io/kubesphere/pkg/constants"
|
||||
"kubesphere.io/kubesphere/pkg/models/metering"
|
||||
monitoringmodel "kubesphere.io/kubesphere/pkg/models/monitoring"
|
||||
"kubesphere.io/kubesphere/pkg/models/openpitrix"
|
||||
"kubesphere.io/kubesphere/pkg/server/params"
|
||||
@@ -735,41 +734,6 @@ func (t *tenantOperator) classifyPodStats(user user.Info, cluster, ns string, po
|
||||
return
|
||||
}
|
||||
|
||||
func (t *tenantOperator) listServices(user user.Info, ns string) (*corev1.ServiceList, error) {
|
||||
|
||||
svcScope := request.NamespaceScope
|
||||
|
||||
listSvc := authorizer.AttributesRecord{
|
||||
User: user,
|
||||
Verb: "list",
|
||||
Resource: "services",
|
||||
Namespace: ns,
|
||||
ResourceRequest: true,
|
||||
ResourceScope: svcScope,
|
||||
}
|
||||
|
||||
decision, _, err := t.authorizer.Authorize(listSvc)
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if decision != authorizer.DecisionAllow {
|
||||
_, err := t.am.ListRoleBindings(user.GetName(), nil, ns)
|
||||
if err != nil {
|
||||
klog.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
svcs, err := t.k8sclient.CoreV1().Services(ns).List(context.Background(), metav1.ListOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return svcs, nil
|
||||
}
|
||||
|
||||
// updateDeploysStats will update deployment field in resource stats struct with pod stats data and deployments will be classified into 3 classes:
|
||||
// 1. openpitrix deployments
|
||||
// 2. app deployments
|
||||
|
||||
@@ -79,13 +79,11 @@ type TerminalMessage struct {
|
||||
// TerminalSize handles pty->process resize events
|
||||
// Called in a loop from remotecommand as long as the process is running
|
||||
func (t TerminalSession) Next() *remotecommand.TerminalSize {
|
||||
select {
|
||||
case size := <-t.sizeChan:
|
||||
if size.Height == 0 && size.Width == 0 {
|
||||
return nil
|
||||
}
|
||||
return &size
|
||||
size := <-t.sizeChan
|
||||
if size.Height == 0 && size.Width == 0 {
|
||||
return nil
|
||||
}
|
||||
return &size
|
||||
}
|
||||
|
||||
// Read handles pty->process messages (stdin, resize)
|
||||
|
||||
@@ -15,9 +15,6 @@ const (
|
||||
epRules = apiPrefix + "/rules"
|
||||
statusAPIError = 422
|
||||
|
||||
statusSuccess status = "success"
|
||||
statusError status = "error"
|
||||
|
||||
ErrBadData ErrorType = "bad_data"
|
||||
ErrTimeout ErrorType = "timeout"
|
||||
ErrCanceled ErrorType = "canceled"
|
||||
@@ -84,10 +81,11 @@ func (c *ruleClient) rules(client api.Client, ctx context.Context) ([]*RuleGroup
|
||||
return nil, errors.Wrap(err, "error creating request: ")
|
||||
}
|
||||
|
||||
_, body, _, err := c.do(client, ctx, req)
|
||||
resp, body, _, err := c.do(client, ctx, req)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error doing request: ")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Groups []*RuleGroup
|
||||
|
||||
@@ -192,6 +192,7 @@ func (b *Build) Stop() (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return false, errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -202,7 +203,8 @@ func (b *Build) Stop() (bool, error) {
|
||||
func (b *Build) GetConsoleOutput() string {
|
||||
url := b.Base + "/consoleText"
|
||||
var content string
|
||||
b.Jenkins.Requester.GetXML(url, &content, nil)
|
||||
rsp, _ := b.Jenkins.Requester.GetXML(url, &content, nil)
|
||||
rsp.Body.Close()
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -224,10 +226,11 @@ func (b *Build) GetInjectedEnvVars() (map[string]string, error) {
|
||||
EnvMap map[string]string `json:"envMap"`
|
||||
}
|
||||
endpoint := b.Base + "/injectedEnvVars"
|
||||
_, err := b.Jenkins.Requester.GetJSON(endpoint, &envVars, nil)
|
||||
rsp, err := b.Jenkins.Requester.GetJSON(endpoint, &envVars, nil)
|
||||
if err != nil {
|
||||
return envVars.EnvMap, err
|
||||
}
|
||||
rsp.Body.Close()
|
||||
return envVars.EnvMap, nil
|
||||
}
|
||||
|
||||
@@ -308,13 +311,12 @@ func (b *Build) GetResultSet() (*TestResult, error) {
|
||||
url := b.Base + "/testReport"
|
||||
var report TestResult
|
||||
|
||||
_, err := b.Jenkins.Requester.GetJSON(url, &report, nil)
|
||||
rsp, err := b.Jenkins.Requester.GetJSON(url, &report, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rsp.Body.Close()
|
||||
return &report, nil
|
||||
|
||||
}
|
||||
|
||||
func (b *Build) GetTimestamp() time.Time {
|
||||
@@ -355,7 +357,10 @@ func (b *Build) IsRunning() bool {
|
||||
func (b *Build) SetDescription(description string) error {
|
||||
data := url.Values{}
|
||||
data.Set("description", description)
|
||||
_, err := b.Jenkins.Requester.Post(b.Base+"/submitDescription", bytes.NewBufferString(data.Encode()), nil, nil)
|
||||
resp, err := b.Jenkins.Requester.Post(b.Base+"/submitDescription", bytes.NewBufferString(data.Encode()), nil, nil)
|
||||
if err != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (b *Build) PauseToggle() error {
|
||||
@@ -363,6 +368,7 @@ func (b *Build) PauseToggle() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -395,6 +401,7 @@ func (b *Build) Poll(options ...interface{}) (int, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response.Body.Close()
|
||||
return response.StatusCode, nil
|
||||
}
|
||||
|
||||
@@ -403,6 +410,7 @@ func (j *Jenkins) GetProjectPipelineBuildByType(projectId, pipelineId string, st
|
||||
if err != nil {
|
||||
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
|
||||
}
|
||||
//nolint:staticcheck
|
||||
build, err := job.getBuildByType(status)
|
||||
return build.Raw, nil
|
||||
}
|
||||
@@ -411,6 +419,7 @@ func (j *Jenkins) GetMultiBranchPipelineBuildByType(projectId, pipelineId, branc
|
||||
if err != nil {
|
||||
return nil, restful.NewError(devops.GetDevOpsStatusCode(err), err.Error())
|
||||
}
|
||||
//nolint:staticcheck
|
||||
build, err := job.getBuildByType(status)
|
||||
return build.Raw, nil
|
||||
}
|
||||
|
||||
@@ -177,6 +177,7 @@ func (j *Jenkins) GetCredentialInProject(projectId, id string) (*devops.Credenti
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -197,6 +198,7 @@ func (j *Jenkins) GetCredentialsInProject(projectId string) ([]*devops.Credentia
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -236,7 +238,7 @@ func (j *Jenkins) CreateCredentialInProject(projectId string, credential *v1.Sec
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -272,6 +274,7 @@ func (j *Jenkins) UpdateCredentialInProject(projectId string, credential *v1.Sec
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
@@ -285,6 +288,7 @@ func (j *Jenkins) DeleteCredentialInProject(projectId, id string) (string, error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.New(strconv.Itoa(response.StatusCode))
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ func (f *Folder) Create(name, description string) (*Folder, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.Body.Close()
|
||||
if r.StatusCode == 200 {
|
||||
f.Poll()
|
||||
return f, nil
|
||||
@@ -71,5 +72,6 @@ func (f *Folder) Poll() (int, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response.Body.Close()
|
||||
return response.StatusCode, nil
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user