Debian Codegraph @

pkg/parsers/kernel/kernel.go

raw
1 //go:build !windows
2
3 // Package kernel provides helper function to get, parse and compare kernel
4 // versions for different platforms.
5 package kernel
6
7 import (
8 "errors"
9 "fmt"
10
11 "github.com/sirupsen/logrus"
12 )
13
14 // VersionInfo holds information about the kernel.
15 type VersionInfo struct {
16 Kernel int // Version of the kernel (e.g. 4.1.2-generic -> 4)
17 Major int // Major part of the kernel version (e.g. 4.1.2-generic -> 1)
18 Minor int // Minor part of the kernel version (e.g. 4.1.2-generic -> 2)
19 Flavor string // Flavor of the kernel version (e.g. 4.1.2-generic -> generic)
20 }
21
22 func (k *VersionInfo) String() string {
23 return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor)
24 }
25
26 // CompareKernelVersion compares two kernel.VersionInfo structs.
27 // Returns -1 if a < b, 0 if a == b, 1 it a > b
28 func CompareKernelVersion(a, b VersionInfo) int {
29 if a.Kernel < b.Kernel {
30 return -1
31 } else if a.Kernel > b.Kernel {
32 return 1
33 }
34
35 if a.Major < b.Major {
36 return -1
37 } else if a.Major > b.Major {
38 return 1
39 }
40
41 if a.Minor < b.Minor {
42 return -1
43 } else if a.Minor > b.Minor {
44 return 1
45 }
46
47 return 0
48 }
49
50 // CheckKernelVersion checks if current kernel is newer than (or equal to)
51 // the given version.
52 func CheckKernelVersion(k, major, minor int) bool {
53 if v, err := GetKernelVersion(); err != nil {
54 logrus.Warnf("Error getting kernel version: %s", err)
55 } else {
56 if CompareKernelVersion(*v, VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
57 return false
58 }
59 }
60 return true
61 }
62
63 // ParseRelease parses a string and creates a VersionInfo based on it.
64 func ParseRelease(release string) (*VersionInfo, error) {
65 var (
66 kernel, major, minor, parsed int
67 flavor, partial string
68 )
69
70 // Ignore error from Sscanf to allow an empty flavor. Instead, just
71 // make sure we got all the version numbers.
72 parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
73 if parsed < 2 {
74 return nil, errors.New("Can't parse kernel version " + release)
75 }
76
77 // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
78 parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
79 if parsed < 1 {
80 flavor = partial
81 }
82
83 return &VersionInfo{
84 Kernel: kernel,
85 Major: major,
86 Minor: minor,
87 Flavor: flavor,
88 }, nil
89 }