修复数据库连接内存泄漏

1.0.2
zhangchenhao 2025-05-21 11:59:03 +08:00
parent d14f110ab9
commit aa8f0e2291
12 changed files with 43 additions and 59 deletions

View File

@ -24,7 +24,7 @@ func Sign(c *gin.Context) {
}
form.Username = strings.TrimSpace(form.Username)
form.Code = strings.TrimSpace(form.Code)
// 从数据库拿用户
s, err := public.NewSqlite("data/data.db", "")
if err != nil {
@ -32,7 +32,6 @@ func Sign(c *gin.Context) {
public.FailMsg(c, err.Error())
return
}
s.Connect()
defer s.Close()
s.TableName = "users"
res, err := s.Where("username=?", []interface{}{form.Username}).Select()
@ -41,10 +40,10 @@ func Sign(c *gin.Context) {
public.FailMsg(c, err.Error())
return
}
session := sessions.Default(c)
now := time.Now()
loginErrCount := session.Get("__loginErrCount")
loginErrEnd := session.Get("__loginErrEnd")
ErrCount := 0
@ -57,9 +56,9 @@ func Sign(c *gin.Context) {
if __loginErrEnd, ok := loginErrEnd.(time.Time); ok {
ErrEnd = __loginErrEnd
}
// fmt.Println(ErrCount, ErrEnd)
// 判断登录错误次数
switch {
case ErrCount >= 5:
@ -91,7 +90,7 @@ func Sign(c *gin.Context) {
}
}
}
// 判断用户是否存在
if len(res) == 0 {
session.Set("__loginErrCount", ErrCount+1)
@ -117,7 +116,7 @@ func Sign(c *gin.Context) {
keyMd5 := md5.Sum([]byte(passwd))
passwdMd5 := hex.EncodeToString(keyMd5[:])
// fmt.Println(passwdMd5)
if res[0]["password"] != passwdMd5 {
session.Set("__loginErrCount", ErrCount+1)
session.Set("__loginErrEnd", now)
@ -128,7 +127,7 @@ func Sign(c *gin.Context) {
public.FailMsg(c, "密码错误")
return
}
// session := sessions.Default(c)
session.Set("__loginErrCount", 0)
session.Delete("__loginErrEnd")
@ -145,7 +144,7 @@ func Sign(c *gin.Context) {
func GetCode(c *gin.Context) {
_, bs64, code, _ := public.GenerateCode()
session := sessions.Default(c)
session.Set("_verifyCode", code)
_ = session.Save()
public.SuccessData(c, bs64, 0)

View File

@ -12,7 +12,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "access"
return s, nil
}

View File

@ -9,7 +9,6 @@ func GetSqliteAT() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "access_type"
return s, nil
}

View File

@ -32,7 +32,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "_accounts"
return s, nil
}
@ -183,7 +182,6 @@ func Apply(cfg map[string]any, logger *public.Logger) (map[string]any, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "workflow_history"
defer s.Close()
// 查询 workflowId

View File

@ -13,7 +13,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "cert"
return s, nil
}
@ -26,7 +25,7 @@ func GetList(search string, p, limit int64) ([]map[string]any, int, error) {
return data, 0, err
}
defer s.Close()
var limits []int64
if p >= 0 && limit >= 0 {
limits = []int64{0, limit}
@ -35,7 +34,7 @@ func GetList(search string, p, limit int64) ([]map[string]any, int, error) {
limits[1] = p * limit
}
}
if search != "" {
count, err = s.Where("domains like ?", []interface{}{"%" + search + "%"}).Count()
data, err = s.Where("domains like ?", []interface{}{"%" + search + "%"}).Limit(limits).Order("create_time", "desc").Select()
@ -68,7 +67,6 @@ func AddCert(source, key, cert, issuer, issuerCert, domains, sha256, historyId,
if err != nil {
return err
}
s.Connect()
s.TableName = "workflow_history"
defer s.Close()
// 查询 workflowId
@ -80,7 +78,7 @@ func AddCert(source, key, cert, issuer, issuerCert, domains, sha256, historyId,
workflowId = wh[0]["workflow_id"].(string)
}
}
now := time.Now().Format("2006-01-02 15:04:05")
_, err = s.Insert(map[string]any{
"source": source,
@ -108,7 +106,7 @@ func SaveCert(source, key, cert, issuerCert, historyId string) (string, error) {
if err := public.ValidateSSLCertificate(cert, key); err != nil {
return "", err
}
certObj, err := public.ParseCertificate([]byte(cert))
if err != nil {
return "", fmt.Errorf("解析证书失败: %v", err)
@ -121,23 +119,23 @@ func SaveCert(source, key, cert, issuerCert, historyId string) (string, error) {
if d, _ := GetCert(sha256); d != nil {
return sha256, nil
}
domainSet := make(map[string]bool)
if certObj.Subject.CommonName != "" {
domainSet[certObj.Subject.CommonName] = true
}
for _, dns := range certObj.DNSNames {
domainSet[dns] = true
}
// 转成切片并拼接成逗号分隔的字符串
var domains []string
for domain := range domainSet {
domains = append(domains, domain)
}
domainList := strings.Join(domains, ",")
// 提取 CA 名称Issuer 的组织名)
caName := "UNKNOWN"
if len(certObj.Issuer.Organization) > 0 {
@ -149,7 +147,7 @@ func SaveCert(source, key, cert, issuerCert, historyId string) (string, error) {
startTime := certObj.NotBefore.Format("2006-01-02 15:04:05")
endTime := certObj.NotAfter.Format("2006-01-02 15:04:05")
endDay := fmt.Sprintf("%d", int(certObj.NotAfter.Sub(time.Now()).Hours()/24))
err = AddCert(source, key, cert, caName, issuerCert, domainList, sha256, historyId, startTime, endTime, endDay)
if err != nil {
return "", fmt.Errorf("保存证书失败: %v", err)
@ -171,7 +169,7 @@ func DelCert(id string) error {
return err
}
defer s.Close()
_, err = s.Where("id=?", []interface{}{id}).Delete()
if err != nil {
return err
@ -185,7 +183,7 @@ func GetCert(id string) (map[string]string, error) {
return nil, err
}
defer s.Close()
res, err := s.Where("id=? or sha256=?", []interface{}{id, id}).Select()
if err != nil {
return nil, err
@ -193,13 +191,13 @@ func GetCert(id string) (map[string]string, error) {
if len(res) == 0 {
return nil, fmt.Errorf("证书不存在")
}
data := map[string]string{
"domains": res[0]["domains"].(string),
"cert": res[0]["cert"].(string),
"key": res[0]["key"].(string),
}
return data, nil
}

View File

@ -12,7 +12,6 @@ func GetWorkflowCount() (map[string]any, error) {
if err != nil {
return nil, err
}
s.Connect()
defer s.Close()
workflow, err := s.Query(`select count(*) as count,
count(case when exec_type='auto' then 1 end ) as active,
@ -71,7 +70,6 @@ func GetSiteMonitorCount() (map[string]any, error) {
if err != nil {
return nil, err
}
s.Connect()
defer s.Close()
cert, err := s.Query(`select count(*) as count,
count(case when state='' then 1 end ) as exception
@ -126,7 +124,7 @@ func GetWorkflowHistory() ([]map[string]any, error) {
} else {
name = "未知"
}
result = append(result, map[string]any{
"name": name,
"state": state,

View File

@ -16,7 +16,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "report"
return s, nil
}

View File

@ -29,7 +29,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "site_monitor"
return s, nil
}

View File

@ -13,7 +13,6 @@ func GetSqlite() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "workflow"
return s, nil
}

View File

@ -13,7 +13,6 @@ func GetSqliteObjWH() (*public.Sqlite, error) {
if err != nil {
return nil, err
}
s.Connect()
s.TableName = "workflow_history"
return s, nil
}
@ -27,7 +26,7 @@ func GetListWH(id string, p, limit int64) ([]map[string]any, int, error) {
return data, 0, err
}
defer s.Close()
var limits []int64
if p >= 0 && limit >= 0 {
limits = []int64{0, limit}
@ -43,7 +42,7 @@ func GetListWH(id string, p, limit int64) ([]map[string]any, int, error) {
count, err = s.Where("workflow_id=?", []interface{}{id}).Count()
data, err = s.Where("workflow_id=?", []interface{}{id}).Limit(limits).Order("create_time", "desc").Select()
}
if err != nil {
return data, 0, err
}

View File

@ -28,9 +28,9 @@ func init() {
fmt.Fprintf(os.Stderr, "切换目录失败: %v\n", err)
os.Exit(1)
}
os.MkdirAll("data", os.ModePerm)
dbPath := "data/data.db"
_, _ = filepath.Abs(dbPath)
// fmt.Println("数据库路径:", absPath)
@ -167,7 +167,7 @@ func init() {
workflow_id TEXT not null
);
create table workflow_deploy
create table IF NOT EXISTS workflow_deploy
(
id TEXT,
workflow_id TEXT,
@ -187,15 +187,15 @@ func init() {
INSERT INTO access_type (name, type) VALUES ('ssh', 'host');
INSERT INTO access_type (name, type) VALUES ('btpanel', 'host');
INSERT INTO access_type (name, type) VALUES ('1panel', 'host');`)
uuidStr := public.GenerateUUID()
randomStr := public.RandomString(8)
port, err := public.GetFreePort()
if err != nil {
port = 20773
}
Isql := fmt.Sprintf(
`INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES ('log_path', 'logs/ALLinSSL.log', '2025-04-15 15:58', '2025-04-15 15:58', 1, null);
INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES ( 'workflow_log_path', 'logs/workflows/', '2025-04-15 15:58', '2025-04-15 15:58', 1, null);
@ -204,26 +204,26 @@ INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES
INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES ('session_key', '%s', '2025-04-15 15:58', '2025-04-15 15:58', 1, null);
INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES ('secure', '/%s', '2025-04-15 15:58', '2025-04-15 15:58', 1, null);
INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES ('port', '%d', '2025-04-15 15:58', '2025-04-15 15:58', 1, null);`, uuidStr, randomStr, port)
insertDefaultData(db, "settings", Isql)
InsertIfNotExists(db, "access_type", map[string]any{"name": "cloudflare", "type": "host"}, []string{"name", "type"}, []any{"cloudflare", "host"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "cloudflare", "type": "dns"}, []string{"name", "type"}, []any{"cloudflare", "dns"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "huaweicloud", "type": "host"}, []string{"name", "type"}, []any{"huaweicloud", "host"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "huaweicloud", "type": "dns"}, []string{"name", "type"}, []any{"huaweicloud", "dns"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "baidu", "type": "host"}, []string{"name", "type"}, []any{"baidu", "host"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "baidu", "type": "dns"}, []string{"name", "type"}, []any{"baidu", "dns"})
InsertIfNotExists(db, "access_type", map[string]any{"name": "btwaf", "type": "host"}, []string{"name", "type"}, []any{"btwaf", "host"})
// 雷池
InsertIfNotExists(db, "access_type", map[string]any{"name": "safeline", "type": "host"}, []string{"name", "type"}, []any{"safeline", "host"})
// 西部数码
InsertIfNotExists(db, "access_type", map[string]any{"name": "westcn", "type": "dns"}, []string{"name", "type"}, []any{"westcn", "dns"})
// 火山引擎
InsertIfNotExists(db, "access_type", map[string]any{"name": "volcengine", "type": "dns"}, []string{"name", "type"}, []any{"volcengine", "dns"})
err = sqlite_migrate.EnsureDatabaseWithTables(
"data/site_monitor.db",
"data/data.db",
@ -232,7 +232,7 @@ INSERT INTO settings (key, value, create_time, update_time, active, type) VALUES
if err != nil {
fmt.Println("错误:", err)
}
db1, err := sql.Open("sqlite", "data/site_monitor.db")
if err != nil {
// fmt.Println("创建数据库失败:", err)
@ -275,7 +275,7 @@ func insertDefaultData(db *sql.DB, table, insertSQL string) {
// fmt.Println("检查数据行数失败:", err)
return
}
// 如果表为空,则插入默认数据
if count == 0 {
// fmt.Println("表为空,插入默认数据...")
@ -309,7 +309,7 @@ func InsertIfNotExists(
whereArgs = append(whereArgs, val)
i++
}
// 2. 判断是否存在
query := fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM %s WHERE %s)", table, whereClause)
var exists bool
@ -320,7 +320,7 @@ func InsertIfNotExists(
if exists {
return nil // 已存在
}
// 3. 构建 INSERT 语句
columnList := ""
placeholderList := ""
@ -333,11 +333,11 @@ func InsertIfNotExists(
placeholderList += "?"
}
insertSQL := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", table, columnList, placeholderList)
_, err = db.Exec(insertSQL, insertValues...)
if err != nil {
return fmt.Errorf("insert failed: %w", err)
}
return nil
}

View File

@ -22,7 +22,6 @@ func GetSettingIgnoreError(key string) string {
if err != nil {
return ""
}
s.Connect()
defer s.Close()
s.TableName = "settings"
res, err := s.Where("key=?", []interface{}{key}).Select()
@ -44,7 +43,6 @@ func UpdateSetting(key, val string) error {
if err != nil {
return err
}
s.Connect()
defer s.Close()
s.TableName = "settings"
_, err = s.Where("key=?", []interface{}{key}).Update(map[string]any{"value": val})
@ -60,7 +58,6 @@ func GetSettingsFromType(typ string) ([]map[string]any, error) {
if err != nil {
return nil, err
}
s.Connect()
defer s.Close()
s.TableName = "settings"
res, err := s.Where("type=?", []interface{}{typ}).Select()