github.com/olljanat/moby@v1.13.1/pkg/aaparser/aaparser.go (about) 1 // Package aaparser is a convenience package interacting with `apparmor_parser`. 2 package aaparser 3 4 import ( 5 "fmt" 6 "os/exec" 7 "strconv" 8 "strings" 9 ) 10 11 const ( 12 binary = "apparmor_parser" 13 ) 14 15 // GetVersion returns the major and minor version of apparmor_parser. 16 func GetVersion() (int, error) { 17 output, err := cmd("", "--version") 18 if err != nil { 19 return -1, err 20 } 21 22 return parseVersion(output) 23 } 24 25 // LoadProfile runs `apparmor_parser -r` on a specified apparmor profile to 26 // replace the profile. 27 func LoadProfile(profilePath string) error { 28 _, err := cmd("", "-r", profilePath) 29 if err != nil { 30 return err 31 } 32 return nil 33 } 34 35 // cmd runs `apparmor_parser` with the passed arguments. 36 func cmd(dir string, arg ...string) (string, error) { 37 c := exec.Command(binary, arg...) 38 c.Dir = dir 39 40 output, err := c.CombinedOutput() 41 if err != nil { 42 return "", fmt.Errorf("running `%s %s` failed with output: %s\nerror: %v", c.Path, strings.Join(c.Args, " "), string(output), err) 43 } 44 45 return string(output), nil 46 } 47 48 // parseVersion takes the output from `apparmor_parser --version` and returns 49 // a representation of the {major, minor, patch} version as a single number of 50 // the form MMmmPPP {major, minor, patch}. 51 func parseVersion(output string) (int, error) { 52 // output is in the form of the following: 53 // AppArmor parser version 2.9.1 54 // Copyright (C) 1999-2008 Novell Inc. 55 // Copyright 2009-2012 Canonical Ltd. 56 57 lines := strings.SplitN(output, "\n", 2) 58 words := strings.Split(lines[0], " ") 59 version := words[len(words)-1] 60 61 // split by major minor version 62 v := strings.Split(version, ".") 63 if len(v) == 0 || len(v) > 3 { 64 return -1, fmt.Errorf("parsing version failed for output: `%s`", output) 65 } 66 67 // Default the versions to 0. 68 var majorVersion, minorVersion, patchLevel int 69 70 majorVersion, err := strconv.Atoi(v[0]) 71 if err != nil { 72 return -1, err 73 } 74 75 if len(v) > 1 { 76 minorVersion, err = strconv.Atoi(v[1]) 77 if err != nil { 78 return -1, err 79 } 80 } 81 if len(v) > 2 { 82 patchLevel, err = strconv.Atoi(v[2]) 83 if err != nil { 84 return -1, err 85 } 86 } 87 88 // major*10^5 + minor*10^3 + patch*10^0 89 numericVersion := majorVersion*1e5 + minorVersion*1e3 + patchLevel 90 return numericVersion, nil 91 }