utils

package
v0.0.0-...-8cd4dec Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2025 License: MIT Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StatusError   = 1 // 操作失败
	StatusSuccess = 0 // 操作成功
)

定义操作成功和失败的常量状态码

View Source
const QuotaName = "compute-quota"

Variables

View Source
var UpGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

升级器

Functions

func AesDecrypt

func AesDecrypt(encrypted []byte, key []byte) ([]byte, error)

AesDecrypt AES解密

func AesEncrypt

func AesEncrypt(data []byte, key []byte) ([]byte, error)

AesEncrypt AES加密

func ApiData

func ApiData(c *gin.Context, code int, data interface{}, message string)

ApiData 通用的返回函数,用于标准化API响应格式 参数: - c: gin 上下文 - code: 状态码 - data: 返回的数据 - message: 返回的消息

func ApplyLimitRange

func ApplyLimitRange(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string, cluster *model.K8sCluster) error

ApplyLimitRange 应用 LimitRange 到指定命名空间

func ApplyResourceQuota

func ApplyResourceQuota(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string, cluster *model.K8sCluster) error

ApplyResourceQuota 应用 ResourceQuota 到指定命名空间

func ApplyTerraform

func ApplyTerraform(ctx context.Context, tf *tfexec.Terraform) error

ApplyTerraform 执行 Terraform Apply 在指定 Terraform 实例

func BadRequest

func BadRequest(c *gin.Context, code int, data interface{}, message string)

BadRequest 参数错误的返回,使用HTTP 400状态码

func BadRequestError

func BadRequestError(c *gin.Context, message string)

BadRequestError 参数错误的失败返回

func BadRequestWithDetails

func BadRequestWithDetails(c *gin.Context, data interface{}, message string)

BadRequestWithDetails 带详细数据和消息的参数错误返回

func Base64Decode

func Base64Decode(encoded string) ([]byte, error)

Base64Decode 将 base64 编码的字符串转换为字节数组

func Base64Encode

func Base64Encode(data []byte) string

Base64Encode 将字节数组转换为 base64 编码的字符串

func BuildK8sContainers

func BuildK8sContainers(containers []corev1.Container) []model.K8sPodContainer

BuildK8sContainers 构建 K8sContainer 列表

func BuildK8sContainersWithPointer

func BuildK8sContainersWithPointer(k8sContainers []model.K8sPodContainer) []*model.K8sPodContainer

BuildK8sContainersWithPointer 转换普通切片为指针切片

func BuildK8sNode

func BuildK8sNode(ctx context.Context, id int, node corev1.Node, kubeClient *kubernetes.Clientset, metricsClient *metricsClient.Clientset) (*model.K8sNode, error)

func BuildK8sPods

func BuildK8sPods(pods *corev1.PodList) []*model.K8sPod

BuildK8sPods BuildK8sNodes 构建 K8sNode 列表

func BuildMatchers

func BuildMatchers(alertEvent *model.MonitorAlertEvent, l *zap.Logger, useName bool) ([]*labels.Matcher, error)

func CheckAlertsIpExists

func CheckAlertsIpExists(req *model.MonitorAlertManagerPool, rules []*model.MonitorAlertManagerPool) bool

func CheckPoolIpExists

func CheckPoolIpExists(pools []*model.MonitorScrapePool, req *model.MonitorScrapePool) error

func CloneMap

func CloneMap(original map[string]string) map[string]string

CloneMap 克隆一个字符串到字符串的映射

func ConvertToIntList

func ConvertToIntList(stringList []string) ([]int, error)

func DaysBetween

func DaysBetween(t1, t2 time.Time) int

DaysBetween 计算两个日期之间的天数

func DeepCopyScrapeConfig

func DeepCopyScrapeConfig(sc *pc.ScrapeConfig) *pc.ScrapeConfig

DeepCopyScrapeConfig 深度拷贝 ScrapeConfig

func DeleteWithId

func DeleteWithId(l *zap.Logger, funcName string, timeout int, url string, paramsMap map[string]string, headerMap map[string]string) ([]byte, error)

func DestroyTerraform

func DestroyTerraform(ctx context.Context, workDir string, terraformBin string) error

DestroyTerraform 执行 Terraform Destroy 在指定目录

func EnsureDir

func EnsureDir(dirPath string, logger *zap.Logger) error

EnsureDir 确保目录存在,不存在则创建

func EnsureNamespace

func EnsureNamespace(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) error

EnsureNamespace 确保指定的命名空间存在,如果不存在则创建

