github.com/turingchain2020/turingchain@v1.1.21/blockchain/ntp.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package blockchain
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  	"sync/atomic"
    11  	"time"
    12  
    13  	"github.com/turingchain2020/turingchain/common"
    14  	"github.com/turingchain2020/turingchain/types"
    15  )
    16  
    17  const (
    18  	ntpChecks      = 6
    19  	driftThreshold = 10 * time.Second // Allowed clock drift before warning user
    20  )
    21  
    22  var (
    23  	ntpLog = chainlog.New("submodule", "ntp")
    24  )
    25  
    26  // checkClockDrift queries an NTP server for clock drifts and warns the user if
    27  // one large enough is detected.
    28  func (chain *BlockChain) checkClockDrift() {
    29  	realnow := common.GetRealTimeRetry(chain.client.GetConfig().GetModuleConfig().NtpHosts, 10)
    30  	if realnow.IsZero() {
    31  		chain.UpdateNtpClockSyncStatus(false)
    32  		ntpLog.Warn("checkClockDrift", "sntpDrift err", "get ntptime error")
    33  		return
    34  	}
    35  	now := types.Now()
    36  	drift := now.Sub(realnow)
    37  	if drift < -driftThreshold || drift > driftThreshold {
    38  		warning := fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift)
    39  		howtofix := fmt.Sprintf("Please enable network time synchronisation in system settings")
    40  		separator := strings.Repeat("-", len(warning))
    41  		ntpLog.Info(fmt.Sprint(separator))
    42  		ntpLog.Info(fmt.Sprint(warning))
    43  		ntpLog.Info(fmt.Sprint(howtofix))
    44  		ntpLog.Info(fmt.Sprint(separator))
    45  		atomic.AddInt32(&chain.failed, 1)
    46  		if atomic.LoadInt32(&chain.failed) == ntpChecks {
    47  			ntpLog.Info("System clock seems ERROR")
    48  			chain.UpdateNtpClockSyncStatus(false)
    49  		}
    50  	} else {
    51  		atomic.StoreInt32(&chain.failed, 0)
    52  		chain.UpdateNtpClockSyncStatus(true)
    53  		ntpLog.Info(fmt.Sprintf("Sanity NTP check reported %v drift, all ok", drift))
    54  	}
    55  }