Skip to content

Commit a90fad3

Browse files
committed
pkg/machine: rework getLocalTimeZone on linux
Get the timezone off the localtime symlink like systemd does it. It is more efficient then fork/exec another command for it that may or may not exits and the /etc/timezone files doesn't exist on most distros so that is not a great fallback. Signed-off-by: Paul Holzinger <[email protected]>
1 parent 193d7b8 commit a90fad3

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed
Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
package ignition
22

33
import (
4+
"errors"
45
"os"
5-
"os/exec"
6+
"path/filepath"
67
"strings"
7-
8-
"github.com/sirupsen/logrus"
98
)
109

1110
func getLocalTimeZone() (string, error) {
12-
trimTzFunc := func(s string) string {
13-
return strings.TrimPrefix(strings.TrimSuffix(s, "\n"), "Timezone=")
11+
path, err := filepath.EvalSymlinks("/etc/localtime")
12+
if err != nil {
13+
// of the path does not exist, ignore it as the code default to UTC then
14+
if errors.Is(err, os.ErrNotExist) {
15+
return "", nil
16+
}
17+
return "", err
1418
}
1519

16-
// perform a variety of ways to see if we can determine the tz
17-
output, err := exec.Command("timedatectl", "show", "--property=Timezone").Output()
18-
if err == nil {
19-
return trimTzFunc(string(output)), nil
20-
}
21-
logrus.Debugf("Timedatectl show --property=Timezone failed: %s", err)
22-
output, err = os.ReadFile("/etc/timezone")
23-
if err == nil {
24-
return trimTzFunc(string(output)), nil
20+
// Allow using TZDIR per:
21+
// https://sourceware.org/git/?p=glibc.git;a=blob;f=time/tzfile.c;h=8a923d0cccc927a106dc3e3c641be310893bab4e;hb=HEAD#l149
22+
zoneinfo := os.Getenv("TZDIR")
23+
if zoneinfo == "" {
24+
// default zoneinfo location
25+
zoneinfo = "/usr/share/zoneinfo"
2526
}
26-
logrus.Debugf("unable to read /etc/timezone, falling back to empty timezone: %s", err)
27-
// if we cannot determine the tz, return empty string
28-
return "", nil
27+
// Trim of the TZDIR part to extract the actual timezone name
28+
return strings.TrimPrefix(path, filepath.Clean(zoneinfo)+"/"), nil
2929
}

0 commit comments

Comments
 (0)