func Error

func Error(c *gin.Context)

Error 操作失败的返回

func ErrorWithDetails

func ErrorWithDetails(c *gin.Context, data interface{}, message string)

ErrorWithDetails 带详细数据和消息的操作失败返回

func ErrorWithMessage

func ErrorWithMessage(c *gin.Context, message string)

ErrorWithMessage 带消息的操作失败返回

func ExtractIPs

func ExtractIPs(state *struct {
	Outputs map[string]struct {
		Value       interface{} `json:"value"`
		Description string      `json:"description"`
	} `json:"outputs"`
}, logger *zap.Logger) (string, string, error)

ExtractIPs 从 Terraform 状态中提取公网和私网 IP

func Forbidden

func Forbidden(c *gin.Context, code int, data interface{}, message string)

Forbidden 无权限的返回,使用HTTP 403状态码

func ForbiddenError

func ForbiddenError(c *gin.Context, message string)

ForbiddenError 无权限的失败返回

func FormatMap

func FormatMap(m map[string]string) string

FormatMap 将 map[string]string 格式化为字符串,每个键值对占一行

func FromSliceTuMap

func FromSliceTuMap(kvs []string) map[string]string

func GenPromDuration

func GenPromDuration(seconds int) promModel.Duration

GenPromDuration 转换秒为Prometheus Duration

func GetDaemonSetResources

func GetDaemonSetResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetDaemonSetResources 获取 DaemonSet 资源

func GetDefaultValue

func GetDefaultValue(value interface{}) interface{}

GetDefaultValue 返回值的默认值(零值)

func GetDeploymentResources

func GetDeploymentResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetDeploymentResources 获取 Deployment 资源

func GetDynamicClient

func GetDynamicClient(ctx context.Context, id int, clusterDao admin.ClusterDAO, client client.K8sClient) (*dynamic.DynamicClient, error)

func GetInternalIP

func GetInternalIP(node corev1.Node) string

GetInternalIP 获取节点内部IP

func GetKubeAndMetricsClient

func GetKubeAndMetricsClient(id int, logger *zap.Logger, client client.K8sClient) (*kubernetes.Clientset, *metricsClient.Clientset, error)

func GetKubeClient

func GetKubeClient(clusterId int, client client.K8sClient, l *zap.Logger) (*kubernetes.Clientset, error)

GetKubeClient 获取 Kubernetes 客户端

func GetMax

func GetMax(value1, value2 interface{}) (interface{}, error)

GetMax 返回两个数值中的最大值,支持 int, float64 等常见类型

func GetMin

func GetMin(value1, value2 interface{}) (interface{}, error)

GetMin 返回两个数值中的最小值,支持 int, float64 等常见类型

func GetNodeAge

func GetNodeAge(node corev1.Node) string

GetNodeAge 计算节点存在时间

func GetNodeEvents

func GetNodeEvents(ctx context.Context, client *kubernetes.Clientset, nodeName string) ([]model.OneEvent, error)

GetNodeEvents 获取节点事件

func GetNodeLabels

func GetNodeLabels(node corev1.Node) []string

GetNodeLabels 获取节点标签

func GetNodeResource

func GetNodeResource(ctx context.Context, metricsCli *metricsClient.Clientset, nodeName string, pods *corev1.PodList, node *corev1.Node) ([]string, error)

GetNodeResource 获取节点资源信息

func GetNodeRoles

func GetNodeRoles(node corev1.Node) []string

GetNodeRoles 获取节点角色

func GetNodeStatus

func GetNodeStatus(node corev1.Node) string

GetNodeStatus 获取节点状态

func GetNodesByName

func GetNodesByName(ctx context.Context, client *kubernetes.Clientset, nodeName string) (*corev1.NodeList, error)

GetNodesByName 获取指定集群上的 Node 列表

func GetParamID

func GetParamID(ctx *gin.Context) (int, error)

GetParamID 从查询参数中解析 ID,并进行类型转换

func GetParamName

func GetParamName(ctx *gin.Context) (string, error)

GetParamName 从查询参数中解析 Name,并进行类型转换

func GetPodResources

func GetPodResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetPodResources 获取 Pod 资源

func GetPodsByNodeName

func GetPodsByNodeName(ctx context.Context, client *kubernetes.Clientset, nodeName string) (*corev1.PodList, error)

GetPodsByNodeName 获取指定节点上的 Pod 列表

func GetQueryID

