Skip to content

Commit

Permalink
✨ feat: support model provider for k8s resource (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
lwnmengjing committed May 24, 2024
1 parent 7d38636 commit 4b32331
Show file tree
Hide file tree
Showing 20 changed files with 1,280 additions and 53 deletions.
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ run:
skip-files:
- ".*\\_test\\.go$"
- ".*\\_string\\.go$"
- "pkg/response/actions/k8s/control.go"
- "pkg/response/actions/k8s/search.go"
linters-settings:
lll:
line-length: 170
Expand Down
99 changes: 99 additions & 0 deletions pkg/config/k8s/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package k8s

import (
"log/slog"
"os"
"path/filepath"
"strings"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/util/homedir"
)

/*
* @Author: lwnmengjing<lwnmengjing@qq.com>
* @Date: 2024/5/23 18:01:31
* @Last Modified by: lwnmengjing<lwnmengjing@qq.com>
* @Last Modified time: 2024/5/23 18:01:31
*/

var ClientSet *kubernetes.Clientset

type Config struct {
KubeConfig string `yaml:"kubeConfig" json:"kubeConfig"`
KubeConfigPath string `yaml:"kubeConfigPath" json:"kubeConfigPath"`
*ClusterConfig `yaml:",inline" json:",inline"`
}

type ClusterConfig struct {
BearerToken string `yaml:"bearerToken" json:"bearerToken"`
TLSClientConfig TLSClientConfig `yaml:"tlsClientConfig" json:"tlsClientConfig"`
}

type TLSClientConfig struct {
Insecure bool `yaml:"insecure" json:"insecure"`
CertData string `yaml:"certData" json:"certData"`
CertPath string `yaml:"certPath" json:"certPath"`
KeyData string `yaml:"keyData" json:"keyData"`
KeyPath string `yaml:"keyPath" json:"keyPath"`
CaData string `yaml:"caData" json:"caData"`
CaPath string `yaml:"caPath" json:"caPath"`
}

func (e *Config) Init() {
var config *rest.Config
var err error
// 获取集群内部的配置
if Stage() != "local" && e.KubeConfig == "" && e.KubeConfigPath == "" {
config, err = rest.InClusterConfig()
if err != nil {
slog.Error("Failed to get in-cluster sectConfig", "err", err)
os.Exit(-1)
}
} else {
var apiConfig *clientcmdapi.Config
if e.KubeConfig != "" {
apiConfig, err = clientcmd.Load([]byte(e.KubeConfig))
if err != nil {
slog.Error("Failed to load kubeconfig", "err", err)
os.Exit(-1)
}
} else {
if e.KubeConfigPath == "" {
e.KubeConfigPath = filepath.Join(homedir.HomeDir(), ".kube", "config")
}
apiConfig, err = clientcmd.LoadFromFile(e.KubeConfigPath)
if err != nil {
slog.Error("Failed to load kubeconfig", "err", err)
os.Exit(-1)
}
}
// 创建一个 rest.Config 对象
config, err = clientcmd.NewDefaultClientConfig(*apiConfig, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
slog.Error("Failed to create restConfig", "err", err)
os.Exit(-1)
}
}
// 创建 Kubernetes 客户端
ClientSet, err = kubernetes.NewForConfig(config)
if err != nil {
slog.Error("Failed to create clientset", "err", err)
os.Exit(-1)
}
}

// Stage get current stage
func Stage() string {
stage := os.Getenv("STAGE")
if stage == "" {
stage = os.Getenv("stage")
}
if stage == "" {
stage = "local"
}
return strings.ToLower(stage)
}
35 changes: 0 additions & 35 deletions pkg/response/actions/gorm/base.go

This file was deleted.

2 changes: 1 addition & 1 deletion pkg/response/actions/gorm/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (e *Get) get(c *gin.Context, key string) {

if e.opts.BeforeGet != nil {
if err := e.opts.BeforeGet(c, query, m); err != nil {
api.AddError(err).Log.Error("BeforeGet error", "error", err)
api.AddError(err).Log.Error("BeforeGet error")
api.Err(http.StatusInternalServerError)
return
}
Expand Down
7 changes: 6 additions & 1 deletion pkg/response/actions/gorm/options.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package gorm

import (
"context"

"github.com/gin-gonic/gin"
"github.com/mss-boot-io/mss-boot/pkg/response"
"gorm.io/gorm"
"gorm.io/gorm/schema"

"github.com/mss-boot-io/mss-boot/pkg/response"
)

/*
Expand All @@ -14,6 +17,8 @@ import (
* @Last Modified time: 2024/4/20 22:46:00
*/

var CleanCacheFromTag func(ctx context.Context, tag string) error

type ActionHook func(ctx *gin.Context, db *gorm.DB, m schema.Tabler) error

type Option func(*Options)
Expand Down
25 changes: 21 additions & 4 deletions pkg/response/actions/gorm/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (e *Search) search(c *gin.Context) {

if e.opts.BeforeSearch != nil {
if err := e.opts.BeforeSearch(c, db, m); err != nil {
api.AddError(err).Log.Error("BeforeSearch error", "error", err)
api.AddError(err).Log.Error("BeforeSearch error")
api.Err(http.StatusInternalServerError)
return
}
Expand All @@ -90,6 +90,11 @@ func (e *Search) search(c *gin.Context) {
scopes = append(scopes, e.opts.Scope(c, m))
}
query := db.Model(m).Scopes(scopes...)
//if err := query.Limit(-1).Offset(-1).Count(&count).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
// api.AddError(err).Log.ErrorContext(c, "Search error", "error", err)
// api.Err(http.StatusInternalServerError)
// return
//}

if e.opts.TreeField != "" && e.opts.Depth > 0 {
treeFields := make([]string, 0, e.opts.Depth)
Expand All @@ -98,13 +103,25 @@ func (e *Search) search(c *gin.Context) {
}
query = query.Preload(strings.Join(treeFields, "."))
}
list := pkg.DeepSlice(m)
err := query.Find(&list).Error

rows, err := query.Rows()
if err != nil {
api.AddError(err).Log.ErrorContext(c, "Search error", "error", err)
api.Err(http.StatusInternalServerError)
return
}
defer rows.Close()
items := make([]any, 0, req.GetPageSize())
for rows.Next() {
m = pkg.TablerDeepCopy(e.opts.Model)
err = db.ScanRows(rows, m)
if err != nil {
api.AddError(err).Log.ErrorContext(c, "search error", "error", err)
api.Err(http.StatusInternalServerError)
return
}
items = append(items, m)
}
err = query.Limit(-1).Offset(-1).Count(&count).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
api.AddError(err).Log.ErrorContext(c, "search error", "error", err)
Expand All @@ -118,6 +135,6 @@ func (e *Search) search(c *gin.Context) {
return
}
}
api.PageOK(list, count, req.GetPage(), req.GetPageSize(), "search success")
api.PageOK(items, count, req.GetPage(), req.GetPageSize(), "search success")
c.Next()
}
Loading

0 comments on commit 4b32331

Please sign in to comment.