github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/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 return err 30 } 31 32 // cmd runs `apparmor_parser` with the passed arguments. 33 func cmd(dir string, arg ...string) (string, error) { 34 c := exec.Command(binary, arg...) 35 c.Dir = dir 36 37 output, err := c.CombinedOutput() 38 if err != nil { 39 return "", fmt.Errorf("running `%s %s` failed with output: %s\nerror: %v", c.Path, strings.Join(c.Args, " "), output, err) 40 } 41 42 return string(output), nil 43 } 44 45 // parseVersion takes the output from `apparmor_parser --version` and returns 46 // a representation of the {major, minor, patch} version as a single number of 47 // the form MMmmPPP {major, minor, patch}. 48 func parseVersion(output string) (int, error) { 49 // output is in the form of the following: 50 // AppArmor parser version 2.9.1 51 // Copyright (C) 1999-2008 Novell Inc. 52 // Copyright 2009-2012 Canonical Ltd. 53 54 lines := strings.SplitN(output, "\n", 2) 55 words := strings.Split(lines[0], " ") 56 version := words[len(words)-1] 57 58 // split by major minor version 59 v := strings.Split(version, ".") 60 if len(v) == 0 || len(v) > 3 { 61 return -1, fmt.Errorf("parsing version failed for output: `%s`", output) 62 } 63 64 // Default the versions to 0. 65 var majorVersion, minorVersion, patchLevel int 66 67 majorVersion, err := strconv.Atoi(v[0]) 68 if err != nil { 69 return -1, err 70 } 71 72 if len(v) > 1 { 73 minorVersion, err = strconv.Atoi(v[1]) 74 if err != nil { 75 return -1, err 76 } 77 } 78 if len(v) > 2 { 79 patchLevel, err = strconv.Atoi(v[2]) 80 if err != nil { 81 return -1, err 82 } 83 } 84 85 // major*10^5 + minor*10^3 + patch*10^0 86 numericVersion := majorVersion*1e5 + minorVersion*1e3 + patchLevel 87 return numericVersion, nil 88 }