func GetQueryID(ctx *gin.Context) (int, error)

GetQueryID 从query参数中解析 ID,并进行类型转换

func GetReplicaSetResources

func GetReplicaSetResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetReplicaSetResources 获取 ReplicaSet 资源

func GetResourceName

func GetResourceName(kind string) string

GetResourceName 根据 Kind 获取资源名称

func GetResourceString

func GetResourceString(node corev1.Node, resourceName string) string

GetResourceString 获取节点资源信息

func GetServiceResources

func GetServiceResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetServiceResources 获取 Service 资源

func GetStatefulSetResources

func GetStatefulSetResources(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string) ([]model.Resource, error)

GetStatefulSetResources 获取 StatefulSet 资源

func GetTaintsMapFromTaints

func GetTaintsMapFromTaints(taints []corev1.Taint) map[string]corev1.Taint

GetTaintsMapFromTaints 将 taints 转换为键为 "Key:Value:Effect" 的 map

func GetTerraformState

func GetTerraformState(ctx context.Context, tf *tfexec.Terraform, logger *zap.Logger) (*struct {
	Outputs map[string]struct {
		Value       interface{} `json:"value"`
		Description string      `json:"description"`
	} `json:"outputs"`
}, error)

GetTerraformState 获取并解析 Terraform 状态

func HandleList

func HandleList[T any](ctx context.Context, search *string, searchFunc func(ctx context.Context, name string) ([]*T, error), listFunc func(ctx context.Context) ([]*T, error)) ([]*T, error)

HandleList 处理搜索或获取所有记录

func HandleRequest

func HandleRequest(ctx *gin.Context, req interface{}, action func() (interface{}, error))

HandleRequest 用于统一处理请求绑定和响应

func InitAadGetKubeClient

func InitAadGetKubeClient(ctx context.Context, cluster *model.K8sCluster, logger *zap.Logger, client client.K8sClient) (*kubernetes.Clientset, error)

func InternalServerError

func InternalServerError(c *gin.Context, code int, data interface{}, message string)

InternalServerError 服务器内部错误的返回,使用HTTP 500状态码

func InternalServerErrorWithDetails

func InternalServerErrorWithDetails(c *gin.Context, data interface{}, message string)

InternalServerErrorWithDetails 带详细数据和消息的服务器内部错误返回

func IsNodeSchedulable

func IsNodeSchedulable(node corev1.Node) bool

IsNodeSchedulable 判断节点是否可调度

func IsSameDay

func IsSameDay(t1, t2 time.Time) bool

IsSameDay 判断两个日期是否为同一天

func IsType

func IsType(value1, value2 interface{}) bool

IsType 判断两个值是否是相同类型

func IsValidEmail

func IsValidEmail(email string) bool

IsValidEmail 简单检查一个字符串是否是有效的电子邮件格式

func MapToStringSlice

func MapToStringSlice(inputMap map[string]string) ([]string, error)

MapToStringSlice 将 map 转换为 []string,要求偶数个元素,key和值依次排列

func MergeTaints

func MergeTaints(existingTaints []corev1.Taint, newTaints []corev1.Taint) []corev1.Taint

MergeTaints 合并新的 taints,避免重复

func ParseConfigs

ParseConfigs 解析 Terraform 配置中的各部分

func ParseExternalLabels

func ParseExternalLabels(labelsList []string) []string

ParseExternalLabels 解析外部标签

func ParseTags

func ParseTags(tags []string) (map[promModel.LabelName]promModel.LabelValue, error)

ParseTags 将 ECS 的 Tags 切片解析为 Prometheus 的标签映射

func ParseURL

func ParseURL(u string) (*pcc.URL, error)

ParseURL 解析字符串为URL,返回错误而非 panic

func Ping

func Ping(ipAddr string) bool

Ping 检查指定的 IP 地址是否可达

func PostWithJson

func PostWithJson(ctx context.Context, client *http.Client, l *zap.Logger, url string, jsonStr string, params map[string]string, headers map[string]string) ([]byte, error)

PostWithJson 发送带有JSON字符串的POST请求

func PostWithJsonString

func PostWithJsonString(l *zap.Logger, funcName string, timeout int, url string, jsonStr string, paramsMap map[string]string, headerMap map[string]string) ([]byte, error)

PostWithJsonString 发送带 JSON 数据的 POST 请求

func PromqlExprCheck

func PromqlExprCheck(expr string) (bool, error)

func RemoveTaints

