|
| 1 | +// Copyright 2024 CoreOS, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package daemon |
| 16 | + |
| 17 | +import ( |
| 18 | + "errors" |
| 19 | + "strconv" |
| 20 | + "strings" |
| 21 | + "testing" |
| 22 | + "time" |
| 23 | + |
| 24 | + "golang.org/x/sys/unix" |
| 25 | +) |
| 26 | + |
| 27 | +// TestUsec checks that SdNotifyMonotonicUsec is probably not returning complete garbage. |
| 28 | +func TestUsec(t *testing.T) { |
| 29 | + var resolution unix.Timespec |
| 30 | + if err := unix.ClockGetres(unix.CLOCK_MONOTONIC, &resolution); err != nil { |
| 31 | + if errors.Is(err, unix.EINVAL) { |
| 32 | + t.Log("CLOCK_MONOTONIC is not supported on this system") |
| 33 | + if got := SdNotifyMonotonicUsec(); got != "" { |
| 34 | + t.Errorf("SdNotifyMonotonicUsec() = %q; want empty string", got) |
| 35 | + } |
| 36 | + return |
| 37 | + } |
| 38 | + t.Fatalf("ClockGetres(CLOCK_MONOTONIC) failed: %v", err) |
| 39 | + } |
| 40 | + |
| 41 | + now := func() uint64 { |
| 42 | + got := SdNotifyMonotonicUsec() |
| 43 | + t.Logf("SdNotifyMonotonicUsec() = %q", got) |
| 44 | + if got == "" { |
| 45 | + t.Fatal("SdNotifyMonotonicUsec() returned empty string on system which supports CLOCK_MONOTONIC") |
| 46 | + } |
| 47 | + tag, val, ok := strings.Cut(got, "=") |
| 48 | + if !ok { |
| 49 | + t.Fatal("string is not a well-formed variable assignment") |
| 50 | + } |
| 51 | + if tag != "MONOTONIC_USEC" { |
| 52 | + t.Errorf("expected tag MONOTONIC_USEC, got %q", tag) |
| 53 | + } |
| 54 | + ts, err := strconv.ParseUint(val, 10, 64) |
| 55 | + if err != nil { |
| 56 | + t.Fatalf("value %q is not well-formed: %v", val, err) |
| 57 | + } |
| 58 | + if ts == 0 { |
| 59 | + // CLOCK_MONOTONIC is defined on Linux as the number of seconds |
| 60 | + // since boot, per clock_gettime(2). A timestamp of zero is |
| 61 | + // almost certainly bogus. |
| 62 | + t.Fatal("timestamp is zero") |
| 63 | + } |
| 64 | + return ts |
| 65 | + } |
| 66 | + |
| 67 | + start := now() |
| 68 | + time.Sleep(time.Duration(resolution.Nano()) * 3) |
| 69 | + ts := now() |
| 70 | + if ts < start { |
| 71 | + t.Errorf("timestamp went backwards: %d < %d", ts, start) |
| 72 | + } else if ts == start { |
| 73 | + t.Errorf("timestamp did not advance: %d == %d", ts, start) |
| 74 | + } |
| 75 | +} |
0 commit comments