Sfoglia il codice sorgente

优化修改代码

niujiuru 2 mesi fa
parent
commit
b022e268de

+ 2 - 1
timesyncd.service/api_handlers.go

@@ -8,9 +8,10 @@ import (
 	"hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
 )
 
-func (p *program) getSysTimeStatus(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
+func (p *program) getTimeSyncStatus(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
 	result := map[string]string{
 		"time_synced": strconv.FormatBool(p.timeSyncOK.Load()),
+		"time_source": p.syncSource.Load().(string),
 		"system_time": time.Now().Format("2006-01-02 15:04:05"),
 	}
 

+ 12 - 8
timesyncd.service/main.go

@@ -32,6 +32,7 @@ type program struct {
 	core_server  *jsonrpc2.RPCServer
 	http_server  *http.Server
 	timeSyncOK   atomic.Bool
+	syncSource   atomic.Value
 	stopTimeSync chan struct{}
 }
 
@@ -64,7 +65,7 @@ func (p *program) Start(s service.Service) error {
 	_saveLogConf := servicelib.SaveLogConf
 	methods["basic.saveLogConf"] = _saveLogConf // 保存日志设置
 	//////////////////////////////////////////////////////////
-	methods["core.getSysTimeStatus"] = p.getSysTimeStatus
+	methods["core.getTimeSyncStatus"] = p.getTimeSyncStatus
 
 	err = p.core_server.RegisterMethods(methods)
 	if err != nil {
@@ -80,6 +81,7 @@ func (p *program) Start(s service.Service) error {
 	}
 
 	p.stopTimeSync = make(chan struct{})
+	p.syncSource.Store("")
 
 	go p.run()
 
@@ -131,16 +133,18 @@ func (p *program) syncSysTime() error {
 		return errors.New("network not available")
 	}
 
-	var err error
-	if !httpTime.IsZero() {
-		err = netmgrd.SetSystemTime(httpTime)
+	if !httpTime.IsZero() && netmgrd.SetSystemTime(httpTime) == nil {
+		p.syncSource.Store("http")
+		return nil
 	}
 
-	if httpTime.IsZero() || err != nil {
-		err = netmgrd.SyncNTPTime()
+	err := netmgrd.SyncNTPTime()
+	if err == nil {
+		p.syncSource.Store("ntp")
+		return nil
+	} else {
+		return err
 	}
-
-	return err
 }
 
 func (p *program) maintainSystemTime() {

+ 1 - 1
timesyncd.service/test.txt

@@ -16,4 +16,4 @@ curl -s -X POST http://127.0.0.1:7001/rpc -H "Content-Type: application/json" -d
 curl -s -X POST http://127.0.0.1:7001/rpc -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"basic.saveLogConf","params":{},"id":5}'
 
 // 获取系统时间同步状态
-curl -s -X POST http://127.0.0.1:7001/rpc -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"core.getSysTimeStatus","params":{},"id":6}'
+curl -s -X POST http://127.0.0.1:7001/rpc -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"core.getTimeSyncStatus","params":{},"id":6}'