strategy.go 11.2 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4 5 6 7
package console_mysql

import (
	"fmt"
	"strings"
	"time"

黄孟柱 已提交
8 9 10
	database2 "github.com/eolinker/goku-api-gateway/common/database"
	entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
	"github.com/eolinker/goku-api-gateway/utils"
E
eoLinker API Management 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
)

// 新增策略组
func AddStrategy(strategyName string, groupID int) (bool, string, error) {
	db := database2.GetConnection()
	now := time.Now().Format("2006-01-02 15:04:05")
	// 随机生成字符串
	sqlCode := "SELECT strategyID FROM goku_gateway_strategy WHERE strategyID = ?"
	var strategyID string
	for i := 0; i < 5; i++ {
		randomStr := utils.GetRandomString(6)
		err := db.QueryRow(sqlCode, randomStr).Scan(&strategyID)
		if err == nil {
			continue
		}
		strategyID = randomStr
		break
	}
	if strategyID == "" {
		return false, "[ERROR]Empty strategy id !", nil
	}
	stmt, err := db.Prepare(`INSERT INTO goku_gateway_strategy (strategyID,strategyName,updateTime,createTime,groupID) VALUES (?,?,?,?,?);`)

	if err != nil {
		return false, "[ERROR]Illegal SQL statement!", err
	}
	defer stmt.Close()
	_, err = stmt.Exec(strategyID, strategyName, now, now, groupID)
	if err != nil {
		return false, "[ERROR]Failed to insert data!", err
	} else {
		return true, strategyID, nil
	}
}

// 修改策略组信息
func EditStrategy(strategyID, strategyName string, groupID int) (bool, string, error) {
	db := database2.GetConnection()
	now := time.Now().Format("2006-01-02 15:04:05")
	stmt, err := db.Prepare(`UPDATE goku_gateway_strategy SET strategyName = ?,groupID = ?,updateTime = ? WHERE strategyID = ?;`)
	if err != nil {
		return false, "[ERROR]Illegal SQL statement!", err
	}
	defer stmt.Close()
	_, err = stmt.Exec(strategyName, groupID, now, strategyID)
	if err != nil {
		return false, "[ERROR]Failed to update data!", err
	} else {
		return true, strategyID, nil
	}
}

// 删除策略组
func DeleteStrategy(strategyID string) (bool, string, error) {
	db := database2.GetConnection()
	Tx, _ := db.Begin()
	_, err := Tx.Exec(`DELETE FROM goku_gateway_strategy WHERE strategyID = ?;`, strategyID)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Failed to delete data!", err
	}
	// 删除绑定的接口
	sql := "DELETE FROM goku_conn_strategy_api WHERE strategyID = ?;"
	_, err = Tx.Exec(sql, strategyID)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	// 删除策略组插件
	sql = "DELETE FROM goku_conn_plugin_strategy WHERE strategyID = ?;"
	_, err = Tx.Exec(sql, strategyID)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	// 删除接口插件
	sql = "DELETE FROM goku_conn_plugin_api WHERE strategyID = ?;"
	_, err = Tx.Exec(sql, strategyID)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	Tx.Commit()
	return true, "", nil
}

// GetStrategyList 获取策略组列表
func GetStrategyList(groupID int, keyword string, condition int) (bool, []*entity.Strategy, error) {
	db := database2.GetConnection()

	rule := make([]string, 0, 2)

	rule = append(rule, "A.strategyType != 1")
	if groupID > -1 {
		groupRule := fmt.Sprintf("A.groupID = %d", groupID)
		rule = append(rule, groupRule)
	}
	if keyword != "" {
		searchRule := "(A.strategyID LIKE '%" + keyword + "%' OR A.strategyName LIKE '%" + keyword + "%')"
		rule = append(rule, searchRule)
	}
	if condition > 0 {
		filterRule := fmt.Sprintf("A.enableStatus = %d", condition-1)
		rule = append(rule, filterRule)
	}
	ruleStr := ""
	if len(rule) > 0 {
		ruleStr += "WHERE " + strings.Join(rule, " AND ")
	}
	sql := fmt.Sprintf("SELECT A.strategyID,A.strategyName,IFNULL(A.updateTime,''),IFNULL(A.createTime,''),A.enableStatus,A.groupID,IFNULL(B.groupName,'未分组') FROM goku_gateway_strategy A LEFT JOIN goku_gateway_strategy_group B ON A.groupID = B.groupID %s ORDER BY A.updateTime DESC;", ruleStr)
	rows, err := db.Query(sql)
	if err != nil {
		return false, nil, err
	}
	//延时关闭Rows
	defer rows.Close()
	//获取记录列
	strategyList := make([]*entity.Strategy, 0)
	for rows.Next() {
		var strategy entity.Strategy
		err = rows.Scan(&strategy.StrategyID, &strategy.StrategyName, &strategy.UpdateTime, &strategy.CreateTime, &strategy.EnableStatus, &strategy.GroupID, &strategy.GroupName)
		if err != nil {
			return false, nil, err
		}
		strategyList = append(strategyList, &strategy)
	}
	return true, strategyList, nil
}