func RemoveTaints(existingTaints []corev1.Taint, taintsToDelete []corev1.Taint) []corev1.Taint

RemoveTaints 从现有的 taints 中删除指定的 taints

func RenderTerraformTemplate

func RenderTerraformTemplate(config model.TerraformConfig, workDir string, terraformTemplate string, key string, secret string,
	vpc model.VPCConfig, instance model.InstanceConfig, security model.SecurityConfig) error

RenderTerraformTemplate 渲染 Terraform 模板并写入指定目录的 main.tf 文件

func SendSilenceRequest

func SendSilenceRequest(ctx context.Context, l *zap.Logger, url string, data []byte) (string, error)

func SetupTerraform

func SetupTerraform(ctx context.Context, workDir string, terraformBin string) (*tfexec.Terraform, error)

SetupTerraform 初始化并计划 Terraform 在指定目录

func StringSliceToMap

func StringSliceToMap(inputSlice []string) (map[string]string, error)

StringSliceToMap 将 []string 转换为 map[string]string,要求输入长度为偶数,奇数索引为 key,偶数索引为 value

func Success

func Success(c *gin.Context)

Success 操作成功的返回

func SuccessWithData

func SuccessWithData(c *gin.Context, data interface{})

SuccessWithData 带数据的操作成功返回

func SuccessWithDetails

func SuccessWithDetails(c *gin.Context, data interface{}, message string)

SuccessWithDetails 带详细数据和消息的操作成功返回

func SuccessWithMessage

func SuccessWithMessage(c *gin.Context, message string)

SuccessWithMessage 带消息的操作成功返回

func ToLowerCase

func ToLowerCase(str string) string

ToLowerCase 将字符串转换为小写

func ToUpperCase

func ToUpperCase(str string) string

ToUpperCase 将字符串转换为大写

func TrimSpaces

func TrimSpaces(str string) string

TrimSpaces 去掉字符串的前后空格

func Unauthorized

func Unauthorized(c *gin.Context, code int, data interface{}, message string)

Unauthorized 未认证的返回,使用HTTP 401状态码

func UnauthorizedErrorWithDetails

func UnauthorizedErrorWithDetails(c *gin.Context, data interface{}, message string)

UnauthorizedErrorWithDetails 带详细数据和消息的未认证返回

Types

type ApiResponse

type ApiResponse struct {
	Code    int         `json:"code"`    // 状态码,表示业务逻辑的状态,而非HTTP状态码
	Data    interface{} `json:"data"`    // 响应数据
	Message string      `json:"message"` // 反馈信息
	Type    string      `json:"type"`    // 消息类型
}

ApiResponse 通用的API响应结构体

type Handler

type Handler interface {
	SetLoginToken(ctx *gin.Context, uid int) (string, string, error)
	SetJWTToken(ctx *gin.Context, uid int, ssid string) (string, error)
	ExtractToken(ctx *gin.Context) string
	CheckSession(ctx *gin.Context, ssid string) error
	ClearToken(ctx *gin.Context) error
	// contains filtered or unexported methods
}

func NewJWTHandler

func NewJWTHandler(c redis.Cmdable) Handler

type K8sBatchRequest

type K8sBatchRequest struct {
	Cluster string           `json:"cluster"`
	Items   []K8sRequestItem `json:"items"`
}

type K8sObjectRequest

type K8sObjectRequest struct {
	Cluster   string `json:"cluster"`
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
}

type K8sRequestItem

type K8sRequestItem struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
}

type KeyValuePair

type KeyValuePair struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type LabelOption

type LabelOption struct {
	Label    string         `json:"label"`
	Value    string         `json:"value"`
	Children []*LabelOption `json:"children"`
}

LabelOption 通用返回结构体,用于前后端交互的数据格式

type OperationData

type OperationData struct {
	Success bool   `json:"success"`
	Error   string `json:"error"`
}

type RefreshClaims

type RefreshClaims struct {
	jwt.RegisteredClaims
	Uid  int
	Ssid string
}

type SelectOption

type SelectOption struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

type SelectOptionInt

type SelectOptionInt struct {
	Label string `json:"label"`
	Value int    `json:"value"`
}

type SilenceResponse

type SilenceResponse struct {
	Status string `json:"status"`
	Data   struct {
		SilenceID string `json:"silence_id"`
	} `json:"data"`
}

type UserClaims

type UserClaims struct {
	jwt.RegisteredClaims
	Uid         int
	Ssid        string
	UserAgent   string
	ContentType string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL