Skip to content

Commit

Permalink
feat: implement darwin boottime without using cgo
Browse files Browse the repository at this point in the history
Use sysctl from the stdlib and add a test to make sure the
implementation works with CGO_ENABLED=0
  • Loading branch information
kruskall committed Sep 8, 2022
1 parent 438814e commit 44828a7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
11 changes: 6 additions & 5 deletions providers/darwin/boottime_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,23 @@
// specific language governing permissions and limitations
// under the License.

//go:build (amd64 && cgo) || (arm64 && cgo)
// +build amd64,cgo arm64,cgo
//go:build amd64 || arm64
// +build amd64 arm64

package darwin

import (
"fmt"
"syscall"
"time"

"golang.org/x/sys/unix"
)

const kernBoottimeMIB = "kern.boottime"

func BootTime() (time.Time, error) {
var tv syscall.Timeval
if err := sysctlByName(kernBoottimeMIB, &tv); err != nil {
tv, err := unix.SysctlTimeval(kernBoottimeMIB)
if err != nil {
return time.Time{}, fmt.Errorf("failed to get host uptime: %w", err)
}

Expand Down
32 changes: 32 additions & 0 deletions providers/darwin/boottime_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package darwin

import (
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestBoottime(t *testing.T) {
bt, err := BootTime()
assert.NoError(t, err)

t.Logf(bt.Format(time.RFC1123))
}

0 comments on commit 44828a7

Please sign in to comment.