// GetOpenStrategy 获取策略组列表
func GetOpenStrategy() (bool, *entity.Strategy, error) {
	var openStrategy entity.Strategy
	db := database2.GetConnection()
	sql := `SELECT strategyID,strategyName,IFNULL(updateTime,""),IFNULL(createTime,""),enableStatus,strategyType FROM goku_gateway_strategy WHERE strategyType = 1 ORDER BY updateTime DESC;`
	err := db.QueryRow(sql).Scan(&openStrategy.StrategyID, &openStrategy.StrategyName, &openStrategy.UpdateTime, &openStrategy.CreateTime, &openStrategy.EnableStatus, &openStrategy.StrategyType)
	if err != nil {
		return false, nil, err
	}
	openStrategy.GroupName = "开放分组"
	return true, &openStrategy, nil
}

// 获取策略组信息
func GetStrategyInfo(strategyID string) (bool, *entity.Strategy, error) {
	db := database2.GetConnection()
	sql := `SELECT strategyID,strategyName,IFNULL(updateTime,''),strategyType,enableStatus FROM goku_gateway_strategy WHERE strategyID = ?;`
	strategy := new(entity.Strategy)
	err := db.QueryRow(sql, strategyID).Scan(&strategy.StrategyID, &strategy.StrategyName, &strategy.UpdateTime, &strategy.StrategyType, &strategy.EnableStatus)
	if err != nil {
		return false, nil, err
	} else {
		return true, strategy, err
	}
}

// 检查策略组ID是否存在
func CheckStrategyIsExist(strategyID string) (bool, error) {
	db := database2.GetConnection()
	sql := "SELECT strategyID FROM goku_gateway_strategy WHERE strategyID = ?;"
	var id string
	err := db.QueryRow(sql, strategyID).Scan(&id)
	if err != nil {
		return false, err
	} else {
		return true, err
	}
}

// 批量修改策略组分组
func BatchEditStrategyGroup(strategyIDList string, groupID int) (bool, string, error) {
	db := database2.GetConnection()
	now := time.Now().Format("2006-01-02 15:04:05")
	Tx, _ := db.Begin()
	strategy := strings.Split(strategyIDList, ",")
	code := make([]string, 0, len(strategy))
	s := make([]interface{}, 0, len(strategy)+2)
	s = append(s, groupID, now)
	for i := 0; i < len(strategy); i++ {
		code = append(code, "?")
		s = append(s, strategy[i])
	}
	sql := "UPDATE goku_gateway_strategy SET groupID = ?,updateTime = ? WHERE strategyID IN (" + strings.Join(code, ",") + ");"
	_, err := Tx.Exec(sql, s...)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}
	Tx.Commit()
	return true, "", nil
}

// 批量修改策略组
func BatchDeleteStrategy(strategyIDList string) (bool, string, error) {
	db := database2.GetConnection()
	Tx, _ := db.Begin()
	strategy := strings.Split(strategyIDList, ",")
	code := ""
	s := make([]interface{}, 0)
	for i := 0; i < len(strategy); i++ {
		code += "?"
		if i < len(strategy)-1 {
			code += ","
		}
		s = append(s, strategy[i])
	}
	// 删除绑定的接口
	sql := "DELETE FROM goku_conn_strategy_api WHERE strategyID IN (" + code + ");"
	_, err := Tx.Exec(sql, s...)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	sql = "DELETE FROM goku_gateway_strategy WHERE strategyID IN (" + code + ");"
	_, err = Tx.Exec(sql, s...)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}
	// 删除策略组插件
	sql = "DELETE FROM goku_conn_plugin_strategy WHERE strategyID IN (" + code + ");"
	_, err = Tx.Exec(sql, s...)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	// 删除接口插件
	sql = "DELETE FROM goku_conn_plugin_api WHERE strategyID IN (" + code + ");"
	_, err = Tx.Exec(sql, s...)
	if err != nil {
		Tx.Rollback()
		return false, "[ERROR]Fail to excute SQL statement!", err
	}

	Tx.Commit()
	return true, "", nil
}

