gitee.com/mysnapcore/mysnapd@v0.1.0/timeutil/synchronized.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2021 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package timeutil
    21  
    22  import (
    23  	"fmt"
    24  
    25  	"github.com/godbus/dbus"
    26  
    27  	"gitee.com/mysnapcore/mysnapd/dbusutil"
    28  )
    29  
    30  func isNoServiceOrUnknownPropertyDbusErr(err error) bool {
    31  	derr, ok := err.(dbus.Error)
    32  	if !ok {
    33  		return false
    34  	}
    35  	switch derr.Name {
    36  	case "org.freedesktop.DBus.Error.ServiceUnknown", "org.freedesktop.DBus.Error.UnknownProperty":
    37  		return true
    38  	}
    39  	return false
    40  }
    41  
    42  type NoTimedate1Error struct {
    43  	Err error
    44  }
    45  
    46  func (e NoTimedate1Error) Error() string {
    47  	return fmt.Sprintf("cannot find org.freedesktop.timedate1 dbus service: %v", e.Err)
    48  }
    49  
    50  // IsNTPSynchronized returns true if the time is syncronized according to
    51  // systemd-timedated.
    52  func IsNTPSynchronized() (bool, error) {
    53  	// shared connection, no need to close
    54  	conn, err := dbusutil.SystemBus()
    55  	if err != nil {
    56  		return false, NoTimedate1Error{err}
    57  	}
    58  
    59  	tdObj := conn.Object("org.freedesktop.timedate1", "/org/freedesktop/timedate1")
    60  	dbusV, err := tdObj.GetProperty("org.freedesktop.timedate1.NTPSynchronized")
    61  	if err != nil {
    62  		if isNoServiceOrUnknownPropertyDbusErr(err) {
    63  			return false, NoTimedate1Error{err}
    64  		}
    65  		return false, fmt.Errorf("cannot check for ntp sync: %v", err)
    66  	}
    67  	v, ok := dbusV.Value().(bool)
    68  	if !ok {
    69  		return false, fmt.Errorf("timedate1 returned invalid value for NTPSynchronized property: %s", dbusV)
    70  	}
    71  
    72  	return v, nil
    73  }