use go 1.12

Signed-off-by: hongming <talonwan@yunify.com>
This commit is contained in:
hongming
2019-03-12 15:47:56 +08:00
parent b59c244ca2
commit 4144404b0b
1110 changed files with 161100 additions and 14519 deletions

View File

@@ -18,6 +18,7 @@
package authentication
import (
"context"
"errors"
"fmt"
"k8s.io/apiserver/pkg/authorization/authorizer"
@@ -271,7 +272,7 @@ func pathMatches(path, spec string) bool {
return false
}
func getAuthorizerAttributes(ctx request.Context) (authorizer.Attributes, error) {
func getAuthorizerAttributes(ctx context.Context) (authorizer.Attributes, error) {
attribs := authorizer.AttributesRecord{}
user, ok := request.UserFrom(ctx)

View File

@@ -50,8 +50,13 @@ func Setup(c *caddy.Controller) error {
c.OnStartup(func() error {
stopChan := signals.SetupSignalHandler()
informers.SharedInformerFactory().Start(stopChan)
informers.SharedInformerFactory().WaitForCacheSync(stopChan)
informerFactory := informers.SharedInformerFactory()
informerFactory.Rbac().V1().Roles().Lister()
informerFactory.Rbac().V1().RoleBindings().Lister()
informerFactory.Rbac().V1().ClusterRoles().Lister()
informerFactory.Rbac().V1().ClusterRoleBindings().Lister()
informerFactory.Start(stopChan)
informerFactory.WaitForCacheSync(stopChan)
fmt.Println("Authentication middleware is initiated")
return nil
})

View File

@@ -101,6 +101,7 @@ func addWebService(c *restful.Container) error {
Writes(models.PodInfo{}))
webservice.Route(webservice.GET("/users/{username}/kubeconfig").
Produces("text/plain").
To(resources.GetKubeconfig).
Doc("get users' kubeconfig").
Param(webservice.PathParameter("username", "username")).

View File

@@ -22,6 +22,7 @@ import (
"github.com/dgrijalva/jwt-go"
"github.com/emicklei/go-restful"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/simple/client/ldap"
"net/http"
"kubesphere.io/kubesphere/pkg/errors"
@@ -113,7 +114,7 @@ func TokenReviewHandler(req *restful.Request, resp *restful.Response) {
username := claims["username"].(string)
conn, err := iam.NewConnection()
conn, err := ldap.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))

View File

@@ -19,6 +19,7 @@ package iam
import (
"fmt"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
"net/http"
"regexp"
"strings"
@@ -109,7 +110,7 @@ func GroupDetail(req *restful.Request, resp *restful.Response) {
path := req.PathParameter("path")
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
@@ -133,7 +134,7 @@ func GroupUsers(req *restful.Request, resp *restful.Response) {
path := req.PathParameter("path")
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
@@ -228,7 +229,7 @@ func RootGroupList(req *restful.Request, resp *restful.Response) {
groups := make([]*models.Group, 0)
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))

View File

@@ -31,6 +31,7 @@ import (
"kubesphere.io/kubesphere/pkg/errors"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/iam"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
)
const (
@@ -166,7 +167,7 @@ func CurrentUserDetail(req *restful.Request, resp *restful.Response) {
username := req.HeaderParameter(constants.UserNameHeader)
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
@@ -228,7 +229,7 @@ func NamespacesListHandler(req *restful.Request, resp *restful.Response) {
func UserDetail(req *restful.Request, resp *restful.Response) {
username := req.PathParameter("name")
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
@@ -296,7 +297,7 @@ func UserList(req *restful.Request, resp *restful.Response) {
return
}
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))

View File

@@ -19,6 +19,7 @@ package iam
import (
"fmt"
"github.com/go-ldap/ldap"
"net/http"
"regexp"
"sort"
@@ -26,7 +27,6 @@ import (
"strings"
"github.com/emicklei/go-restful"
"github.com/go-ldap/ldap"
"k8s.io/api/core/v1"
rbac "k8s.io/api/rbac/v1"
apierror "k8s.io/apimachinery/pkg/api/errors"
@@ -37,6 +37,7 @@ import (
"kubesphere.io/kubesphere/pkg/models/iam"
"kubesphere.io/kubesphere/pkg/models/metrics"
"kubesphere.io/kubesphere/pkg/models/workspaces"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
sliceutils "kubesphere.io/kubesphere/pkg/utils"
)
@@ -656,7 +657,7 @@ func WorkspaceMemberList(req *restful.Request, resp *restful.Response) {
offset = 0
}
conn, err := iam.NewConnection()
conn, err := ldapclient.Client()
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))

View File

@@ -19,12 +19,12 @@ package monitoring
import (
"github.com/emicklei/go-restful"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/models/metrics"
"kubesphere.io/kubesphere/pkg/simple/client/prometheus"
)
func MonitorPod(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
podName := requestParams.PodName
metricName := requestParams.MetricsName
if podName != "" {
@@ -49,7 +49,7 @@ func MonitorPod(request *restful.Request, response *restful.Response) {
}
func MonitorContainer(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
metricName := requestParams.MetricsName
if requestParams.MetricsFilter != "" {
rawMetrics := metrics.MonitorAllMetrics(requestParams, metrics.MetricLevelContainer)
@@ -68,7 +68,7 @@ func MonitorContainer(request *restful.Request, response *restful.Response) {
}
func MonitorWorkload(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
rawMetrics := metrics.MonitorAllMetrics(requestParams, metrics.MetricLevelWorkload)
@@ -95,7 +95,7 @@ func MonitorWorkload(request *restful.Request, response *restful.Response) {
func MonitorAllWorkspaces(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
tp := requestParams.Tp
if tp == "_statistics" {
@@ -119,7 +119,7 @@ func MonitorAllWorkspaces(request *restful.Request, response *restful.Response)
}
func MonitorOneWorkspace(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
tp := requestParams.Tp
if tp == "rank" {
@@ -145,7 +145,7 @@ func MonitorOneWorkspace(request *restful.Request, response *restful.Response) {
}
func MonitorNamespace(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
metricName := requestParams.MetricsName
nsName := requestParams.NsName
if nsName != "" {
@@ -166,7 +166,7 @@ func MonitorNamespace(request *restful.Request, response *restful.Response) {
}
func MonitorCluster(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
metricName := requestParams.MetricsName
if metricName != "" {
@@ -183,7 +183,7 @@ func MonitorCluster(request *restful.Request, response *restful.Response) {
}
func MonitorNode(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
metricName := requestParams.MetricsName
if metricName != "" {
@@ -213,7 +213,7 @@ func MonitorNode(request *restful.Request, response *restful.Response) {
// k8s component(controller, scheduler, etcd) status
func MonitorComponentStatus(request *restful.Request, response *restful.Response) {
requestParams := client.ParseMonitoringRequestParams(request)
requestParams := prometheus.ParseMonitoringRequestParams(request)
status := metrics.MonitorComponentStatus(requestParams)
response.WriteAsJson(status)

View File

@@ -51,5 +51,5 @@ func GetKubeconfig(req *restful.Request, resp *restful.Response) {
return
}
resp.WriteAsJson(kubectlConfig)
resp.Write([]byte(kubectlConfig))
}

View File

@@ -52,5 +52,5 @@ var (
SystemWorkspace = "system-workspace"
DevopsAPIServer = "ks-devops-apiserver.kubesphere-system.svc"
AccountAPIServer = "ks-account.kubesphere-system.svc"
SystemNamespaces = []string{KubeSystemNamespace, OpenPitrixNamespace, KubeSystemNamespace}
SystemNamespaces = []string{KubeSphereNamespace, OpenPitrixNamespace, KubeSystemNamespace}
)

View File

@@ -1,29 +0,0 @@
package controller
import (
"kubesphere.io/kubesphere/pkg/controller/namespace"
"log"
"sync"
"time"
"k8s.io/client-go/informers"
"kubesphere.io/kubesphere/pkg/client"
)
const defaultResync = 600 * time.Second
var once sync.Once
func Run(stopCh <-chan struct{}) {
once.Do(func() {
kubeclientset := client.K8sClient()
informerFactory := informers.NewSharedInformerFactory(kubeclientset, defaultResync)
namespaceController := namespace.NewNamespaceController(kubeclientset, informerFactory.Core().V1().Namespaces(), informerFactory.Rbac().V1().Roles())
// data sync
informerFactory.Start(stopCh)
// start workers
namespaceController.Start(stopCh)
log.Println("all controller is running")
})
}

View File

@@ -1,10 +0,0 @@
package controller
import (
"testing"
)
// controller test
func TestController(t *testing.T) {
}

View File

@@ -18,12 +18,11 @@
package informers
import (
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"sync"
"time"
"k8s.io/client-go/informers"
"kubesphere.io/kubesphere/pkg/client"
)
const defaultResync = 600 * time.Second
@@ -35,7 +34,7 @@ var (
func SharedInformerFactory() informers.SharedInformerFactory {
once.Do(func() {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
informerFactory = informers.NewSharedInformerFactory(k8sClient, defaultResync)
})
return informerFactory

View File

@@ -20,8 +20,7 @@ package components
import (
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"kubesphere.io/kubesphere/pkg/informers"
@@ -84,7 +83,7 @@ func GetSystemHealthStatus() (map[string]interface{}, error) {
status := make(map[string]interface{})
componentStatuses, err := client.K8sClient().CoreV1().ComponentStatuses().List(meta_v1.ListOptions{})
componentStatuses, err := k8s.Client().CoreV1().ComponentStatuses().List(meta_v1.ListOptions{})
if err != nil {
return nil, err
}

View File

@@ -23,6 +23,8 @@ import (
"fmt"
"io/ioutil"
"kubesphere.io/kubesphere/pkg/informers"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
"log"
"net/http"
"regexp"
@@ -35,7 +37,6 @@ import (
"k8s.io/apimachinery/pkg/labels"
"k8s.io/kubernetes/pkg/util/slice"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/iam/policy"
@@ -264,7 +265,7 @@ func ClusterRoleUsers(clusterRoleName string) ([]*models.User, error) {
return nil, err
}
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
@@ -306,7 +307,7 @@ func RoleUsers(namespace string, roleName string) ([]*models.User, error) {
return nil, err
}
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
@@ -343,7 +344,7 @@ func NamespaceUsers(namespaceName string) ([]*models.User, error) {
if err != nil {
return nil, err
}
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
@@ -608,7 +609,7 @@ func CreateClusterRoleBinding(username string, clusterRoleName string) error {
}
}
_, err = client.K8sClient().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
if err != nil {
return err
@@ -636,7 +637,7 @@ func CreateClusterRoleBinding(username string, clusterRoleName string) error {
if clusterRoleBinding != nil {
clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, v1.Subject{Kind: v1.UserKind, Name: username})
_, err := client.K8sClient().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
_, err := k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
if err != nil {
return err
}
@@ -647,7 +648,7 @@ func CreateClusterRoleBinding(username string, clusterRoleName string) error {
clusterRoleBinding.RoleRef = v1.RoleRef{Name: clusterRoleName, Kind: ClusterRoleKind}
clusterRoleBinding.Subjects = []v1.Subject{{Kind: v1.UserKind, Name: username}}
_, err = client.K8sClient().RbacV1().ClusterRoleBindings().Create(clusterRoleBinding)
_, err = k8s.Client().RbacV1().ClusterRoleBindings().Create(clusterRoleBinding)
if err != nil {
return err

View File

@@ -22,7 +22,8 @@ import (
"fmt"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/informers"
"log"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"kubesphere.io/kubesphere/pkg/simple/client/redis"
"os"
"regexp"
"strconv"
@@ -35,8 +36,8 @@ import (
"k8s.io/api/rbac/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/models"
jwtutils "kubesphere.io/kubesphere/pkg/utils/jwt"
)
@@ -62,20 +63,7 @@ func init() {
}
func DatabaseInit() error {
var conn ldap.Client
var err error
maxRetry := 5
for retry := 0; retry < maxRetry; retry++ {
conn, err = NewConnection()
if err == nil {
break
} else if retry == maxRetry-1 {
log.Printf("cannot connect to ldap server ,%s", err)
} else {
log.Printf("cannot connect to ldap server ,retry %d/%d\n after 2s", retry+1, maxRetry)
}
time.Sleep(10 * time.Second)
}
conn, err := ldapclient.Client()
if err != nil {
return err
@@ -83,54 +71,21 @@ func DatabaseInit() error {
defer conn.Close()
err = checkAndCreateDefaultUser(conn)
if err != nil {
return err
}
// search for the given username
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=inetOrgPerson))",
nil,
nil,
)
err = checkAndCreateDefaultGroup(conn)
users, err := conn.Search(userSearchRequest)
return err
}
if err != nil {
switch err.(type) {
case *ldap.Error:
if err.(*ldap.Error).ResultCode == 32 {
err := createUserBaseDN()
if err != nil {
return fmt.Errorf("UserBaseDN %s create failed: %s\n", client.UserSearchBase, err)
} else {
log.Printf("UserBaseDN %s create success\n", client.UserSearchBase)
}
} else {
return fmt.Errorf("UserBaseDN %s not exist: %s\n", client.UserSearchBase, err)
}
default:
return fmt.Errorf("UserBaseDN %s not exist: %s\n", client.UserSearchBase, err)
}
}
func checkAndCreateDefaultGroup(conn ldap.Client) error {
counter = NewCounter(len(users.Entries))
if users == nil || len(users.Entries) == 0 {
err := CreateUser(models.User{Username: constants.AdminUserName, Email: AdminEmail, Password: AdminPWD, Description: "Administrator account that was always created by default."})
if err != nil {
return fmt.Errorf("admin create failed: %s\n", err)
}
log.Println("admin init success")
}
// search user group
groupSearchRequest := ldap.NewSearchRequest(
client.GroupSearchBase,
ldapclient.GroupSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=posixGroup))",
nil,
@@ -139,85 +94,83 @@ func DatabaseInit() error {
groups, err := conn.Search(groupSearchRequest)
if err != nil {
switch err.(type) {
case *ldap.Error:
if err.(*ldap.Error).ResultCode == 32 {
err := createGroupsBaseDN()
if err != nil {
return fmt.Errorf("GroupBaseDN %s create failed: %s\n", client.GroupSearchBase, err)
} else {
log.Printf("GroupBaseDN %s create success\n", client.GroupSearchBase)
}
} else {
return fmt.Errorf("GroupBaseDN %s not exist: %s\n", client.GroupSearchBase, err)
}
default:
return fmt.Errorf("GroupBaseDN %s not exist: %s\n", client.GroupSearchBase, err)
}
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
err = createGroupsBaseDN(conn)
}
if groups == nil || len(groups.Entries) == 0 {
systemGroup := models.Group{Path: constants.SystemWorkspace, Name: constants.SystemWorkspace, Creator: constants.AdminUserName, Description: "system workspace"}
if err != nil {
return fmt.Errorf("GroupBaseDN %s not exist: %s\n", ldapclient.GroupSearchBase, err)
}
_, err = CreateGroup(systemGroup)
if len(groups.Entries) == 0 {
_, err = CreateGroup(models.Group{Path: constants.SystemWorkspace, Name: constants.SystemWorkspace, Creator: constants.AdminUserName, Description: "system workspace"})
if err != nil {
return fmt.Errorf("system-group create failed: %s\n", err)
return fmt.Errorf("system-workspace create failed: %s\n", err)
}
log.Println("system-workspace init success")
}
return nil
}
func createUserBaseDN() error {
func checkAndCreateDefaultUser(conn ldap.Client) error {
conn, err := NewConnection()
userSearchRequest := ldap.NewSearchRequest(
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=inetOrgPerson))",
nil,
nil,
)
users, err := conn.Search(userSearchRequest)
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
err = createUserBaseDN(conn)
}
if err != nil {
return fmt.Errorf("UserBaseDN %s not exist: %s\n", ldapclient.UserSearchBase, err)
}
if len(users.Entries) == 0 {
err := CreateUser(models.User{Username: constants.AdminUserName, Email: AdminEmail, Password: AdminPWD, Description: "Administrator account that was always created by default."})
if err != nil {
return fmt.Errorf("admin create failed: %s\n", err)
}
}
counter = NewCounter(len(users.Entries))
return nil
}
func createUserBaseDN(conn ldap.Client) error {
conn, err := ldapclient.Client()
if err != nil {
return err
}
defer conn.Close()
groupsCreateRequest := ldap.NewAddRequest(client.UserSearchBase, nil)
groupsCreateRequest := ldap.NewAddRequest(ldapclient.UserSearchBase, nil)
groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
groupsCreateRequest.Attribute("ou", []string{"Users"})
return conn.Add(groupsCreateRequest)
}
func createGroupsBaseDN() error {
conn, err := NewConnection()
if err != nil {
return err
}
defer conn.Close()
groupsCreateRequest := ldap.NewAddRequest(client.GroupSearchBase, nil)
func createGroupsBaseDN(conn ldap.Client) error {
groupsCreateRequest := ldap.NewAddRequest(ldapclient.GroupSearchBase, nil)
groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
groupsCreateRequest.Attribute("ou", []string{"Groups"})
return conn.Add(groupsCreateRequest)
}
func NewConnection() (ldap.Client, error) {
conn, err := client.LdapClient().Get()
if err != nil {
return nil, err
}
err = conn.Bind(client.ManagerDN, client.ManagerPassword)
if err != nil {
return nil, err
}
return conn, nil
}
// User login
func Login(username string, password string, ip string) (string, error) {
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return "", err
@@ -226,7 +179,7 @@ func Login(username string, password string, ip string) (string, error) {
defer conn.Close()
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", username, username),
[]string{"uid", "mail"},
@@ -257,7 +210,7 @@ func Login(username string, password string, ip string) (string, error) {
}
if ip != "" {
redisClient := client.RedisClient()
redisClient := redis.Client()
redisClient.RPush(fmt.Sprintf("kubesphere:users:%s:login-log", uid), fmt.Sprintf("%s,%s", time.Now().UTC().Format("2006-01-02T15:04:05Z"), ip))
redisClient.LTrim(fmt.Sprintf("kubesphere:users:%s:login-log", uid), -10, -1)
}
@@ -277,7 +230,7 @@ func Login(username string, password string, ip string) (string, error) {
func UserList(limit int, offset int) (int, []models.User, error) {
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return 0, nil, err
@@ -296,7 +249,7 @@ l1:
for {
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=inetOrgPerson))",
[]string{"uid", "mail", "description"},
@@ -329,7 +282,7 @@ l1:
break
}
redisClient := client.RedisClient()
redisClient := redis.Client()
for _, v := range entries {
@@ -369,7 +322,7 @@ l1:
}
func LoginLog(username string) ([]string, error) {
redisClient := client.RedisClient()
redisClient := redis.Client()
data, err := redisClient.LRange(fmt.Sprintf("kubesphere:users:%s:login-log", username), -10, -1).Result()
@@ -382,7 +335,7 @@ func LoginLog(username string) ([]string, error) {
func Search(keyword string, limit int, offset int) (int, []models.User, error) {
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return 0, nil, err
@@ -400,7 +353,7 @@ func Search(keyword string, limit int, offset int) (int, []models.User, error) {
l1:
for {
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=*%s*)(mail=*%s*)(description=*%s*)))", keyword, keyword, keyword),
[]string{"uid", "mail", "description"},
@@ -433,7 +386,7 @@ l1:
break
}
redisClient := client.RedisClient()
redisClient := redis.Client()
for _, v := range entries {
@@ -475,7 +428,7 @@ l1:
func UserDetail(username string, conn ldap.Client) (*models.User, error) {
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", username),
[]string{"mail", "description", "preferredLanguage"},
@@ -498,7 +451,7 @@ func UserDetail(username string, conn ldap.Client) (*models.User, error) {
user := models.User{Username: username, Email: email, Description: description, Lang: lang}
groupSearchRequest := ldap.NewSearchRequest(
client.GroupSearchBase,
ldapclient.GroupSearchBase,
ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=posixGroup)(memberUid=%s))", username),
nil,
@@ -521,7 +474,7 @@ func UserDetail(username string, conn ldap.Client) (*models.User, error) {
user.Groups = groups
redisClient := client.RedisClient()
redisClient := redis.Client()
avatar, err := redisClient.HMGet("kubesphere:users:avatar", username).Result()
@@ -553,14 +506,14 @@ func UserDetail(username string, conn ldap.Client) (*models.User, error) {
func DeleteUser(username string) error {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return err
}
defer conn.Close()
deleteRequest := ldap.NewDelRequest(fmt.Sprintf("uid=%s,%s", username, client.UserSearchBase), nil)
deleteRequest := ldap.NewDelRequest(fmt.Sprintf("uid=%s,%s", username, ldapclient.UserSearchBase), nil)
err = conn.Del(deleteRequest)
@@ -602,13 +555,13 @@ func deleteRoleBindings(username string) error {
if length2 == 0 {
deletePolicy := meta_v1.DeletePropagationForeground
err = client.K8sClient().RbacV1().RoleBindings(roleBinding.Namespace).Delete(roleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Delete(roleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
if err != nil {
glog.Errorf("delete role binding %s %s %s failed: %v", username, roleBinding.Namespace, roleBinding.Name, err)
}
} else if length2 < length1 {
_, err = client.K8sClient().RbacV1().RoleBindings(roleBinding.Namespace).Update(roleBinding)
_, err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Update(roleBinding)
if err != nil {
glog.Errorf("update role binding %s %s %s failed: %v", username, roleBinding.Namespace, roleBinding.Name, err)
@@ -632,16 +585,16 @@ func deleteRoleBindings(username string) error {
length2 := len(clusterRoleBinding.Subjects)
if length2 == 0 {
if groups := regexp.MustCompile(fmt.Sprintf(`^system:(\S+):(%s)$`, strings.Join(constants.WorkSpaceRoles, "|"))).FindStringSubmatch(clusterRoleBinding.RoleRef.Name); len(groups) == 3 {
_, err = client.K8sClient().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
} else {
deletePolicy := meta_v1.DeletePropagationForeground
err = client.K8sClient().RbacV1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
err = k8s.Client().RbacV1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
}
if err != nil {
glog.Errorf("update cluster role binding %s failed:%s", clusterRoleBinding.Name, err)
}
} else if length2 < length1 {
_, err = client.K8sClient().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
if err != nil {
glog.Errorf("update cluster role binding %s failed:%s", clusterRoleBinding.Name, err)
@@ -656,7 +609,7 @@ func deleteRoleBindings(username string) error {
func UserCreateCheck(check string) (exist bool, err error) {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return false, err
@@ -666,7 +619,7 @@ func UserCreateCheck(check string) (exist bool, err error) {
// search for the given username
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", check, check),
[]string{"uid", "mail"},
@@ -692,7 +645,7 @@ func CreateUser(user models.User) error {
user.Password = strings.TrimSpace(user.Password)
user.Description = strings.TrimSpace(user.Description)
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return err
@@ -701,7 +654,7 @@ func CreateUser(user models.User) error {
defer conn.Close()
userSearchRequest := ldap.NewSearchRequest(
client.UserSearchBase,
ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", user.Username, user.Email),
[]string{"uid", "mail"},
@@ -726,7 +679,7 @@ func CreateUser(user models.User) error {
maxUid += 1
userCreateRequest := ldap.NewAddRequest(fmt.Sprintf("uid=%s,%s", user.Username, client.UserSearchBase), nil)
userCreateRequest := ldap.NewAddRequest(fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase), nil)
userCreateRequest.Attribute("objectClass", []string{"inetOrgPerson", "posixAccount", "top"})
userCreateRequest.Attribute("cn", []string{user.Username}) // RFC4519: common name(s) for which the entity is known by
userCreateRequest.Attribute("sn", []string{" "}) // RFC2256: last (family) name(s) for which the entity is known by
@@ -759,7 +712,7 @@ func CreateUser(user models.User) error {
}
func getMaxUid(conn ldap.Client) (int, error) {
userSearchRequest := ldap.NewSearchRequest(client.UserSearchBase,
userSearchRequest := ldap.NewSearchRequest(ldapclient.UserSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=inetOrgPerson))",
[]string{"uidNumber"},
@@ -789,7 +742,7 @@ func getMaxUid(conn ldap.Client) (int, error) {
func getMaxGid(conn ldap.Client) (int, error) {
groupSearchRequest := ldap.NewSearchRequest(client.GroupSearchBase,
groupSearchRequest := ldap.NewSearchRequest(ldapclient.GroupSearchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=posixGroup))",
[]string{"gidNumber"},
@@ -819,14 +772,14 @@ func getMaxGid(conn ldap.Client) (int, error) {
func UpdateUser(user models.User) error {
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return err
}
defer conn.Close()
dn := fmt.Sprintf("uid=%s,%s", user.Username, client.UserSearchBase)
dn := fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase)
userModifyRequest := ldap.NewModifyRequest(dn, nil)
if user.Email != "" {
userModifyRequest.Replace("mail", []string{user.Email})
@@ -860,7 +813,7 @@ func UpdateUser(user models.User) error {
func DeleteGroup(path string) error {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return err
}
@@ -881,7 +834,7 @@ func DeleteGroup(path string) error {
func CreateGroup(group models.Group) (*models.Group, error) {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
}
@@ -922,7 +875,7 @@ func CreateGroup(group models.Group) (*models.Group, error) {
group.CreateTime = time.Now().UTC().Format("2006-01-02T15:04:05Z")
redisClient := client.RedisClient()
redisClient := redis.Client()
if err := redisClient.HMSet("kubesphere:groups:create-time", map[string]interface{}{group.Name: group.CreateTime}).Err(); err != nil {
return nil, err
@@ -937,7 +890,7 @@ func CreateGroup(group models.Group) (*models.Group, error) {
func UpdateGroup(group *models.Group) (*models.Group, error) {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
}
@@ -980,7 +933,7 @@ func UpdateGroup(group *models.Group) (*models.Group, error) {
func CountChild(path string) (int, error) {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return 0, err
}
@@ -988,7 +941,7 @@ func CountChild(path string) (int, error) {
var groupSearchRequest *ldap.SearchRequest
if path == "" {
groupSearchRequest = ldap.NewSearchRequest(client.GroupSearchBase,
groupSearchRequest = ldap.NewSearchRequest(ldapclient.GroupSearchBase,
ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=posixGroup))",
[]string{"cn", "gidNumber", "memberUid", "description"},
@@ -1014,7 +967,7 @@ func CountChild(path string) (int, error) {
func ChildList(path string) ([]models.Group, error) {
// bind root DN
conn, err := NewConnection()
conn, err := ldapclient.Client()
if err != nil {
return nil, err
@@ -1024,7 +977,7 @@ func ChildList(path string) ([]models.Group, error) {
var groupSearchRequest *ldap.SearchRequest
if path == "" {
groupSearchRequest = ldap.NewSearchRequest(client.GroupSearchBase,
groupSearchRequest = ldap.NewSearchRequest(ldapclient.GroupSearchBase,
ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=posixGroup))",
[]string{"cn", "gidNumber", "memberUid", "description"},
@@ -1076,7 +1029,7 @@ func ChildList(path string) ([]models.Group, error) {
group.ChildGroups = childGroups
redisClient := client.RedisClient()
redisClient := redis.Client()
createTime, _ := redisClient.HMGet("kubesphere:groups:create-time", group.Name).Result()
@@ -1132,7 +1085,7 @@ func GroupDetail(path string, conn ldap.Client) (*models.Group, error) {
group.ChildGroups = childGroups
redisClient := client.RedisClient()
redisClient := redis.Client()
createTime, _ := redisClient.HMGet("kubesphere:groups:create-time", group.Name).Result()

View File

@@ -19,7 +19,7 @@ package iam
import (
"fmt"
"kubesphere.io/kubesphere/pkg/client"
ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
"regexp"
"strings"
)
@@ -60,12 +60,12 @@ func splitPath(path string) (searchBase string, cn string) {
basePath[i], basePath[j] = basePath[j], basePath[i]
}
searchBase = fmt.Sprintf("%s,%s", strings.Join(basePath, ","), client.GroupSearchBase)
searchBase = fmt.Sprintf("%s,%s", strings.Join(basePath, ","), ldapclient.GroupSearchBase)
} else if length == 2 {
searchBase = fmt.Sprintf("cn=%s,%s", paths[0], client.GroupSearchBase)
searchBase = fmt.Sprintf("cn=%s,%s", paths[0], ldapclient.GroupSearchBase)
cn = paths[1]
} else {
searchBase = client.GroupSearchBase
searchBase = ldapclient.GroupSearchBase
if paths[0] == "" {
cn = "*"
} else {

View File

@@ -27,6 +27,7 @@ import (
"encoding/base64"
"encoding/pem"
"io/ioutil"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"math/big"
rd "math/rand"
"time"
@@ -39,7 +40,6 @@ import (
"k8s.io/api/core/v1"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/constants"
)
@@ -216,7 +216,7 @@ func createKubeConfig(userName string) (string, error) {
return "", err
}
base64ServerCa := base64.StdEncoding.EncodeToString(serverCa)
tmpClusterInfo := clusterInfo{CertificateAuthorityData: base64ServerCa, Server: client.KubeConfig.Host}
tmpClusterInfo := clusterInfo{CertificateAuthorityData: base64ServerCa, Server: k8s.KubeConfig.Host}
tmpCluster := cluster{Cluster: tmpClusterInfo, Name: clusterName}
tmpKubeConfig.Clusters = append(tmpKubeConfig.Clusters, tmpCluster)
@@ -243,7 +243,7 @@ func createKubeConfig(userName string) (string, error) {
}
func CreateKubeConfig(user string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
_, err := k8sClient.CoreV1().ConfigMaps(constants.KubeSphereControlNamespace).Get(user, metaV1.GetOptions{})
@@ -268,7 +268,7 @@ func CreateKubeConfig(user string) error {
}
func GetKubeConfig(user string) (string, error) {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
configMap, err := k8sClient.CoreV1().ConfigMaps(constants.KubeSphereControlNamespace).Get(user, metaV1.GetOptions{})
if err != nil {
glog.Errorf("cannot get user %s's kubeConfig, reason: %v", user, err)
@@ -278,7 +278,7 @@ func GetKubeConfig(user string) (string, error) {
}
func DelKubeConfig(user string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
_, err := k8sClient.CoreV1().ConfigMaps(constants.KubeSphereControlNamespace).Get(user, metaV1.GetOptions{})
if errors.IsNotFound(err) {
return nil

View File

@@ -21,6 +21,7 @@ package kubectl
import (
"fmt"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"math/rand"
"github.com/golang/glog"
@@ -31,7 +32,6 @@ import (
"k8s.io/apimachinery/pkg/api/errors"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/constants"
)
@@ -40,7 +40,7 @@ const (
)
func GetKubectlPod(username string) (models.PodInfo, error) {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
deploy, err := k8sClient.AppsV1beta2().Deployments(namespace).Get(username, metav1.GetOptions{})
if err != nil {
glog.Errorln(err)
@@ -87,7 +87,7 @@ func selectCorrectPod(namespace string, pods []v1.Pod) (kubectlPod v1.Pod, err e
}
func CreateKubectlDeploy(user string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
_, err := k8sClient.AppsV1().Deployments(namespace).Get(user, metav1.GetOptions{})
if err == nil {
return nil
@@ -128,7 +128,7 @@ func CreateKubectlDeploy(user string) error {
}
func DelKubectlDeploy(user string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
_, err := k8sClient.AppsV1beta2().Deployments(namespace).Get(user, metav1.GetOptions{})
if errors.IsNotFound(err) {
return nil

View File

@@ -21,6 +21,8 @@ package metrics
import (
"fmt"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"kubesphere.io/kubesphere/pkg/simple/client/prometheus"
"net/url"
"regexp"
"strings"
@@ -42,8 +44,6 @@ import (
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"kubesphere.io/kubesphere/pkg/client"
)
var (
@@ -145,7 +145,7 @@ func getAllWorkspaces() map[string]int {
paramValues := make(url.Values)
paramValues.Set("query", WorkspaceNamespaceLabelRule)
params := paramValues.Encode()
res := client.SendMonitoringRequest(client.DefaultQueryType, params)
res := prometheus.SendMonitoringRequest(prometheus.DefaultQueryType, params)
metric := ReformatJson(res, "")
@@ -240,7 +240,7 @@ func unifyMetricHistoryTimeRange(fmtMetrics *FormatedMetric) {
}
}
func AssembleSpecificWorkloadMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string, bool) {
func AssembleSpecificWorkloadMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string, bool) {
nsName := monitoringRequest.NsName
wkName := monitoringRequest.WorkloadName
@@ -250,7 +250,7 @@ func AssembleSpecificWorkloadMetricRequestInfo(monitoringRequest *client.Monitor
paramValues := monitoringRequest.Params
params := makeRequestParamString(rule, paramValues)
res := client.SendMonitoringRequest(client.DefaultQueryType, params)
res := prometheus.SendMonitoringRequest(prometheus.DefaultQueryType, params)
podNamesFilter := getPodNameRegexInWorkload(res, podsFilter)
@@ -261,7 +261,7 @@ func AssembleSpecificWorkloadMetricRequestInfo(monitoringRequest *client.Monitor
return queryType, params, rule == ""
}
func AssembleAllWorkloadMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string) {
func AssembleAllWorkloadMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
@@ -271,7 +271,7 @@ func AssembleAllWorkloadMetricRequestInfo(monitoringRequest *client.MonitoringRe
return queryType, params
}
func AssemblePodMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string, bool) {
func AssemblePodMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string, bool) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
@@ -282,7 +282,7 @@ func AssemblePodMetricRequestInfo(monitoringRequest *client.MonitoringRequestPar
}
func GetMetric(queryType, params, metricName string) *FormatedMetric {
res := client.SendMonitoringRequest(queryType, params)
res := prometheus.SendMonitoringRequest(queryType, params)
formatedMetric := ReformatJson(res, metricName)
return formatedMetric
}
@@ -319,13 +319,13 @@ func AddNodeAddressMetric(nodeMetric *FormatedMetric, nodeAddress *map[string][]
}
}
func MonitorContainer(monitoringRequest *client.MonitoringRequestParams, metricName string) *FormatedMetric {
func MonitorContainer(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) *FormatedMetric {
queryType, params := AssembleContainerMetricRequestInfo(monitoringRequest, metricName)
res := GetMetric(queryType, params, metricName)
return res
}
func AssembleContainerMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string) {
func AssembleContainerMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
@@ -335,7 +335,7 @@ func AssembleContainerMetricRequestInfo(monitoringRequest *client.MonitoringRequ
return queryType, params
}
func AssembleNamespaceMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string) {
func AssembleNamespaceMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
@@ -345,7 +345,7 @@ func AssembleNamespaceMetricRequestInfo(monitoringRequest *client.MonitoringRequ
return queryType, params
}
func AssembleSpecificWorkspaceMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, namespaceList []string, metricName string) (string, string) {
func AssembleSpecificWorkspaceMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, namespaceList []string, metricName string) (string, string) {
nsFilter := "^(" + strings.Join(namespaceList, "|") + ")$"
@@ -357,7 +357,7 @@ func AssembleSpecificWorkspaceMetricRequestInfo(monitoringRequest *client.Monito
return queryType, params
}
func AssembleAllWorkspaceMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, namespaceList []string, metricName string) (string, string) {
func AssembleAllWorkspaceMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, namespaceList []string, metricName string) (string, string) {
var nsFilter = "^()$"
if namespaceList != nil {
@@ -407,7 +407,7 @@ func filterNamespace(nsFilter string, namespaceList []string) []string {
return newNSlist
}
func MonitorAllWorkspaces(monitoringRequest *client.MonitoringRequestParams) *FormatedLevelMetric {
func MonitorAllWorkspaces(monitoringRequest *prometheus.MonitoringRequestParams) *FormatedLevelMetric {
metricsFilter := monitoringRequest.MetricsFilter
if strings.Trim(metricsFilter, " ") == "" {
metricsFilter = ".*"
@@ -470,7 +470,7 @@ func MonitorAllWorkspaces(monitoringRequest *client.MonitoringRequestParams) *Fo
}
}
func collectWorkspaceMetric(monitoringRequest *client.MonitoringRequestParams, ws string, filterMetricsName []string, wgAll *sync.WaitGroup, wsAllch chan *[]FormatedMetric) {
func collectWorkspaceMetric(monitoringRequest *prometheus.MonitoringRequestParams, ws string, filterMetricsName []string, wgAll *sync.WaitGroup, wsAllch chan *[]FormatedMetric) {
defer wgAll.Done()
var wg sync.WaitGroup
var ch = make(chan *FormatedMetric, ChannelMaxCapacity)
@@ -511,7 +511,7 @@ func collectWorkspaceMetric(monitoringRequest *client.MonitoringRequestParams, w
wsAllch <- &metricsArray
}
func MonitorAllMetrics(monitoringRequest *client.MonitoringRequestParams, resourceType string) *FormatedLevelMetric {
func MonitorAllMetrics(monitoringRequest *prometheus.MonitoringRequestParams, resourceType string) *FormatedLevelMetric {
metricsFilter := monitoringRequest.MetricsFilter
if metricsFilter == "" {
metricsFilter = ".*"
@@ -869,8 +869,8 @@ func getSpecificMetricItem(timestamp int64, metricName string, resource string,
}
// k8s component(controller, scheduler, etcd) status
func MonitorComponentStatus(monitoringRequest *client.MonitoringRequestParams) *[]interface{} {
componentList, err := client.K8sClient().CoreV1().ComponentStatuses().List(metaV1.ListOptions{})
func MonitorComponentStatus(monitoringRequest *prometheus.MonitoringRequestParams) *[]interface{} {
componentList, err := k8s.Client().CoreV1().ComponentStatuses().List(metaV1.ListOptions{})
if err != nil {
glog.Errorln(err.Error())
}
@@ -900,7 +900,7 @@ func MonitorComponentStatus(monitoringRequest *client.MonitoringRequestParams) *
paramValues := monitoringRequest.Params
paramValues.Set("query", NodeStatusRule)
params := paramValues.Encode()
res := client.SendMonitoringRequest(queryType, params)
res := prometheus.SendMonitoringRequest(queryType, params)
nodeStatusMetric := ReformatJson(res, "node_status", nodeStatusDelLabel...)
nodeStatusMetric = ReformatNodeStatusField(nodeStatusMetric)
@@ -986,7 +986,7 @@ func makeMetricItems(timestamp int64, statusMap map[string]int, resourceType str
return &metricItems
}
func AssembleClusterMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string) {
func AssembleClusterMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
rule := MakeClusterRule(metricName)
@@ -995,7 +995,7 @@ func AssembleClusterMetricRequestInfo(monitoringRequest *client.MonitoringReques
return queryType, params
}
func AssembleNodeMetricRequestInfo(monitoringRequest *client.MonitoringRequestParams, metricName string) (string, string) {
func AssembleNodeMetricRequestInfo(monitoringRequest *prometheus.MonitoringRequestParams, metricName string) (string, string) {
queryType := monitoringRequest.QueryType
paramValues := monitoringRequest.Params
rule := MakeNodeRule(monitoringRequest.NodeId, monitoringRequest.NodesFilter, metricName)

View File

@@ -1,3 +1,20 @@
/*
Copyright 2019 The KubeSphere 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 metrics
import (
@@ -6,7 +23,7 @@ import (
"k8s.io/api/core/v1"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/simple/client/prometheus"
)
func GetNamespacesWithMetrics(namespaces []*v1.Namespace) []*v1.Namespace {
@@ -17,10 +34,10 @@ func GetNamespacesWithMetrics(namespaces []*v1.Namespace) []*v1.Namespace {
nsFilter := "^(" + strings.Join(nsNameList, "|") + ")$"
var timeRelateParams = make(url.Values)
params := client.MonitoringRequestParams{
params := prometheus.MonitoringRequestParams{
NsFilter: nsFilter,
Params: timeRelateParams,
QueryType: client.DefaultQueryType,
QueryType: prometheus.DefaultQueryType,
MetricsFilter: "namespace_cpu_usage|namespace_memory_usage_wo_cache|namespace_pod_count",
}

View File

@@ -19,6 +19,7 @@ package nodes
import (
"fmt"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"math"
"strings"
"time"
@@ -31,13 +32,11 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"kubesphere.io/kubesphere/pkg/client"
)
func DrainNode(nodename string) (err error) {
k8sclient := client.K8sClient()
k8sclient := k8s.Client()
node, err := k8sclient.CoreV1().Nodes().Get(nodename, metav1.GetOptions{})
if err != nil {
return err
@@ -69,7 +68,7 @@ func DrainNode(nodename string) (err error) {
func drainEviction(nodename string, donech chan bool, errch chan error) {
k8sclient := client.K8sClient()
k8sclient := k8s.Client()
var options metav1.ListOptions
pods := make([]v1.Pod, 0)
options.FieldSelector = "spec.nodeName=" + nodename
@@ -108,7 +107,7 @@ func drainEviction(nodename string, donech chan bool, errch chan error) {
//create eviction
getPodFn := func(namespace, name string) (*v1.Pod, error) {
k8sclient := client.K8sClient()
k8sclient := k8s.Client()
return k8sclient.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
}
evicerr := evictPods(pods, 0, getPodFn)
@@ -160,7 +159,7 @@ func containDaemonset(pod v1.Pod, daemonsetList v1beta2.DaemonSetList) bool {
func evictPod(pod v1.Pod, GracePeriodSeconds int) error {
k8sclient := client.K8sClient()
k8sclient := k8s.Client()
deleteOptions := &metav1.DeleteOptions{}
if GracePeriodSeconds >= 0 {
gracePeriodSeconds := int64(GracePeriodSeconds)

View File

@@ -78,7 +78,7 @@ func (*clusterRoleSearcher) fuzzy(fuzzy map[string]string, item *rbac.ClusterRol
func (*clusterRoleSearcher) compare(a, b *rbac.ClusterRole, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*configMapSearcher) fuzzy(fuzzy map[string]string, item *v1.ConfigMap) boo
func (*configMapSearcher) compare(a, b *v1.ConfigMap, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -90,11 +90,19 @@ func (*cronJobSearcher) fuzzy(fuzzy map[string]string, item *v1beta1.CronJob) bo
func (*cronJobSearcher) compare(a, b *v1beta1.CronJob, orderBy string) bool {
switch orderBy {
case lastScheduleTime:
if a.Status.LastScheduleTime == nil {
return true
}
if b.Status.LastScheduleTime == nil {
return false
}
return a.Status.LastScheduleTime.Before(b.Status.LastScheduleTime)
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
case name:
fallthrough
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
default:
fallthrough
case name:
return strings.Compare(a.Name, b.Name) <= 0
}
}

View File

@@ -93,7 +93,7 @@ func (*daemonSetSearcher) fuzzy(fuzzy map[string]string, item *v1.DaemonSet) boo
func (*daemonSetSearcher) compare(a, b *v1.DaemonSet, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -97,7 +97,7 @@ func (*deploymentSearcher) fuzzy(fuzzy map[string]string, item *v1.Deployment) b
func (*deploymentSearcher) compare(a, b *v1.Deployment, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -83,7 +83,7 @@ func (*ingressSearcher) fuzzy(fuzzy map[string]string, item *extensions.Ingress)
func (*ingressSearcher) compare(a, b *extensions.Ingress, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -112,7 +112,7 @@ func jobUpdateTime(item *batchv1.Job) time.Time {
func (*jobSearcher) compare(a, b *batchv1.Job, orderBy string) bool {
switch orderBy {
case updateTime:
return jobUpdateTime(a).After(jobUpdateTime(b))
return jobUpdateTime(a).Before(jobUpdateTime(b))
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*namespaceSearcher) fuzzy(fuzzy map[string]string, item *v1.Namespace) boo
func (*namespaceSearcher) compare(a, b *v1.Namespace, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*nodeSearcher) fuzzy(fuzzy map[string]string, item *v1.Node) bool {
func (*nodeSearcher) compare(a, b *v1.Node, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*persistentVolumeClaimSearcher) fuzzy(fuzzy map[string]string, item *v1.Pe
func (*persistentVolumeClaimSearcher) compare(a, b *v1.PersistentVolumeClaim, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*podSearcher) fuzzy(fuzzy map[string]string, item *v1.Pod) bool {
func (*podSearcher) compare(a, b *v1.Pod, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -52,6 +52,7 @@ const (
label = "label"
createTime = "createTime"
updateTime = "updateTime"
lastScheduleTime = "lastScheduleTime"
displayName = "displayName"
chart = "chart"
release = "release"

View File

@@ -78,7 +78,7 @@ func (*roleSearcher) fuzzy(fuzzy map[string]string, item *rbac.Role) bool {
func (*roleSearcher) compare(a, b *rbac.Role, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -86,7 +86,7 @@ func (*secretSearcher) fuzzy(fuzzy map[string]string, item *v1.Secret) bool {
func (*secretSearcher) compare(a, b *v1.Secret, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -82,7 +82,7 @@ func (*serviceSearcher) fuzzy(fuzzy map[string]string, item *v1.Service) bool {
func (*serviceSearcher) compare(a, b *v1.Service, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -96,7 +96,7 @@ func (*statefulSetSearcher) fuzzy(fuzzy map[string]string, item *v1.StatefulSet)
func (*statefulSetSearcher) compare(a, b *v1.StatefulSet, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -78,7 +78,7 @@ func (*storageClassesSearcher) fuzzy(fuzzy map[string]string, item *v1.StorageCl
func (*storageClassesSearcher) compare(a, b *v1.StorageClass, orderBy string) bool {
switch orderBy {
case createTime:
return a.CreationTimestamp.Time.After(b.CreationTimestamp.Time)
return a.CreationTimestamp.Time.Before(b.CreationTimestamp.Time)
case name:
fallthrough
default:

View File

@@ -21,6 +21,7 @@ package routers
import (
"fmt"
"io/ioutil"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"k8s.io/apimachinery/pkg/labels"
"kubesphere.io/kubesphere/pkg/informers"
@@ -35,7 +36,6 @@ import (
"strings"
"kubesphere.io/kubesphere/pkg/client"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/models/iam"
)
@@ -139,7 +139,7 @@ func LoadYamls() ([]string, error) {
// Create a ingress controller in a namespace
func CreateRouter(namespace string, routerType corev1.ServiceType, annotations map[string]string) (*corev1.Service, error) {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
var router *corev1.Service
@@ -214,7 +214,7 @@ func CreateRouter(namespace string, routerType corev1.ServiceType, annotations m
// DeleteRouter is used to delete ingress controller related resources in namespace
// It will not delete ClusterRole resource cause it maybe used by other controllers
func DeleteRouter(namespace string) (*corev1.Service, error) {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
var err error
var router *corev1.Service
@@ -269,7 +269,7 @@ func DeleteRouter(namespace string) (*corev1.Service, error) {
// Update Ingress Controller Service, change type from NodePort to Loadbalancer or vice versa.
func UpdateRouter(namespace string, routerType corev1.ServiceType, annotations map[string]string) (*corev1.Service, error) {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
var router *corev1.Service

View File

@@ -19,20 +19,19 @@ package workloads
import (
"fmt"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"strings"
"time"
"github.com/golang/glog"
"k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"kubesphere.io/kubesphere/pkg/client"
)
const retryTimes = 3
func JobReRun(namespace, jobName string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
job, err := k8sClient.BatchV1().Jobs(namespace).Get(jobName, metav1.GetOptions{})
if err != nil {
return err
@@ -72,7 +71,7 @@ func JobReRun(namespace, jobName string) error {
}
func deleteJob(namespace, job string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
deletePolicy := metav1.DeletePropagationBackground
err := k8sClient.BatchV1().Jobs(namespace).Delete(job, &metav1.DeleteOptions{PropagationPolicy: &deletePolicy})
return err

View File

@@ -22,6 +22,8 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"kubesphere.io/kubesphere/pkg/simple/client/mysql"
"net/http"
"kubesphere.io/kubesphere/pkg/constants"
@@ -49,12 +51,11 @@ import (
"sort"
"kubesphere.io/kubesphere/pkg/client"
kserr "kubesphere.io/kubesphere/pkg/errors"
)
func UnBindDevopsProject(workspace string, devops string) error {
db := client.DBClient()
db := mysql.Client()
defer db.Close()
return db.Delete(&models.WorkspaceDPBinding{Workspace: workspace, DevOpsProject: devops}).Error
}
@@ -304,19 +305,19 @@ func Namespaces(workspaceName string) ([]*core.Namespace, error) {
}
func BindingDevopsProject(workspace string, devops string) error {
db := client.DBClient()
db := mysql.Client()
defer db.Close()
return db.Create(&models.WorkspaceDPBinding{Workspace: workspace, DevOpsProject: devops}).Error
}
func DeleteNamespace(workspace string, namespaceName string) error {
namespace, err := client.K8sClient().CoreV1().Namespaces().Get(namespaceName, meta_v1.GetOptions{})
namespace, err := k8s.Client().CoreV1().Namespaces().Get(namespaceName, meta_v1.GetOptions{})
if err != nil {
return err
}
if namespace.Labels != nil && namespace.Labels["kubesphere.io/workspace"] == workspace {
deletePolicy := meta_v1.DeletePropagationForeground
return client.K8sClient().CoreV1().Namespaces().Delete(namespaceName, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
return k8s.Client().CoreV1().Namespaces().Delete(namespaceName, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
} else {
return errors.New("resource not found")
}
@@ -376,7 +377,7 @@ func release(workspace *models.Workspace) error {
return err
}
func workspaceRoleRelease(workspace string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
deletePolicy := meta_v1.DeletePropagationForeground
for _, role := range constants.WorkSpaceRoles {
@@ -513,7 +514,7 @@ func Detail(name string) (*models.Workspace, error) {
return nil, err
}
db := client.DBClient()
db := mysql.Client()
defer db.Close()
workspace, err := convertGroupToWorkspace(db, group)
@@ -604,7 +605,7 @@ func fetch(names []string) ([]*models.Workspace, error) {
return nil, err
}
db := client.DBClient()
db := mysql.Client()
defer db.Close()
@@ -622,7 +623,7 @@ func fetch(names []string) ([]*models.Workspace, error) {
func ListDevopsProjectsByUser(username string, workspace string, keyword string, orderBy string, reverse bool, limit int, offset int) (int, []models.DevopsProject, error) {
db := client.DBClient()
db := mysql.Client()
defer db.Close()
var workspaceDOPBindings []models.WorkspaceDPBinding
@@ -738,7 +739,7 @@ func convertGroupToWorkspace(db *gorm.DB, group models.Group) (*models.Workspace
func CreateNamespace(namespace *core.Namespace) (*core.Namespace, error) {
ns, err := client.K8sClient().CoreV1().Namespaces().Create(namespace)
ns, err := k8s.Client().CoreV1().Namespaces().Create(namespace)
if err != nil {
return nil, err
@@ -784,7 +785,7 @@ func Invite(workspaceName string, users []models.UserInvite) error {
func NamespaceExistCheck(namespaceName string) (bool, error) {
_, err := client.K8sClient().CoreV1().Namespaces().Get(namespaceName, meta_v1.GetOptions{})
_, err := k8s.Client().CoreV1().Namespaces().Get(namespaceName, meta_v1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
@@ -887,7 +888,7 @@ func GetWorkspaceMembers(workspace string, keyword string) ([]models.User, error
}
func WorkspaceRoleInit(workspace *models.Workspace) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
admin := new(v1.ClusterRole)
admin.Name = fmt.Sprintf("system:%s:%s", workspace.Name, constants.WorkspaceAdmin)
@@ -1086,7 +1087,7 @@ func WorkspaceRoleInit(workspace *models.Workspace) error {
}
func unbindWorkspaceRole(workspace string, users []string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
for _, name := range constants.WorkSpaceRoles {
roleBinding, err := k8sClient.RbacV1().ClusterRoleBindings().Get(fmt.Sprintf("system:%s:%s", workspace, name), meta_v1.GetOptions{})
@@ -1118,7 +1119,7 @@ func unbindWorkspaceRole(workspace string, users []string) error {
func unbindNamespacesRole(namespaces []string, users []string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
for _, namespace := range namespaces {
roleBindings, err := k8sClient.RbacV1().RoleBindings(namespace).List(meta_v1.ListOptions{})
@@ -1166,7 +1167,7 @@ func UnbindWorkspace(workspace *models.Workspace, users []string) error {
func CreateWorkspaceRoleBinding(workspace *models.Workspace, username string, role string) error {
k8sClient := client.K8sClient()
k8sClient := k8s.Client()
for _, roleName := range constants.WorkSpaceRoles {
roleBinding, err := k8sClient.RbacV1().ClusterRoleBindings().Get(fmt.Sprintf("system:%s:%s", workspace.Name, roleName), meta_v1.GetOptions{})
@@ -1220,7 +1221,7 @@ func CreateWorkspaceRoleBinding(workspace *models.Workspace, username string, ro
func GetDevOpsProjects(workspaceName string) ([]string, error) {
db := client.DBClient()
db := mysql.Client()
defer db.Close()
var workspaceDOPBindings []models.WorkspaceDPBinding
@@ -1313,7 +1314,7 @@ func GetAllProjectNums() (int, error) {
}
func GetAllDevOpsProjectsNums() (int, error) {
db := client.DBClient()
db := mysql.Client()
defer db.Close()
var count int

View File

@@ -16,7 +16,7 @@
*/
package client
package k8s
import (
"flag"
@@ -44,11 +44,11 @@ func init() {
flag.StringVar(&kubeConfigFile, "kubeconfig", fmt.Sprintf("%s/.kube/config", os.Getenv("HOME")), "path to kubeconfig file")
}
func K8sClient() *kubernetes.Clientset {
func Client() *kubernetes.Clientset {
k8sClientOnce.Do(func() {
config, err := getKubeConfig()
config, err := Config()
if err != nil {
log.Fatalln(err)
@@ -62,7 +62,7 @@ func K8sClient() *kubernetes.Clientset {
return k8sClient
}
func getKubeConfig() (kubeConfig *rest.Config, err error) {
func Config() (kubeConfig *rest.Config, err error) {
if kubeConfigFile == "" {
if env := os.Getenv("KUBECONFIG"); env != "" {

View File

@@ -1,20 +1,3 @@
/*
Copyright 2019 The KubeSphere 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 ldap
import (

View File

@@ -1,20 +1,3 @@
/*
Copyright 2019 The KubeSphere 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 ldap
import (

View File

@@ -15,20 +15,18 @@
limitations under the License.
*/
package client
package ldap
import (
"flag"
"fmt"
"github.com/go-ldap/ldap"
ldapPool "kubesphere.io/kubesphere/pkg/client/ldap"
"os"
"log"
"sync"
)
var (
once sync.Once
pool ldapPool.Pool
pool Pool
ldapHost string
ManagerDN string
ManagerPassword string
@@ -44,11 +42,11 @@ func init() {
flag.StringVar(&GroupSearchBase, "ldap-group-search-base", "ou=Groups,dc=example,dc=org", "ldap group search base")
}
func LdapClient() ldapPool.Pool {
func ldapClientPool() Pool {
once.Do(func() {
var err error
pool, err = ldapPool.NewChannelPool(8, 96, "kubesphere", func(s string) (ldap.Client, error) {
pool, err = NewChannelPool(8, 96, "kubesphere", func(s string) (ldap.Client, error) {
conn, err := ldap.Dial("tcp", ldapHost)
if err != nil {
return nil, err
@@ -57,9 +55,25 @@ func LdapClient() ldapPool.Pool {
}, []uint16{ldap.LDAPResultTimeLimitExceeded, ldap.ErrorNetwork})
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
panic(err)
log.Fatalln(err)
}
})
return pool
}
func Client() (ldap.Client, error) {
conn, err := ldapClientPool().Get()
if err != nil {
return nil, err
}
err = conn.Bind(ManagerDN, ManagerPassword)
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}

View File

@@ -1,20 +1,3 @@
/*
Copyright 2019 The KubeSphere 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 ldap
import (

View File

@@ -16,12 +16,15 @@
*/
package client
package mysql
import (
"flag"
"log"
"os"
"os/signal"
"sync"
"syscall"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
@@ -37,7 +40,7 @@ func init() {
flag.StringVar(&dsn, "database-connection", "root@tcp(localhost:3306)/kubesphere?charset=utf8&parseTime=True", "data source name")
}
func DBClient() *gorm.DB {
func Client() *gorm.DB {
dbClientOnce.Do(func() {
var err error
dbClient, err = gorm.Open("mysql", dsn)
@@ -45,10 +48,12 @@ func DBClient() *gorm.DB {
if err != nil {
log.Fatalln(err)
}
if err := dbClient.DB().Ping(); err != nil {
log.Fatalln(err)
}
c := make(chan os.Signal, 0)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
dbClient.Close()
}()
})
return dbClient

View File

@@ -15,7 +15,7 @@
limitations under the License.
*/
package client
package prometheus
import (
"flag"

View File

@@ -15,7 +15,7 @@
limitations under the License.
*/
package client
package redis
import (
"flag"
@@ -39,7 +39,7 @@ func init() {
flag.IntVar(&redisDB, "redis-db", 0, "redis db")
}
func RedisClient() *redis.Client {
func Client() *redis.Client {
redisClientOnce.Do(func() {
redisClient = redis.NewClient(&redis.Options{

View File

@@ -134,7 +134,7 @@ func (c *NamespaceController) processNextWorkItem() bool {
return nil
}
if err := c.syncHandler(namespace); err != nil {
if err := c.reconcile(namespace); err != nil {
c.workqueue.AddRateLimited(namespace)
return fmt.Errorf("error syncing '%s': %s, requeuing", namespace, err.Error())
}
@@ -152,7 +152,7 @@ func (c *NamespaceController) processNextWorkItem() bool {
return true
}
func (c *NamespaceController) syncHandler(name string) error {
func (c *NamespaceController) reconcile(name string) error {
_, err := c.namespaceInformer.Lister().Get(name)
@@ -162,7 +162,7 @@ func (c *NamespaceController) syncHandler(name string) error {
}
// Handler update or create event
if err := c.checkRoles(name); err != nil {
if err := c.checkAndCreateRoles(name); err != nil {
return err
}
@@ -175,14 +175,19 @@ func (c *NamespaceController) handleObject(obj interface{}) {
}
}
func (c *NamespaceController) checkRoles(namespace string) error {
// Create default roles
func (c *NamespaceController) checkAndCreateRoles(namespace string) error {
for _, role := range defaultRoles {
_, err := c.roleInformer.Lister().Roles(namespace).Get(role.Name)
if errors.IsNotFound(err) {
r := role.DeepCopy()
r.Namespace = namespace
_, err := c.clientset.RbacV1().Roles(namespace).Create(r)
if err != nil && !errors.IsAlreadyExists(err) {
if err != nil {
if errors.IsNotFound(err) {
r := role.DeepCopy()
r.Namespace = namespace
_, err = c.clientset.RbacV1().Roles(namespace).Create(r)
if err != nil && !errors.IsAlreadyExists(err) {
return err
}
} else {
return err
}
}