func CheckIsOpenStrategy(strategyID string) bool {
	db := database2.GetConnection()
	var strategyType int
	sql := "SELECT strategyType FROM goku_gateway_strategy WHERE strategyID = ?;"
	err := db.QueryRow(sql, strategyID).Scan(&strategyType)
	if err != nil {
		return false
	}
	if strategyType == 1 {
		return true
	} else {
		return false
	}
}

// 更新策略启动状态
func BatchUpdateStrategyEnableStatus(strategyIDList string, enableStatus int) (bool, string, error) {
	db := database2.GetConnection()
	now := time.Now().Format("2006-01-02 15:04:05")
	strategy := strings.Split(strategyIDList, ",")
	code := ""
	s := make([]interface{}, 0)
	s = append(s, enableStatus)
	s = append(s, now)
	for i := 0; i < len(strategy); i++ {
		code += "?"
		if i < len(strategy)-1 {
			code += ","
		}
		s = append(s, strategy[i])
	}
	sql := "UPDATE goku_gateway_strategy SET enableStatus = ?,updateTime = ? WHERE strategyID IN (" + code + ");"
	result, err := db.Exec(sql, s...)
	if err != nil {
		return false, "[ERROR]Fail to excute SQL statement!", err
	}
	affectRow, err := result.RowsAffected()
	if err != nil || affectRow == 0 {
		return false, "[ERROR]Fail to update data!", err
	}
	return true, "", nil
}

// GetBalanceListInStrategy 获取在策略中的负载列表
func GetBalanceListInStrategy(strategyID string, balanceType int) (bool, []string, error) {
	db := database2.GetConnection()

	sql := "SELECT DISTINCT(IFNULL(A.balanceName,'')) FROM goku_gateway_api A INNER JOIN goku_conn_strategy_api B ON A.apiID = B.apiID WHERE B.strategyID = ?;"
	if balanceType == 1 {
		sql = "SELECT DISTINCT(IFNULL(target,'')) FROM goku_conn_strategy_api WHERE strategyID = ?;"
	}
	rows, err := db.Query(sql, strategyID)
	if err != nil {
		return false, nil, err
	}
	//延时关闭Rows
	defer rows.Close()
	//获取记录列
	balanceNameList := make([]string, 0, 10)
	for rows.Next() {
		var balanceName string
		err = rows.Scan(&balanceName)
		if err != nil {
			return false, nil, err
		}
		if balanceName == "" {
			continue
		}
		balanceNameList = append(balanceNameList, balanceName)
	}
	return true, balanceNameList, nil
}

// CopyStrategy 复制策略
func CopyStrategy(strategyID string, newStrategyID string, userID int) (string, error) {
	db := database2.GetConnection()
	now := time.Now().Format("2006-01-02 15:04:05")
	sql := "INSERT INTO goku_conn_strategy_api (strategyID,apiID,apiMonitorStatus,strategyMonitorStatus,target,updateTime) SELECT ?,apiID,apiMonitorStatus,strategyMonitorStatus,target,? FROM goku_conn_strategy_api WHERE strategyID = ?"
	_, err := db.Exec(sql, newStrategyID, now, strategyID)
	if err != nil {
		return "", err
	}
	sql = "INSERT INTO goku_conn_plugin_strategy (strategyID,pluginName,pluginConfig,pluginInfo,createTime,updateTime,pluginStatus,updateTag,updaterID) SELECT ?,pluginName,pluginConfig,pluginInfo,?,?,pluginStatus,updateTag,? FROM goku_conn_plugin_strategy WHERE strategyID = ?"
	_, err = db.Exec(sql, newStrategyID, now, now, userID, strategyID)
	if err != nil {
		return "", err
	}

	sql = "INSERT INTO goku_conn_plugin_api (strategyID,apiID,pluginName,pluginConfig,pluginInfo,createTime,updateTime,pluginStatus,updateTag,updaterID) SELECT ?,apiID,pluginName,pluginConfig,pluginInfo,?,?,pluginStatus,updateTag,? FROM goku_conn_plugin_api WHERE strategyID = ?"
	_, err = db.Exec(sql, newStrategyID, now, now, userID, strategyID)
	if err != nil {
		return "", err
	}
	return newStrategyID, nil
}