File: hostos.go

package info (click to toggle)
golang-gvisor-gvisor 0.0~20240729.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,276 kB
  • sloc: asm: 3,361; ansic: 1,197; cpp: 348; makefile: 92; python: 89; sh: 83
file content (87 lines) | stat: -rw-r--r-- 2,294 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2022 The gVisor Authors.
//
// Licensed 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 hostos contains utility functions for getting information about the host OS.
package hostos

import (
	"fmt"
	"regexp"
	"strings"
	"sync"

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

// Version represents a semantic version of the form "%d.%d[.%d]".
type Version struct {
	version string
}

// AtLeast returns whether vr is at least version major.minor.
func (vr Version) AtLeast(major, minor int) bool {
	return semver.Compare(vr.version, fmt.Sprintf("v%d.%d", major, minor)) >= 0
}

// LessThan returns whether vr is less than version major.minor.
func (vr Version) LessThan(major, minor int) bool {
	return !vr.AtLeast(major, minor)
}

// String implements fmt.Stringer.
func (vr Version) String() string {
	if vr.version == "" {
		return "unknown"
	}
	// Omit the "v" prefix required by semver.
	return vr.version[1:]
}

// These values are effectively local to KernelVersion, but kept here so as to
// work with sync.Once.
var (
	semVersion Version
	unameErr   error
	once       sync.Once
)

// KernelVersion returns the version of the kernel using uname().
func KernelVersion() (Version, error) {
	once.Do(func() {
		var utsname unix.Utsname
		if err := unix.Uname(&utsname); err != nil {
			unameErr = err
			return
		}

		var sb strings.Builder
		for _, b := range utsname.Release {
			if b == 0 {
				break
			}
			sb.WriteByte(byte(b))
		}

		versionRegexp := regexp.MustCompile(`[0-9]+\.[0-9]+(\.[0-9]+)?`)
		version := "v" + string(versionRegexp.Find([]byte(sb.String())))
		if !semver.IsValid(version) {
			unameErr = fmt.Errorf("invalid version found in release %q", sb.String())
			return
		}
		semVersion.version = version
	})

	return semVersion, unameErr
}