Skip to content

Commit 5e023a9

Browse files
committed
启动时如果无法连接数据库,则尝试N分钟,防止因为数据库连接失败而异常退出
1 parent 8f10fff commit 5e023a9

1 file changed

Lines changed: 40 additions & 3 deletions

File tree

internal/nodes/api_node.go

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package nodes
33
import (
44
"crypto/tls"
55
"errors"
6+
"fmt"
67
"github.com/TeaOSLab/EdgeAPI/internal/configs"
78
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
89
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
@@ -43,8 +44,15 @@ func NewAPINode() *APINode {
4344
func (this *APINode) Start() {
4445
logs.Println("[API_NODE]start api node, pid: " + strconv.Itoa(os.Getpid()))
4546

47+
// 检查数据库连接
48+
err := this.checkDB()
49+
if err != nil {
50+
logs.Println("[API_NODE]" + err.Error())
51+
return
52+
}
53+
4654
// 本地Sock
47-
err := this.listenSock()
55+
err = this.listenSock()
4856
if err != nil {
4957
logs.Println("[API_NODE]" + err.Error())
5058
return
@@ -108,7 +116,7 @@ func (this *APINode) Start() {
108116
select {}
109117
}
110118

111-
// 实现守护进程
119+
// Daemon 实现守护进程
112120
func (this *APINode) Daemon() {
113121
path := os.TempDir() + "/edge-api.sock"
114122
isDebug := lists.ContainsString(os.Args, "debug")
@@ -153,7 +161,7 @@ func (this *APINode) Daemon() {
153161
}
154162
}
155163

156-
// 安装系统服务
164+
// InstallSystemService 安装系统服务
157165
func (this *APINode) InstallSystemService() error {
158166
shortName := teaconst.SystemdServiceName
159167

@@ -263,6 +271,35 @@ func (this *APINode) listenRPC(listener net.Listener, tlsConfig *tls.Config) err
263271
return nil
264272
}
265273

274+
// 检查数据库
275+
func (this *APINode) checkDB() error {
276+
logs.Println("checking database connection ...")
277+
278+
db, err := dbs.Default()
279+
if err != nil {
280+
return err
281+
}
282+
283+
maxTries := 600
284+
for i := 0; i <= maxTries; i++ {
285+
_, err := db.Exec("SELECT 1")
286+
if err != nil {
287+
if i == maxTries-1 {
288+
return err
289+
} else {
290+
if i%10 == 0 { // 这让提示不会太多
291+
logs.Println("[API_NODE]reconnecting to database (" + fmt.Sprintf("%.1f", float32(i * 100)/float32(maxTries+1)) + "%) ...")
292+
}
293+
time.Sleep(1 * time.Second)
294+
}
295+
} else {
296+
return nil
297+
}
298+
}
299+
300+
return nil
301+
}
302+
266303
// 自动升级
267304
func (this *APINode) autoUpgrade() error {
268305
if Tea.IsTesting() {

0 commit comments

Comments
 (0)