github.com/mizzy/docker@v1.5.0/pkg/parsers/kernel/kernel.go (about) 1 package kernel 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 ) 8 9 type KernelVersionInfo struct { 10 Kernel int 11 Major int 12 Minor int 13 Flavor string 14 } 15 16 func (k *KernelVersionInfo) String() string { 17 return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor) 18 } 19 20 // Compare two KernelVersionInfo struct. 21 // Returns -1 if a < b, 0 if a == b, 1 it a > b 22 func CompareKernelVersion(a, b *KernelVersionInfo) int { 23 if a.Kernel < b.Kernel { 24 return -1 25 } else if a.Kernel > b.Kernel { 26 return 1 27 } 28 29 if a.Major < b.Major { 30 return -1 31 } else if a.Major > b.Major { 32 return 1 33 } 34 35 if a.Minor < b.Minor { 36 return -1 37 } else if a.Minor > b.Minor { 38 return 1 39 } 40 41 return 0 42 } 43 44 func GetKernelVersion() (*KernelVersionInfo, error) { 45 var ( 46 err error 47 ) 48 49 uts, err := uname() 50 if err != nil { 51 return nil, err 52 } 53 54 release := make([]byte, len(uts.Release)) 55 56 i := 0 57 for _, c := range uts.Release { 58 release[i] = byte(c) 59 i++ 60 } 61 62 // Remove the \x00 from the release for Atoi to parse correctly 63 release = release[:bytes.IndexByte(release, 0)] 64 65 return ParseRelease(string(release)) 66 } 67 68 func ParseRelease(release string) (*KernelVersionInfo, error) { 69 var ( 70 kernel, major, minor, parsed int 71 flavor, partial string 72 ) 73 74 // Ignore error from Sscanf to allow an empty flavor. Instead, just 75 // make sure we got all the version numbers. 76 parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial) 77 if parsed < 2 { 78 return nil, errors.New("Can't parse kernel version " + release) 79 } 80 81 // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64 82 parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor) 83 if parsed < 1 { 84 flavor = partial 85 } 86 87 return &KernelVersionInfo{ 88 Kernel: kernel, 89 Major: major, 90 Minor: minor, 91 Flavor: flavor, 92 }, nil 93 }